aoptx86.pas 750 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  181. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  182. function TrySwapMovOp(var p, hp1: tai): Boolean;
  183. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  184. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  185. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  186. { Processor-dependent reference optimisation }
  187. class procedure OptimizeRefs(var p: taicpu); static;
  188. end;
  189. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  190. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  193. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  194. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  195. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  196. {$if max_operands>2}
  197. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  198. {$endif max_operands>2}
  199. function RefsEqual(const r1, r2: treference): boolean;
  200. { Like RefsEqual, but doesn't compare the offsets }
  201. function RefsAlmostEqual(const r1, r2: treference): boolean;
  202. { Note that Result is set to True if the references COULD overlap but the
  203. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  204. might still overlap because %reg2 could be equal to %reg1-4 }
  205. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  206. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  207. { returns true, if ref is a reference using only the registers passed as base and index
  208. and having an offset }
  209. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  210. implementation
  211. uses
  212. cutils,verbose,
  213. systems,
  214. globals,
  215. cpuinfo,
  216. procinfo,
  217. paramgr,
  218. aasmbase,
  219. aoptbase,aoptutils,
  220. symconst,symsym,
  221. cgx86,
  222. itcpugas;
  223. {$ifndef 8086}
  224. const
  225. MAX_CMOV_INSTRUCTIONS = 4;
  226. MAX_CMOV_REGISTERS = 8;
  227. type
  228. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  229. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  230. tsProcessed);
  231. { For OptPass2Jcc }
  232. TCMOVTracking = object
  233. private
  234. CMOVScore, ConstCount: LongInt;
  235. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  236. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  237. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  238. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  239. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  240. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  241. fOptimizer: TX86AsmOptimizer;
  242. fLabel: TAsmSymbol;
  243. fInsertionPoint,
  244. fCondition,
  245. fInitialJump,
  246. fFirstMovBlock,
  247. fFirstMovBlockStop,
  248. fSecondJump,
  249. fThirdJump,
  250. fSecondMovBlock,
  251. fSecondMovBlockStop,
  252. fMidLabel,
  253. fEndLabel,
  254. fAllocationRange: tai;
  255. fState: TCMovTrackingState;
  256. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  257. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  258. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  259. public
  260. RegisterTracking: TAllUsedRegs;
  261. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  262. destructor Done;
  263. procedure Process(out new_p: tai);
  264. property State: TCMovTrackingState read fState;
  265. end;
  266. PCMOVTracking = ^TCMOVTracking;
  267. {$endif 8086}
  268. {$ifdef DEBUG_AOPTCPU}
  269. const
  270. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  271. {$else DEBUG_AOPTCPU}
  272. { Empty strings help the optimizer to remove string concatenations that won't
  273. ever appear to the user on release builds. [Kit] }
  274. const
  275. SPeepholeOptimization = '';
  276. {$endif DEBUG_AOPTCPU}
  277. LIST_STEP_SIZE = 4;
  278. type
  279. TJumpTrackingItem = class(TLinkedListItem)
  280. private
  281. FSymbol: TAsmSymbol;
  282. FRefs: LongInt;
  283. public
  284. constructor Create(ASymbol: TAsmSymbol);
  285. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. property Symbol: TAsmSymbol read FSymbol;
  287. property Refs: LongInt read FRefs;
  288. end;
  289. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  290. begin
  291. inherited Create;
  292. FSymbol := ASymbol;
  293. FRefs := 0;
  294. end;
  295. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  296. begin
  297. Inc(FRefs);
  298. end;
  299. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  300. begin
  301. result :=
  302. (instr.typ = ait_instruction) and
  303. (taicpu(instr).opcode = op) and
  304. ((opsize = []) or (taicpu(instr).opsize in opsize));
  305. end;
  306. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  307. begin
  308. result :=
  309. (instr.typ = ait_instruction) and
  310. ((taicpu(instr).opcode = op1) or
  311. (taicpu(instr).opcode = op2)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  316. begin
  317. result :=
  318. (instr.typ = ait_instruction) and
  319. ((taicpu(instr).opcode = op1) or
  320. (taicpu(instr).opcode = op2) or
  321. (taicpu(instr).opcode = op3)
  322. ) and
  323. ((opsize = []) or (taicpu(instr).opsize in opsize));
  324. end;
  325. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  326. const opsize : topsizes) : boolean;
  327. var
  328. op : TAsmOp;
  329. begin
  330. result:=false;
  331. if (instr.typ <> ait_instruction) or
  332. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  333. exit;
  334. for op in ops do
  335. begin
  336. if taicpu(instr).opcode = op then
  337. begin
  338. result:=true;
  339. exit;
  340. end;
  341. end;
  342. end;
  343. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  344. begin
  345. result := (oper.typ = top_reg) and (oper.reg = reg);
  346. end;
  347. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  348. begin
  349. result := (oper.typ = top_const) and (oper.val = a);
  350. end;
  351. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  352. begin
  353. result := oper1.typ = oper2.typ;
  354. if result then
  355. case oper1.typ of
  356. top_const:
  357. Result:=oper1.val = oper2.val;
  358. top_reg:
  359. Result:=oper1.reg = oper2.reg;
  360. top_ref:
  361. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  362. else
  363. internalerror(2013102801);
  364. end
  365. end;
  366. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  367. begin
  368. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  369. if result then
  370. case oper1.typ of
  371. top_const:
  372. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  373. top_reg:
  374. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  375. top_ref:
  376. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  377. else
  378. internalerror(2020052401);
  379. end
  380. end;
  381. function RefsEqual(const r1, r2: treference): boolean;
  382. begin
  383. RefsEqual :=
  384. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  385. (r1.relsymbol = r2.relsymbol) and
  386. (r1.segment = r2.segment) and (r1.base = r2.base) and
  387. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  388. (r1.offset = r2.offset) and
  389. (r1.volatility + r2.volatility = []);
  390. end;
  391. function RefsAlmostEqual(const r1, r2: treference): boolean;
  392. begin
  393. RefsAlmostEqual :=
  394. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  395. (r1.relsymbol = r2.relsymbol) and
  396. (r1.segment = r2.segment) and (r1.base = r2.base) and
  397. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  398. { Don't compare the offsets }
  399. (r1.volatility + r2.volatility = []);
  400. end;
  401. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  402. begin
  403. if (r1.symbol<>r2.symbol) then
  404. { If the index registers are different, there's a chance one could
  405. be set so it equals the other symbol }
  406. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  407. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. (r1.volatility + r2.volatility = []) then
  412. { In this case, it all depends on the offsets }
  413. Exit(abs(r1.offset - r2.offset) < Range);
  414. { There's a chance things MIGHT overlap, so take no chances }
  415. Result := True;
  416. end;
  417. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  418. begin
  419. Result:=(ref.offset=0) and
  420. (ref.scalefactor in [0,1]) and
  421. (ref.segment=NR_NO) and
  422. (ref.symbol=nil) and
  423. (ref.relsymbol=nil) and
  424. ((base=NR_INVALID) or
  425. (ref.base=base)) and
  426. ((index=NR_INVALID) or
  427. (ref.index=index)) and
  428. (ref.volatility=[]);
  429. end;
  430. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.scalefactor in [0,1]) and
  433. (ref.segment=NR_NO) and
  434. (ref.symbol=nil) and
  435. (ref.relsymbol=nil) and
  436. ((base=NR_INVALID) or
  437. (ref.base=base)) and
  438. ((index=NR_INVALID) or
  439. (ref.index=index)) and
  440. (ref.volatility=[]);
  441. end;
  442. function InstrReadsFlags(p: tai): boolean;
  443. begin
  444. InstrReadsFlags := true;
  445. case p.typ of
  446. ait_instruction:
  447. if InsProp[taicpu(p).opcode].Ch*
  448. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  449. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  450. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  451. exit;
  452. ait_label:
  453. exit;
  454. else
  455. ;
  456. end;
  457. InstrReadsFlags := false;
  458. end;
  459. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  460. begin
  461. Next:=Current;
  462. repeat
  463. Result:=GetNextInstruction(Next,Next);
  464. until not (Result) or
  465. not(cs_opt_level3 in current_settings.optimizerswitches) or
  466. (Next.typ<>ait_instruction) or
  467. RegInInstruction(reg,Next) or
  468. is_calljmp(taicpu(Next).opcode);
  469. end;
  470. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  471. var
  472. GetNextResult: Boolean;
  473. begin
  474. Result:=0;
  475. Next:=Current;
  476. repeat
  477. GetNextResult := GetNextInstruction(Next,Next);
  478. if GetNextResult then
  479. Inc(Result)
  480. else
  481. { Must return zero upon hitting the end of the linked list without a match }
  482. Result := 0;
  483. until not (GetNextResult) or
  484. not(cs_opt_level3 in current_settings.optimizerswitches) or
  485. (Next.typ<>ait_instruction) or
  486. RegInInstruction(reg,Next) or
  487. is_calljmp(taicpu(Next).opcode);
  488. end;
  489. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  490. procedure TrackJump(Symbol: TAsmSymbol);
  491. var
  492. Search: TJumpTrackingItem;
  493. begin
  494. { See if an entry already exists in our jump tracking list
  495. (faster to search backwards due to the higher chance of
  496. matching destinations) }
  497. Search := TJumpTrackingItem(JumpTracking.Last);
  498. while Assigned(Search) do
  499. begin
  500. if Search.Symbol = Symbol then
  501. begin
  502. { Found it - remove it so it can be pushed to the front }
  503. JumpTracking.Remove(Search);
  504. Break;
  505. end;
  506. Search := TJumpTrackingItem(Search.Previous);
  507. end;
  508. if not Assigned(Search) then
  509. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  510. JumpTracking.Concat(Search);
  511. Search.IncRefs;
  512. end;
  513. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  514. var
  515. Search: TJumpTrackingItem;
  516. begin
  517. Result := False;
  518. { See if this label appears in the tracking list }
  519. Search := TJumpTrackingItem(JumpTracking.Last);
  520. while Assigned(Search) do
  521. begin
  522. if Search.Symbol = Symbol then
  523. begin
  524. { Found it - let's see what we can discover }
  525. if Search.Symbol.getrefs = Search.Refs then
  526. begin
  527. { Success - all the references are accounted for }
  528. JumpTracking.Remove(Search);
  529. Search.Free;
  530. { It is logically impossible for CrossJump to be false here
  531. because we must have run into a conditional jump for
  532. this label at some point }
  533. if not CrossJump then
  534. InternalError(2022041710);
  535. if JumpTracking.First = nil then
  536. { Tracking list is now empty - no more cross jumps }
  537. CrossJump := False;
  538. Result := True;
  539. Exit;
  540. end;
  541. { If the references don't match, it's possible to enter
  542. this label through other means, so drop out }
  543. Exit;
  544. end;
  545. Search := TJumpTrackingItem(Search.Previous);
  546. end;
  547. end;
  548. var
  549. Next_Label: tai;
  550. begin
  551. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  552. Next := Current;
  553. repeat
  554. Result := GetNextInstruction(Next,Next);
  555. if not Result then
  556. Break;
  557. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  558. if is_calljmpuncondret(taicpu(Next).opcode) then
  559. begin
  560. if (taicpu(Next).opcode = A_JMP) and
  561. { Remove dead code now to save time }
  562. RemoveDeadCodeAfterJump(taicpu(Next)) then
  563. { A jump was removed, but not the current instruction, and
  564. Result doesn't necessarily translate into an optimisation
  565. routine's Result, so use the "Force New Iteration" flag so
  566. mark a new pass }
  567. Include(OptsToCheck, aoc_ForceNewIteration);
  568. if not Assigned(JumpTracking) then
  569. begin
  570. { Cross-label optimisations often causes other optimisations
  571. to perform worse because they're not given the chance to
  572. optimise locally. In this case, don't do the cross-label
  573. optimisations yet, but flag them as a potential possibility
  574. for the next iteration of Pass 1 }
  575. if not NotFirstIteration then
  576. Include(OptsToCheck, aoc_ForceNewIteration);
  577. end
  578. else if IsJumpToLabel(taicpu(Next)) and
  579. GetNextInstruction(Next, Next_Label) then
  580. begin
  581. { If we have JMP .lbl, and the label after it has all of its
  582. references tracked, then this is probably an if-else style of
  583. block and we can keep tracking. If the label for this jump
  584. then appears later and is fully tracked, then it's the end
  585. of the if-else blocks and the code paths converge (thus
  586. marking the end of the cross-jump) }
  587. if (Next_Label.typ = ait_label) then
  588. begin
  589. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  590. begin
  591. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  592. Next := Next_Label;
  593. { CrossJump gets set to false by LabelAccountedFor if the
  594. list is completely emptied (as it indicates that all
  595. code paths have converged). We could avoid this nuance
  596. by moving the TrackJump call to before the
  597. LabelAccountedFor call, but this is slower in situations
  598. where LabelAccountedFor would return False due to the
  599. creation of a new object that is not used and destroyed
  600. soon after. }
  601. CrossJump := True;
  602. Continue;
  603. end;
  604. end
  605. else if (Next_Label.typ <> ait_marker) then
  606. { We just did a RemoveDeadCodeAfterJump, so either we find
  607. a label, the end of the procedure or some kind of marker}
  608. InternalError(2022041720);
  609. end;
  610. Result := False;
  611. Exit;
  612. end
  613. else
  614. begin
  615. if not Assigned(JumpTracking) then
  616. begin
  617. { Cross-label optimisations often causes other optimisations
  618. to perform worse because they're not given the chance to
  619. optimise locally. In this case, don't do the cross-label
  620. optimisations yet, but flag them as a potential possibility
  621. for the next iteration of Pass 1 }
  622. if not NotFirstIteration then
  623. Include(OptsToCheck, aoc_ForceNewIteration);
  624. end
  625. else if IsJumpToLabel(taicpu(Next)) then
  626. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  627. else
  628. { Conditional jumps should always be a jump to label }
  629. InternalError(2022041701);
  630. CrossJump := True;
  631. Continue;
  632. end;
  633. if Next.typ = ait_label then
  634. begin
  635. if not Assigned(JumpTracking) then
  636. begin
  637. { Cross-label optimisations often causes other optimisations
  638. to perform worse because they're not given the chance to
  639. optimise locally. In this case, don't do the cross-label
  640. optimisations yet, but flag them as a potential possibility
  641. for the next iteration of Pass 1 }
  642. if not NotFirstIteration then
  643. Include(OptsToCheck, aoc_ForceNewIteration);
  644. end
  645. else if LabelAccountedFor(tai_label(Next).labsym) then
  646. Continue;
  647. { If we reach here, we're at a label that hasn't been seen before
  648. (or JumpTracking was nil) }
  649. Break;
  650. end;
  651. until not Result or
  652. not (cs_opt_level3 in current_settings.optimizerswitches) or
  653. not (Next.typ in [ait_label, ait_instruction]) or
  654. RegInInstruction(reg,Next);
  655. end;
  656. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  657. begin
  658. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  659. begin
  660. Result:=GetNextInstruction(Current,Next);
  661. exit;
  662. end;
  663. Next:=tai(Current.Next);
  664. Result:=false;
  665. while assigned(Next) do
  666. begin
  667. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  668. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  669. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  670. exit
  671. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  672. begin
  673. Result:=true;
  674. exit;
  675. end;
  676. Next:=tai(Next.Next);
  677. end;
  678. end;
  679. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  680. begin
  681. Result:=RegReadByInstruction(reg,hp);
  682. end;
  683. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  684. var
  685. p: taicpu;
  686. opcount: longint;
  687. begin
  688. RegReadByInstruction := false;
  689. if hp.typ <> ait_instruction then
  690. exit;
  691. p := taicpu(hp);
  692. case p.opcode of
  693. A_CALL:
  694. regreadbyinstruction := true;
  695. A_IMUL:
  696. case p.ops of
  697. 1:
  698. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  699. (
  700. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  701. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  702. );
  703. 2,3:
  704. regReadByInstruction :=
  705. reginop(reg,p.oper[0]^) or
  706. reginop(reg,p.oper[1]^);
  707. else
  708. InternalError(2019112801);
  709. end;
  710. A_MUL:
  711. begin
  712. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  713. (
  714. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  715. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  716. );
  717. end;
  718. A_IDIV,A_DIV:
  719. begin
  720. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  721. (
  722. (getregtype(reg)=R_INTREGISTER) and
  723. (
  724. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  725. )
  726. );
  727. end;
  728. else
  729. begin
  730. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  731. begin
  732. RegReadByInstruction := false;
  733. exit;
  734. end;
  735. for opcount := 0 to p.ops-1 do
  736. if (p.oper[opCount]^.typ = top_ref) and
  737. RegInRef(reg,p.oper[opcount]^.ref^) then
  738. begin
  739. RegReadByInstruction := true;
  740. exit
  741. end;
  742. { special handling for SSE MOVSD }
  743. if (p.opcode=A_MOVSD) and (p.ops>0) then
  744. begin
  745. if p.ops<>2 then
  746. internalerror(2017042702);
  747. regReadByInstruction := reginop(reg,p.oper[0]^) or
  748. (
  749. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  750. );
  751. exit;
  752. end;
  753. with insprop[p.opcode] do
  754. begin
  755. case getregtype(reg) of
  756. R_INTREGISTER:
  757. begin
  758. case getsupreg(reg) of
  759. RS_EAX:
  760. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ECX:
  766. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EDX:
  772. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_EBX:
  778. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_ESP:
  784. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. RS_EBP:
  790. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  791. begin
  792. RegReadByInstruction := true;
  793. exit
  794. end;
  795. RS_ESI:
  796. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  797. begin
  798. RegReadByInstruction := true;
  799. exit
  800. end;
  801. RS_EDI:
  802. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. end;
  808. end;
  809. R_MMREGISTER:
  810. begin
  811. case getsupreg(reg) of
  812. RS_XMM0:
  813. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  814. begin
  815. RegReadByInstruction := true;
  816. exit
  817. end;
  818. end;
  819. end;
  820. else
  821. ;
  822. end;
  823. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  824. begin
  825. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  826. begin
  827. case p.condition of
  828. C_A,C_NBE, { CF=0 and ZF=0 }
  829. C_BE,C_NA: { CF=1 or ZF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  831. C_AE,C_NB,C_NC, { CF=0 }
  832. C_B,C_NAE,C_C: { CF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  834. C_NE,C_NZ, { ZF=0 }
  835. C_E,C_Z: { ZF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  837. C_G,C_NLE, { ZF=0 and SF=OF }
  838. C_LE,C_NG: { ZF=1 or SF<>OF }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  840. C_GE,C_NL, { SF=OF }
  841. C_L,C_NGE: { SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_NO, { OF=0 }
  844. C_O: { OF=1 }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  846. C_NP,C_PO, { PF=0 }
  847. C_P,C_PE: { PF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  849. C_NS, { SF=0 }
  850. C_S: { SF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  852. else
  853. internalerror(2017042701);
  854. end;
  855. if RegReadByInstruction then
  856. exit;
  857. end;
  858. case getsubreg(reg) of
  859. R_SUBW,R_SUBD,R_SUBQ:
  860. RegReadByInstruction :=
  861. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  862. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  863. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  864. R_SUBFLAGCARRY:
  865. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  866. R_SUBFLAGPARITY:
  867. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGAUXILIARY:
  869. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGZERO:
  871. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGSIGN:
  873. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGOVERFLOW:
  875. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGINTERRUPT:
  877. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGDIRECTION:
  879. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. else
  881. internalerror(2017042601);
  882. end;
  883. exit;
  884. end;
  885. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  886. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  887. (p.oper[0]^.reg=p.oper[1]^.reg) then
  888. exit;
  889. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  890. begin
  891. RegReadByInstruction := true;
  892. exit
  893. end;
  894. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  895. begin
  896. RegReadByInstruction := true;
  897. exit
  898. end;
  899. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  900. begin
  901. RegReadByInstruction := true;
  902. exit
  903. end;
  904. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  905. begin
  906. RegReadByInstruction := true;
  907. exit
  908. end;
  909. end;
  910. end;
  911. end;
  912. end;
  913. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  914. begin
  915. result:=false;
  916. if p1.typ<>ait_instruction then
  917. exit;
  918. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  919. exit(true);
  920. if (getregtype(reg)=R_INTREGISTER) and
  921. { change information for xmm movsd are not correct }
  922. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  923. begin
  924. { Handle instructions that behave differently depending on the size and operand count }
  925. case taicpu(p1).opcode of
  926. A_MUL, A_DIV, A_IDIV:
  927. if taicpu(p1).opsize = S_B then
  928. Result := (getsupreg(Reg) = RS_EAX)
  929. else
  930. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  931. A_IMUL:
  932. if taicpu(p1).ops = 1 then
  933. begin
  934. if taicpu(p1).opsize = S_B then
  935. Result := (getsupreg(Reg) = RS_EAX)
  936. else
  937. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  938. end;
  939. { If ops are greater than 1, call inherited method }
  940. else
  941. case getsupreg(reg) of
  942. { RS_EAX = RS_RAX on x86-64 }
  943. RS_EAX:
  944. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. RS_ECX:
  946. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_EDX:
  948. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EBX:
  950. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_ESP:
  952. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_EBP:
  954. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_ESI:
  956. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_EDI:
  958. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. else
  960. ;
  961. end;
  962. end;
  963. if result then
  964. exit;
  965. end
  966. else if getregtype(reg)=R_MMREGISTER then
  967. begin
  968. case getsupreg(reg) of
  969. RS_XMM0:
  970. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  971. else
  972. ;
  973. end;
  974. if result then
  975. exit;
  976. end
  977. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  978. begin
  979. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  980. exit(true);
  981. case getsubreg(reg) of
  982. R_SUBFLAGCARRY:
  983. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. R_SUBFLAGPARITY:
  985. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGAUXILIARY:
  987. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGZERO:
  989. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGSIGN:
  991. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGOVERFLOW:
  993. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGINTERRUPT:
  995. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGDIRECTION:
  997. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBW,R_SUBD,R_SUBQ:
  999. { Everything except the direction bits }
  1000. Result:=
  1001. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1002. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1003. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1004. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1005. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1006. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1007. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1008. else
  1009. ;
  1010. end;
  1011. if result then
  1012. exit;
  1013. end
  1014. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1015. exit(true);
  1016. Result:=inherited RegInInstruction(Reg, p1);
  1017. end;
  1018. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1019. const
  1020. WriteOps: array[0..3] of set of TInsChange =
  1021. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1022. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1023. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1024. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1025. var
  1026. OperIdx: Integer;
  1027. begin
  1028. Result := False;
  1029. if p1.typ <> ait_instruction then
  1030. exit;
  1031. with insprop[taicpu(p1).opcode] do
  1032. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1033. begin
  1034. case getsubreg(reg) of
  1035. R_SUBW,R_SUBD,R_SUBQ:
  1036. Result :=
  1037. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1038. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1039. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1040. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1041. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1042. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. R_SUBFLAGCARRY:
  1044. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGPARITY:
  1046. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGAUXILIARY:
  1048. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGZERO:
  1050. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGSIGN:
  1052. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGOVERFLOW:
  1054. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGINTERRUPT:
  1056. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGDIRECTION:
  1058. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. else
  1060. internalerror(2017042602);
  1061. end;
  1062. exit;
  1063. end;
  1064. case taicpu(p1).opcode of
  1065. A_CALL:
  1066. { We could potentially set Result to False if the register in
  1067. question is non-volatile for the subroutine's calling convention,
  1068. but this would require detecting the calling convention in use and
  1069. also assuming that the routine doesn't contain malformed assembly
  1070. language, for example... so it could only be done under -O4 as it
  1071. would be considered a side-effect. [Kit] }
  1072. Result := True;
  1073. A_MOVSD:
  1074. { special handling for SSE MOVSD }
  1075. if (taicpu(p1).ops>0) then
  1076. begin
  1077. if taicpu(p1).ops<>2 then
  1078. internalerror(2017042703);
  1079. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1080. end;
  1081. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1082. so fix it here (FK)
  1083. }
  1084. A_VMOVSS,
  1085. A_VMOVSD:
  1086. begin
  1087. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1088. exit;
  1089. end;
  1090. A_MUL, A_DIV, A_IDIV:
  1091. begin
  1092. if taicpu(p1).opsize = S_B then
  1093. Result := (getsupreg(Reg) = RS_EAX)
  1094. else
  1095. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1096. end;
  1097. A_IMUL:
  1098. begin
  1099. if taicpu(p1).ops = 1 then
  1100. begin
  1101. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1102. end
  1103. else
  1104. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1105. Exit;
  1106. end;
  1107. else
  1108. ;
  1109. end;
  1110. if Result then
  1111. exit;
  1112. with insprop[taicpu(p1).opcode] do
  1113. begin
  1114. if getregtype(reg)=R_INTREGISTER then
  1115. begin
  1116. case getsupreg(reg) of
  1117. RS_EAX:
  1118. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ECX:
  1124. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EDX:
  1130. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_EBX:
  1136. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_ESP:
  1142. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. RS_EBP:
  1148. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1149. begin
  1150. Result := True;
  1151. exit
  1152. end;
  1153. RS_ESI:
  1154. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1155. begin
  1156. Result := True;
  1157. exit
  1158. end;
  1159. RS_EDI:
  1160. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1161. begin
  1162. Result := True;
  1163. exit
  1164. end;
  1165. end;
  1166. end;
  1167. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1168. if (WriteOps[OperIdx]*Ch<>[]) and
  1169. { The register doesn't get modified inside a reference }
  1170. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1171. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1172. begin
  1173. Result := true;
  1174. exit
  1175. end;
  1176. end;
  1177. end;
  1178. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1179. const
  1180. WriteOps: array[0..3] of set of TInsChange =
  1181. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1182. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1183. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1184. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1185. var
  1186. X: Integer;
  1187. CurrentP1Size: asizeint;
  1188. begin
  1189. Result := (
  1190. (Ref.base <> NR_NO) and
  1191. {$ifdef x86_64}
  1192. (Ref.base <> NR_RIP) and
  1193. {$endif x86_64}
  1194. RegModifiedBetween(Ref.base, p1, p2)
  1195. ) or
  1196. (
  1197. (Ref.index <> NR_NO) and
  1198. (Ref.index <> Ref.base) and
  1199. RegModifiedBetween(Ref.index, p1, p2)
  1200. );
  1201. { Now check to see if the memory itself is written to }
  1202. if not Result then
  1203. begin
  1204. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1205. if p1.typ = ait_instruction then
  1206. begin
  1207. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1208. with insprop[taicpu(p1).opcode] do
  1209. for X := 0 to taicpu(p1).ops - 1 do
  1210. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1211. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1212. { Catch any potential overlaps }
  1213. (
  1214. (RefSize = 0) or
  1215. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1216. ) and
  1217. (
  1218. (CurrentP1Size = 0) or
  1219. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1220. ) and
  1221. { Reference is used, but does the instruction write to it? }
  1222. (
  1223. (Ch_All in Ch) or
  1224. ((WriteOps[X] * Ch) <> [])
  1225. ) then
  1226. begin
  1227. Result := True;
  1228. Break;
  1229. end;
  1230. end;
  1231. end;
  1232. end;
  1233. {$ifdef DEBUG_AOPTCPU}
  1234. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1235. begin
  1236. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1237. end;
  1238. function debug_tostr(i: tcgint): string; inline;
  1239. begin
  1240. Result := tostr(i);
  1241. end;
  1242. function debug_hexstr(i: tcgint): string;
  1243. begin
  1244. Result := '0x';
  1245. case i of
  1246. 0..$FF:
  1247. Result := Result + hexstr(i, 2);
  1248. $100..$FFFF:
  1249. Result := Result + hexstr(i, 4);
  1250. $10000..$FFFFFF:
  1251. Result := Result + hexstr(i, 6);
  1252. $1000000..$FFFFFFFF:
  1253. Result := Result + hexstr(i, 8);
  1254. else
  1255. Result := Result + hexstr(i, 16);
  1256. end;
  1257. end;
  1258. function debug_regname(r: TRegister): string; inline;
  1259. begin
  1260. Result := '%' + std_regname(r);
  1261. end;
  1262. { Debug output function - creates a string representation of an operator }
  1263. function debug_operstr(oper: TOper): string;
  1264. begin
  1265. case oper.typ of
  1266. top_const:
  1267. Result := '$' + debug_tostr(oper.val);
  1268. top_reg:
  1269. Result := debug_regname(oper.reg);
  1270. top_ref:
  1271. begin
  1272. if oper.ref^.offset <> 0 then
  1273. Result := debug_tostr(oper.ref^.offset) + '('
  1274. else
  1275. Result := '(';
  1276. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1277. begin
  1278. Result := Result + debug_regname(oper.ref^.base);
  1279. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1280. Result := Result + ',' + debug_regname(oper.ref^.index);
  1281. end
  1282. else
  1283. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1284. Result := Result + debug_regname(oper.ref^.index);
  1285. if (oper.ref^.scalefactor > 1) then
  1286. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1287. else
  1288. Result := Result + ')';
  1289. end;
  1290. else
  1291. Result := '[UNKNOWN]';
  1292. end;
  1293. end;
  1294. function debug_op2str(opcode: tasmop): string; inline;
  1295. begin
  1296. Result := std_op2str[opcode];
  1297. end;
  1298. function debug_opsize2str(opsize: topsize): string; inline;
  1299. begin
  1300. Result := gas_opsize2str[opsize];
  1301. end;
  1302. {$else DEBUG_AOPTCPU}
  1303. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1304. begin
  1305. end;
  1306. function debug_tostr(i: tcgint): string; inline;
  1307. begin
  1308. Result := '';
  1309. end;
  1310. function debug_hexstr(i: tcgint): string; inline;
  1311. begin
  1312. Result := '';
  1313. end;
  1314. function debug_regname(r: TRegister): string; inline;
  1315. begin
  1316. Result := '';
  1317. end;
  1318. function debug_operstr(oper: TOper): string; inline;
  1319. begin
  1320. Result := '';
  1321. end;
  1322. function debug_op2str(opcode: tasmop): string; inline;
  1323. begin
  1324. Result := '';
  1325. end;
  1326. function debug_opsize2str(opsize: topsize): string; inline;
  1327. begin
  1328. Result := '';
  1329. end;
  1330. {$endif DEBUG_AOPTCPU}
  1331. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1332. begin
  1333. {$ifdef x86_64}
  1334. { Always fine on x86-64 }
  1335. Result := True;
  1336. {$else x86_64}
  1337. Result :=
  1338. {$ifdef i8086}
  1339. (current_settings.cputype >= cpu_386) and
  1340. {$endif i8086}
  1341. (
  1342. { Always accept if optimising for size }
  1343. (cs_opt_size in current_settings.optimizerswitches) or
  1344. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1345. (current_settings.optimizecputype >= cpu_Pentium2)
  1346. );
  1347. {$endif x86_64}
  1348. end;
  1349. { Attempts to allocate a volatile integer register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_int;
  1364. (*
  1365. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1366. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1367. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1368. *)
  1369. for CurrentSuperReg in RegSet do
  1370. begin
  1371. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1372. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1373. {$if defined(i386) or defined(i8086)}
  1374. { If the target size is 8-bit, make sure we can actually encode it }
  1375. and (
  1376. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1377. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1378. )
  1379. {$endif i386 or i8086}
  1380. then
  1381. begin
  1382. Currentp := p;
  1383. Breakout := False;
  1384. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1385. begin
  1386. case Currentp.typ of
  1387. ait_instruction:
  1388. begin
  1389. if RegInInstruction(CurrentReg, Currentp) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. { Cannot allocate across an unconditional jump }
  1395. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1396. Exit;
  1397. end;
  1398. ait_marker:
  1399. { Don't try anything more if a marker is hit }
  1400. Exit;
  1401. ait_regalloc:
  1402. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. else
  1408. ;
  1409. end;
  1410. end;
  1411. if Breakout then
  1412. { Try the next register }
  1413. Continue;
  1414. { We have a free register available }
  1415. Result := CurrentReg;
  1416. if not DontAlloc then
  1417. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1418. Exit;
  1419. end;
  1420. end;
  1421. end;
  1422. { Attempts to allocate a volatile MM register for use between p and hp,
  1423. using AUsedRegs for the current register usage information. Returns NR_NO
  1424. if no free register could be found }
  1425. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1426. var
  1427. RegSet: TCPURegisterSet;
  1428. CurrentSuperReg: Integer;
  1429. CurrentReg: TRegister;
  1430. Currentp: tai;
  1431. Breakout: Boolean;
  1432. begin
  1433. Result := NR_NO;
  1434. RegSet :=
  1435. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1436. current_procinfo.saved_regs_mm;
  1437. for CurrentSuperReg in RegSet do
  1438. begin
  1439. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1440. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1441. begin
  1442. Currentp := p;
  1443. Breakout := False;
  1444. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1445. begin
  1446. case Currentp.typ of
  1447. ait_instruction:
  1448. begin
  1449. if RegInInstruction(CurrentReg, Currentp) then
  1450. begin
  1451. Breakout := True;
  1452. Break;
  1453. end;
  1454. { Cannot allocate across an unconditional jump }
  1455. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1456. Exit;
  1457. end;
  1458. ait_marker:
  1459. { Don't try anything more if a marker is hit }
  1460. Exit;
  1461. ait_regalloc:
  1462. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. else
  1468. ;
  1469. end;
  1470. end;
  1471. if Breakout then
  1472. { Try the next register }
  1473. Continue;
  1474. { We have a free register available }
  1475. Result := CurrentReg;
  1476. if not DontAlloc then
  1477. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1478. Exit;
  1479. end;
  1480. end;
  1481. end;
  1482. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1483. begin
  1484. if not SuperRegistersEqual(reg1,reg2) then
  1485. exit(false);
  1486. if getregtype(reg1)<>R_INTREGISTER then
  1487. exit(true); {because SuperRegisterEqual is true}
  1488. case getsubreg(reg1) of
  1489. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1490. higher, it preserves the high bits, so the new value depends on
  1491. reg2's previous value. In other words, it is equivalent to doing:
  1492. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1493. R_SUBL:
  1494. exit(getsubreg(reg2)=R_SUBL);
  1495. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1496. higher, it actually does a:
  1497. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1498. R_SUBH:
  1499. exit(getsubreg(reg2)=R_SUBH);
  1500. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1501. bits of reg2:
  1502. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1503. R_SUBW:
  1504. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1505. { a write to R_SUBD always overwrites every other subregister,
  1506. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1507. R_SUBD,
  1508. R_SUBQ:
  1509. exit(true);
  1510. else
  1511. internalerror(2017042801);
  1512. end;
  1513. end;
  1514. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1515. begin
  1516. if not SuperRegistersEqual(reg1,reg2) then
  1517. exit(false);
  1518. if getregtype(reg1)<>R_INTREGISTER then
  1519. exit(true); {because SuperRegisterEqual is true}
  1520. case getsubreg(reg1) of
  1521. R_SUBL:
  1522. exit(getsubreg(reg2)<>R_SUBH);
  1523. R_SUBH:
  1524. exit(getsubreg(reg2)<>R_SUBL);
  1525. R_SUBW,
  1526. R_SUBD,
  1527. R_SUBQ:
  1528. exit(true);
  1529. else
  1530. internalerror(2017042802);
  1531. end;
  1532. end;
  1533. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1534. var
  1535. hp1 : tai;
  1536. l : TCGInt;
  1537. begin
  1538. result:=false;
  1539. if not(GetNextInstruction(p, hp1)) then
  1540. exit;
  1541. { changes the code sequence
  1542. shr/sar const1, x
  1543. shl const2, x
  1544. to
  1545. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1546. if (taicpu(p).oper[0]^.typ = top_const) and
  1547. MatchInstruction(hp1,A_SHL,[]) and
  1548. (taicpu(hp1).oper[0]^.typ = top_const) and
  1549. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1550. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1551. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1552. begin
  1553. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1554. not(cs_opt_size in current_settings.optimizerswitches) then
  1555. begin
  1556. { shr/sar const1, %reg
  1557. shl const2, %reg
  1558. with const1 > const2 }
  1559. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1560. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1561. taicpu(hp1).opcode := A_AND;
  1562. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1563. case taicpu(p).opsize Of
  1564. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1565. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1566. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1567. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1568. else
  1569. Internalerror(2017050703)
  1570. end;
  1571. end
  1572. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) then
  1574. begin
  1575. { shr/sar const1, %reg
  1576. shl const2, %reg
  1577. with const1 < const2 }
  1578. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1579. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1580. taicpu(p).opcode := A_AND;
  1581. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1582. case taicpu(p).opsize Of
  1583. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1584. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1585. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1586. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1587. else
  1588. Internalerror(2017050702)
  1589. end;
  1590. end
  1591. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 = const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1597. taicpu(p).opcode := A_AND;
  1598. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1599. case taicpu(p).opsize Of
  1600. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1601. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1602. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1603. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1604. else
  1605. Internalerror(2017050701)
  1606. end;
  1607. RemoveInstruction(hp1);
  1608. end;
  1609. end;
  1610. end;
  1611. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1612. var
  1613. opsize : topsize;
  1614. hp1, hp2 : tai;
  1615. tmpref : treference;
  1616. ShiftValue : Cardinal;
  1617. BaseValue : TCGInt;
  1618. begin
  1619. result:=false;
  1620. opsize:=taicpu(p).opsize;
  1621. { changes certain "imul const, %reg"'s to lea sequences }
  1622. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1623. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1624. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1625. if (taicpu(p).oper[0]^.val = 1) then
  1626. if (taicpu(p).ops = 2) then
  1627. { remove "imul $1, reg" }
  1628. begin
  1629. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1630. Result := RemoveCurrentP(p);
  1631. end
  1632. else
  1633. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1634. begin
  1635. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1636. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1637. asml.InsertAfter(hp1, p);
  1638. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1639. RemoveCurrentP(p, hp1);
  1640. Result := True;
  1641. end
  1642. else if ((taicpu(p).ops <= 2) or
  1643. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1644. not(cs_opt_size in current_settings.optimizerswitches) and
  1645. (not(GetNextInstruction(p, hp1)) or
  1646. not((tai(hp1).typ = ait_instruction) and
  1647. ((taicpu(hp1).opcode=A_Jcc) and
  1648. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1649. begin
  1650. {
  1651. imul X, reg1, reg2 to
  1652. lea (reg1,reg1,Y), reg2
  1653. shl ZZ,reg2
  1654. imul XX, reg1 to
  1655. lea (reg1,reg1,YY), reg1
  1656. shl ZZ,reg2
  1657. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1658. it does not exist as a separate optimization target in FPC though.
  1659. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1660. at most two zeros
  1661. }
  1662. reference_reset(tmpref,1,[]);
  1663. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1664. begin
  1665. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1666. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1667. TmpRef.base := taicpu(p).oper[1]^.reg;
  1668. TmpRef.index := taicpu(p).oper[1]^.reg;
  1669. if not(BaseValue in [3,5,9]) then
  1670. Internalerror(2018110101);
  1671. TmpRef.ScaleFactor := BaseValue-1;
  1672. if (taicpu(p).ops = 2) then
  1673. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1674. else
  1675. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1676. AsmL.InsertAfter(hp1,p);
  1677. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1678. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1679. RemoveCurrentP(p, hp1);
  1680. if ShiftValue>0 then
  1681. begin
  1682. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1683. AsmL.InsertAfter(hp2,hp1);
  1684. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1685. end;
  1686. Result := True;
  1687. end;
  1688. end;
  1689. end;
  1690. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1691. begin
  1692. Result := False;
  1693. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1694. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1695. begin
  1696. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1697. taicpu(p).opcode := A_MOV;
  1698. Result := True;
  1699. end;
  1700. end;
  1701. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1702. var
  1703. p: taicpu absolute hp; { Implicit typecast }
  1704. i: Integer;
  1705. begin
  1706. Result := False;
  1707. if not assigned(hp) or
  1708. (hp.typ <> ait_instruction) then
  1709. Exit;
  1710. Prefetch(insprop[p.opcode]);
  1711. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1712. with insprop[p.opcode] do
  1713. begin
  1714. case getsubreg(reg) of
  1715. R_SUBW,R_SUBD,R_SUBQ:
  1716. Result:=
  1717. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1718. uncommon flags are checked first }
  1719. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1720. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1721. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1725. R_SUBFLAGCARRY:
  1726. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1727. R_SUBFLAGPARITY:
  1728. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1729. R_SUBFLAGAUXILIARY:
  1730. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1731. R_SUBFLAGZERO:
  1732. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1733. R_SUBFLAGSIGN:
  1734. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1735. R_SUBFLAGOVERFLOW:
  1736. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1737. R_SUBFLAGINTERRUPT:
  1738. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1739. R_SUBFLAGDIRECTION:
  1740. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1741. else
  1742. internalerror(2017050501);
  1743. end;
  1744. exit;
  1745. end;
  1746. { Handle special cases first }
  1747. case p.opcode of
  1748. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1749. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1750. begin
  1751. Result :=
  1752. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1753. (p.oper[1]^.typ = top_reg) and
  1754. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1755. (
  1756. (p.oper[0]^.typ = top_const) or
  1757. (
  1758. (p.oper[0]^.typ = top_reg) and
  1759. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1760. ) or (
  1761. (p.oper[0]^.typ = top_ref) and
  1762. not RegInRef(reg,p.oper[0]^.ref^)
  1763. )
  1764. );
  1765. end;
  1766. A_MUL, A_IMUL:
  1767. Result :=
  1768. (
  1769. (p.ops=3) and { IMUL only }
  1770. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1771. (
  1772. (
  1773. (p.oper[1]^.typ=top_reg) and
  1774. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1775. ) or (
  1776. (p.oper[1]^.typ=top_ref) and
  1777. not RegInRef(reg,p.oper[1]^.ref^)
  1778. )
  1779. )
  1780. ) or (
  1781. (
  1782. (p.ops=1) and
  1783. (
  1784. (
  1785. (
  1786. (p.oper[0]^.typ=top_reg) and
  1787. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1788. )
  1789. ) or (
  1790. (p.oper[0]^.typ=top_ref) and
  1791. not RegInRef(reg,p.oper[0]^.ref^)
  1792. )
  1793. ) and (
  1794. (
  1795. (p.opsize=S_B) and
  1796. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1797. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1798. ) or (
  1799. (p.opsize=S_W) and
  1800. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1801. ) or (
  1802. (p.opsize=S_L) and
  1803. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1804. {$ifdef x86_64}
  1805. ) or (
  1806. (p.opsize=S_Q) and
  1807. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1808. {$endif x86_64}
  1809. )
  1810. )
  1811. )
  1812. );
  1813. A_CBW:
  1814. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1815. {$ifndef x86_64}
  1816. A_LDS:
  1817. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1818. A_LES:
  1819. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1820. {$endif not x86_64}
  1821. A_LFS:
  1822. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1823. A_LGS:
  1824. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1825. A_LSS:
  1826. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1827. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1828. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1829. A_LODSB:
  1830. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1831. A_LODSW:
  1832. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1833. {$ifdef x86_64}
  1834. A_LODSQ:
  1835. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1836. {$endif x86_64}
  1837. A_LODSD:
  1838. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1839. A_FSTSW, A_FNSTSW:
  1840. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1841. else
  1842. begin
  1843. with insprop[p.opcode] do
  1844. begin
  1845. if (
  1846. { xor %reg,%reg etc. is classed as a new value }
  1847. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1848. MatchOpType(p, top_reg, top_reg) and
  1849. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1850. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1851. ) then
  1852. begin
  1853. Result := True;
  1854. Exit;
  1855. end;
  1856. { Make sure the entire register is overwritten }
  1857. if (getregtype(reg) = R_INTREGISTER) then
  1858. begin
  1859. if (p.ops > 0) then
  1860. begin
  1861. if RegInOp(reg, p.oper[0]^) then
  1862. begin
  1863. if (p.oper[0]^.typ = top_ref) then
  1864. begin
  1865. if RegInRef(reg, p.oper[0]^.ref^) then
  1866. begin
  1867. Result := False;
  1868. Exit;
  1869. end;
  1870. end
  1871. else if (p.oper[0]^.typ = top_reg) then
  1872. begin
  1873. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end
  1878. else if ([Ch_WOp1]*Ch<>[]) then
  1879. begin
  1880. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1881. Result := True
  1882. else
  1883. begin
  1884. Result := False;
  1885. Exit;
  1886. end;
  1887. end;
  1888. end;
  1889. end;
  1890. if (p.ops > 1) then
  1891. begin
  1892. if RegInOp(reg, p.oper[1]^) then
  1893. begin
  1894. if (p.oper[1]^.typ = top_ref) then
  1895. begin
  1896. if RegInRef(reg, p.oper[1]^.ref^) then
  1897. begin
  1898. Result := False;
  1899. Exit;
  1900. end;
  1901. end
  1902. else if (p.oper[1]^.typ = top_reg) then
  1903. begin
  1904. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1905. begin
  1906. Result := False;
  1907. Exit;
  1908. end
  1909. else if ([Ch_WOp2]*Ch<>[]) then
  1910. begin
  1911. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1912. Result := True
  1913. else
  1914. begin
  1915. Result := False;
  1916. Exit;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. if (p.ops > 2) then
  1922. begin
  1923. if RegInOp(reg, p.oper[2]^) then
  1924. begin
  1925. if (p.oper[2]^.typ = top_ref) then
  1926. begin
  1927. if RegInRef(reg, p.oper[2]^.ref^) then
  1928. begin
  1929. Result := False;
  1930. Exit;
  1931. end;
  1932. end
  1933. else if (p.oper[2]^.typ = top_reg) then
  1934. begin
  1935. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1936. begin
  1937. Result := False;
  1938. Exit;
  1939. end
  1940. else if ([Ch_WOp3]*Ch<>[]) then
  1941. begin
  1942. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1943. Result := True
  1944. else
  1945. begin
  1946. Result := False;
  1947. Exit;
  1948. end;
  1949. end;
  1950. end;
  1951. end;
  1952. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1953. begin
  1954. if (p.oper[3]^.typ = top_ref) then
  1955. begin
  1956. if RegInRef(reg, p.oper[3]^.ref^) then
  1957. begin
  1958. Result := False;
  1959. Exit;
  1960. end;
  1961. end
  1962. else if (p.oper[3]^.typ = top_reg) then
  1963. begin
  1964. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end
  1969. else if ([Ch_WOp4]*Ch<>[]) then
  1970. begin
  1971. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1972. Result := True
  1973. else
  1974. begin
  1975. Result := False;
  1976. Exit;
  1977. end;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1985. case getsupreg(reg) of
  1986. RS_EAX:
  1987. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1988. begin
  1989. Result := True;
  1990. Exit;
  1991. end;
  1992. RS_ECX:
  1993. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1994. begin
  1995. Result := True;
  1996. Exit;
  1997. end;
  1998. RS_EDX:
  1999. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2000. begin
  2001. Result := True;
  2002. Exit;
  2003. end;
  2004. RS_EBX:
  2005. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2006. begin
  2007. Result := True;
  2008. Exit;
  2009. end;
  2010. RS_ESP:
  2011. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2012. begin
  2013. Result := True;
  2014. Exit;
  2015. end;
  2016. RS_EBP:
  2017. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2018. begin
  2019. Result := True;
  2020. Exit;
  2021. end;
  2022. RS_ESI:
  2023. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2024. begin
  2025. Result := True;
  2026. Exit;
  2027. end;
  2028. RS_EDI:
  2029. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2030. begin
  2031. Result := True;
  2032. Exit;
  2033. end;
  2034. else
  2035. ;
  2036. end;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2043. var
  2044. hp2,hp3 : tai;
  2045. begin
  2046. { some x86-64 issue a NOP before the real exit code }
  2047. if MatchInstruction(p,A_NOP,[]) then
  2048. GetNextInstruction(p,p);
  2049. result:=assigned(p) and (p.typ=ait_instruction) and
  2050. ((taicpu(p).opcode = A_RET) or
  2051. ((taicpu(p).opcode=A_LEAVE) and
  2052. GetNextInstruction(p,hp2) and
  2053. MatchInstruction(hp2,A_RET,[S_NO])
  2054. ) or
  2055. (((taicpu(p).opcode=A_LEA) and
  2056. MatchOpType(taicpu(p),top_ref,top_reg) and
  2057. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2058. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2059. ) and
  2060. GetNextInstruction(p,hp2) and
  2061. MatchInstruction(hp2,A_RET,[S_NO])
  2062. ) or
  2063. ((((taicpu(p).opcode=A_MOV) and
  2064. MatchOpType(taicpu(p),top_reg,top_reg) and
  2065. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2066. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2067. ((taicpu(p).opcode=A_LEA) and
  2068. MatchOpType(taicpu(p),top_ref,top_reg) and
  2069. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2070. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2071. )
  2072. ) and
  2073. GetNextInstruction(p,hp2) and
  2074. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2075. MatchOpType(taicpu(hp2),top_reg) and
  2076. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2077. GetNextInstruction(hp2,hp3) and
  2078. MatchInstruction(hp3,A_RET,[S_NO])
  2079. )
  2080. );
  2081. end;
  2082. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2083. begin
  2084. isFoldableArithOp := False;
  2085. case hp1.opcode of
  2086. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2087. isFoldableArithOp :=
  2088. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2089. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2090. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2092. (taicpu(hp1).oper[1]^.reg = reg);
  2093. A_INC,A_DEC,A_NEG,A_NOT:
  2094. isFoldableArithOp :=
  2095. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2096. (taicpu(hp1).oper[0]^.reg = reg);
  2097. else
  2098. ;
  2099. end;
  2100. end;
  2101. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2102. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2103. var
  2104. hp2: tai;
  2105. begin
  2106. hp2 := p;
  2107. repeat
  2108. hp2 := tai(hp2.previous);
  2109. if assigned(hp2) and
  2110. (hp2.typ = ait_regalloc) and
  2111. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2112. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2113. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2114. begin
  2115. RemoveInstruction(hp2);
  2116. break;
  2117. end;
  2118. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2119. end;
  2120. begin
  2121. case current_procinfo.procdef.returndef.typ of
  2122. arraydef,recorddef,pointerdef,
  2123. stringdef,enumdef,procdef,objectdef,errordef,
  2124. filedef,setdef,procvardef,
  2125. classrefdef,forwarddef:
  2126. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2127. orddef:
  2128. if current_procinfo.procdef.returndef.size <> 0 then
  2129. begin
  2130. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2131. { for int64/qword }
  2132. if current_procinfo.procdef.returndef.size = 8 then
  2133. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2134. end;
  2135. else
  2136. ;
  2137. end;
  2138. end;
  2139. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2140. var
  2141. hp1: tai;
  2142. operswap: poper;
  2143. begin
  2144. Result := False;
  2145. { Optimise:
  2146. cmov(c) %reg1,%reg2
  2147. mov %reg2,%reg1
  2148. (%reg2 dealloc.)
  2149. To:
  2150. cmov(~c) %reg2,%reg1
  2151. }
  2152. if (taicpu(p).oper[0]^.typ = top_reg) then
  2153. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2154. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2156. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2160. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2163. { Save time by swapping the pointers (they're both registers, so
  2164. we don't need to worry about reference counts) }
  2165. operswap := taicpu(p).oper[0];
  2166. taicpu(p).oper[0] := taicpu(p).oper[1];
  2167. taicpu(p).oper[1] := operswap;
  2168. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2169. RemoveInstruction(hp1);
  2170. { It's still a CMOV, so we can look further ahead }
  2171. Include(OptsToCheck, aoc_ForceNewIteration);
  2172. { But first, let's see if this will get optimised again
  2173. (probably won't happen, but best to be sure) }
  2174. Continue;
  2175. end;
  2176. Break;
  2177. end;
  2178. end;
  2179. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2180. var
  2181. hp1,hp2 : tai;
  2182. begin
  2183. result:=false;
  2184. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2185. begin
  2186. { vmova* reg1,reg1
  2187. =>
  2188. <nop> }
  2189. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2190. begin
  2191. RemoveCurrentP(p);
  2192. result:=true;
  2193. exit;
  2194. end;
  2195. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2196. (hp1.typ = ait_instruction) and
  2197. (
  2198. { Under -O2 and below, the instructions are always adjacent }
  2199. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2200. (taicpu(hp1).ops <= 1) or
  2201. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2202. { If reg1 = reg3, reg1 must not be modified in between }
  2203. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2204. ) then
  2205. begin
  2206. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2207. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2208. begin
  2209. { vmova* reg1,reg2
  2210. ...
  2211. vmova* reg2,reg3
  2212. dealloc reg2
  2213. =>
  2214. vmova* reg1,reg3 }
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2217. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2218. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2219. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2220. begin
  2221. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2222. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2223. TransferUsedRegs(TmpUsedRegs);
  2224. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2225. RemoveInstruction(hp1);
  2226. result:=true;
  2227. exit;
  2228. end;
  2229. { special case:
  2230. vmova* reg1,<op>
  2231. ...
  2232. vmova* <op>,reg1
  2233. =>
  2234. vmova* reg1,<op> }
  2235. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2236. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2237. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2238. ) then
  2239. begin
  2240. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2241. RemoveInstruction(hp1);
  2242. result:=true;
  2243. exit;
  2244. end
  2245. end
  2246. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2247. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2248. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2249. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2250. ) and
  2251. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2252. begin
  2253. { vmova* reg1,reg2
  2254. ...
  2255. vmovs* reg2,<op>
  2256. dealloc reg2
  2257. =>
  2258. vmovs* reg1,<op> }
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2261. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2264. taicpu(p).opcode:=taicpu(hp1).opcode;
  2265. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2266. TransferUsedRegs(TmpUsedRegs);
  2267. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end;
  2273. if MatchInstruction(hp1,[A_VFMADDPD,
  2274. A_VFMADD132PD,
  2275. A_VFMADD132PS,
  2276. A_VFMADD132SD,
  2277. A_VFMADD132SS,
  2278. A_VFMADD213PD,
  2279. A_VFMADD213PS,
  2280. A_VFMADD213SD,
  2281. A_VFMADD213SS,
  2282. A_VFMADD231PD,
  2283. A_VFMADD231PS,
  2284. A_VFMADD231SD,
  2285. A_VFMADD231SS,
  2286. A_VFMADDSUB132PD,
  2287. A_VFMADDSUB132PS,
  2288. A_VFMADDSUB213PD,
  2289. A_VFMADDSUB213PS,
  2290. A_VFMADDSUB231PD,
  2291. A_VFMADDSUB231PS,
  2292. A_VFMSUB132PD,
  2293. A_VFMSUB132PS,
  2294. A_VFMSUB132SD,
  2295. A_VFMSUB132SS,
  2296. A_VFMSUB213PD,
  2297. A_VFMSUB213PS,
  2298. A_VFMSUB213SD,
  2299. A_VFMSUB213SS,
  2300. A_VFMSUB231PD,
  2301. A_VFMSUB231PS,
  2302. A_VFMSUB231SD,
  2303. A_VFMSUB231SS,
  2304. A_VFMSUBADD132PD,
  2305. A_VFMSUBADD132PS,
  2306. A_VFMSUBADD213PD,
  2307. A_VFMSUBADD213PS,
  2308. A_VFMSUBADD231PD,
  2309. A_VFMSUBADD231PS,
  2310. A_VFNMADD132PD,
  2311. A_VFNMADD132PS,
  2312. A_VFNMADD132SD,
  2313. A_VFNMADD132SS,
  2314. A_VFNMADD213PD,
  2315. A_VFNMADD213PS,
  2316. A_VFNMADD213SD,
  2317. A_VFNMADD213SS,
  2318. A_VFNMADD231PD,
  2319. A_VFNMADD231PS,
  2320. A_VFNMADD231SD,
  2321. A_VFNMADD231SS,
  2322. A_VFNMSUB132PD,
  2323. A_VFNMSUB132PS,
  2324. A_VFNMSUB132SD,
  2325. A_VFNMSUB132SS,
  2326. A_VFNMSUB213PD,
  2327. A_VFNMSUB213PS,
  2328. A_VFNMSUB213SD,
  2329. A_VFNMSUB213SS,
  2330. A_VFNMSUB231PD,
  2331. A_VFNMSUB231PS,
  2332. A_VFNMSUB231SD,
  2333. A_VFNMSUB231SS],[S_NO]) and
  2334. { we mix single and double opperations here because we assume that the compiler
  2335. generates vmovapd only after double operations and vmovaps only after single operations }
  2336. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2337. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2338. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2339. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2340. begin
  2341. TransferUsedRegs(TmpUsedRegs);
  2342. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2343. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2344. begin
  2345. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2346. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2347. RemoveCurrentP(p)
  2348. else
  2349. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2350. RemoveInstruction(hp2);
  2351. end;
  2352. end
  2353. else if (hp1.typ = ait_instruction) and
  2354. (((taicpu(p).opcode=A_MOVAPS) and
  2355. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2356. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2357. ((taicpu(p).opcode=A_MOVAPD) and
  2358. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2359. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2360. ) and
  2361. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2362. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2363. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2364. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2365. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2366. { change
  2367. movapX reg,reg2
  2368. addsX/subsX/... reg3, reg2
  2369. movapX reg2,reg
  2370. to
  2371. addsX/subsX/... reg3,reg
  2372. }
  2373. begin
  2374. TransferUsedRegs(TmpUsedRegs);
  2375. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2376. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2377. begin
  2378. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2379. debug_op2str(taicpu(p).opcode)+' '+
  2380. debug_op2str(taicpu(hp1).opcode)+' '+
  2381. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2382. { we cannot eliminate the first move if
  2383. the operations uses the same register for source and dest }
  2384. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2385. { Remember that hp1 is not necessarily the immediate
  2386. next instruction }
  2387. RemoveCurrentP(p);
  2388. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2389. RemoveInstruction(hp2);
  2390. result:=true;
  2391. end;
  2392. end
  2393. else if (hp1.typ = ait_instruction) and
  2394. (((taicpu(p).opcode=A_VMOVAPD) and
  2395. (taicpu(hp1).opcode=A_VCOMISD)) or
  2396. ((taicpu(p).opcode=A_VMOVAPS) and
  2397. ((taicpu(hp1).opcode=A_VCOMISS))
  2398. )
  2399. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2400. { change
  2401. movapX reg,reg1
  2402. vcomisX reg1,reg1
  2403. to
  2404. vcomisX reg,reg
  2405. }
  2406. begin
  2407. TransferUsedRegs(TmpUsedRegs);
  2408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2409. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2410. begin
  2411. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2412. debug_op2str(taicpu(p).opcode)+' '+
  2413. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2414. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2415. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2416. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2417. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2418. RemoveCurrentP(p);
  2419. result:=true;
  2420. exit;
  2421. end;
  2422. end
  2423. end;
  2424. end;
  2425. end;
  2426. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2427. var
  2428. hp1 : tai;
  2429. begin
  2430. result:=false;
  2431. { replace
  2432. V<Op>X %mreg1,%mreg2,%mreg3
  2433. VMovX %mreg3,%mreg4
  2434. dealloc %mreg3
  2435. by
  2436. V<Op>X %mreg1,%mreg2,%mreg4
  2437. ?
  2438. }
  2439. if GetNextInstruction(p,hp1) and
  2440. { we mix single and double operations here because we assume that the compiler
  2441. generates vmovapd only after double operations and vmovaps only after single operations }
  2442. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2443. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2444. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2445. begin
  2446. TransferUsedRegs(TmpUsedRegs);
  2447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2448. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2449. begin
  2450. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2451. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2452. RemoveInstruction(hp1);
  2453. result:=true;
  2454. end;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2459. begin
  2460. Result := False;
  2461. { For safety reasons, only check for exact register matches }
  2462. { Check base register }
  2463. if (ref.base = AOldReg) then
  2464. begin
  2465. ref.base := ANewReg;
  2466. Result := True;
  2467. end;
  2468. { Check index register }
  2469. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2470. begin
  2471. ref.index := ANewReg;
  2472. Result := True;
  2473. end;
  2474. end;
  2475. { Replaces all references to AOldReg in an operand to ANewReg }
  2476. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2477. var
  2478. OldSupReg, NewSupReg: TSuperRegister;
  2479. OldSubReg, NewSubReg: TSubRegister;
  2480. OldRegType: TRegisterType;
  2481. ThisOper: POper;
  2482. begin
  2483. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2484. Result := False;
  2485. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2486. InternalError(2020011801);
  2487. OldSupReg := getsupreg(AOldReg);
  2488. OldSubReg := getsubreg(AOldReg);
  2489. OldRegType := getregtype(AOldReg);
  2490. NewSupReg := getsupreg(ANewReg);
  2491. NewSubReg := getsubreg(ANewReg);
  2492. if OldRegType <> getregtype(ANewReg) then
  2493. InternalError(2020011802);
  2494. if OldSubReg <> NewSubReg then
  2495. InternalError(2020011803);
  2496. case ThisOper^.typ of
  2497. top_reg:
  2498. if (
  2499. (ThisOper^.reg = AOldReg) or
  2500. (
  2501. (OldRegType = R_INTREGISTER) and
  2502. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2503. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2504. (
  2505. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2506. {$ifndef x86_64}
  2507. and (
  2508. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2509. don't have an 8-bit representation }
  2510. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2511. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2512. )
  2513. {$endif x86_64}
  2514. )
  2515. )
  2516. ) then
  2517. begin
  2518. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2519. Result := True;
  2520. end;
  2521. top_ref:
  2522. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2523. Result := True;
  2524. else
  2525. ;
  2526. end;
  2527. end;
  2528. { Replaces all references to AOldReg in an instruction to ANewReg }
  2529. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2530. const
  2531. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2532. var
  2533. OperIdx: Integer;
  2534. begin
  2535. Result := False;
  2536. for OperIdx := 0 to p.ops - 1 do
  2537. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2538. begin
  2539. { The shift and rotate instructions can only use CL }
  2540. if not (
  2541. (OperIdx = 0) and
  2542. { This second condition just helps to avoid unnecessarily
  2543. calling MatchInstruction for 10 different opcodes }
  2544. (p.oper[0]^.reg = NR_CL) and
  2545. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2546. ) then
  2547. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2548. end
  2549. else if p.oper[OperIdx]^.typ = top_ref then
  2550. { It's okay to replace registers in references that get written to }
  2551. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2552. end;
  2553. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2554. begin
  2555. Result :=
  2556. (ref^.index = NR_NO) and
  2557. (
  2558. {$ifdef x86_64}
  2559. (
  2560. (ref^.base = NR_RIP) and
  2561. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2562. ) or
  2563. {$endif x86_64}
  2564. (ref^.refaddr = addr_full) or
  2565. (ref^.base = NR_STACK_POINTER_REG) or
  2566. (ref^.base = current_procinfo.framepointer)
  2567. );
  2568. end;
  2569. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2570. var
  2571. l: asizeint;
  2572. begin
  2573. Result := False;
  2574. { Should have been checked previously }
  2575. if p.opcode <> A_LEA then
  2576. InternalError(2020072501);
  2577. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2578. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2579. not(cs_opt_size in current_settings.optimizerswitches) then
  2580. exit;
  2581. with p.oper[0]^.ref^ do
  2582. begin
  2583. if (base <> p.oper[1]^.reg) or
  2584. (index <> NR_NO) or
  2585. assigned(symbol) then
  2586. exit;
  2587. l:=offset;
  2588. if (l=1) and UseIncDec then
  2589. begin
  2590. p.opcode:=A_INC;
  2591. p.loadreg(0,p.oper[1]^.reg);
  2592. p.ops:=1;
  2593. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2594. end
  2595. else if (l=-1) and UseIncDec then
  2596. begin
  2597. p.opcode:=A_DEC;
  2598. p.loadreg(0,p.oper[1]^.reg);
  2599. p.ops:=1;
  2600. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2601. end
  2602. else
  2603. begin
  2604. if (l<0) and (l<>-2147483648) then
  2605. begin
  2606. p.opcode:=A_SUB;
  2607. p.loadConst(0,-l);
  2608. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2609. end
  2610. else
  2611. begin
  2612. p.opcode:=A_ADD;
  2613. p.loadConst(0,l);
  2614. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2615. end;
  2616. end;
  2617. end;
  2618. Result := True;
  2619. end;
  2620. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2621. var
  2622. CurrentReg, ReplaceReg: TRegister;
  2623. begin
  2624. Result := False;
  2625. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2626. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2627. case hp.opcode of
  2628. A_FSTSW, A_FNSTSW,
  2629. A_IN, A_INS, A_OUT, A_OUTS,
  2630. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2631. { These routines have explicit operands, but they are restricted in
  2632. what they can be (e.g. IN and OUT can only read from AL, AX or
  2633. EAX. }
  2634. Exit;
  2635. A_IMUL:
  2636. begin
  2637. { The 1-operand version writes to implicit registers
  2638. The 2-operand version reads from the first operator, and reads
  2639. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2640. the 3-operand version reads from a register that it doesn't write to
  2641. }
  2642. case hp.ops of
  2643. 1:
  2644. if (
  2645. (
  2646. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2647. ) or
  2648. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2649. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2650. begin
  2651. Result := True;
  2652. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2653. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2654. end;
  2655. 2:
  2656. { Only modify the first parameter }
  2657. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2658. begin
  2659. Result := True;
  2660. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2661. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2662. end;
  2663. 3:
  2664. { Only modify the second parameter }
  2665. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2666. begin
  2667. Result := True;
  2668. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2669. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2670. end;
  2671. else
  2672. InternalError(2020012901);
  2673. end;
  2674. end;
  2675. else
  2676. if (hp.ops > 0) and
  2677. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2678. begin
  2679. Result := True;
  2680. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2681. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2682. end;
  2683. end;
  2684. end;
  2685. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2686. var
  2687. hp2, hp_regalloc: tai;
  2688. p_SourceReg, p_TargetReg: TRegister;
  2689. begin
  2690. Result := False;
  2691. { Backward optimisation. If we have:
  2692. func. %reg1,%reg2
  2693. mov %reg2,%reg3
  2694. (dealloc %reg2)
  2695. Change to:
  2696. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2697. Perform similar optimisations with 1, 3 and 4-operand instructions
  2698. that only have one output.
  2699. }
  2700. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2701. begin
  2702. p_SourceReg := taicpu(p).oper[0]^.reg;
  2703. p_TargetReg := taicpu(p).oper[1]^.reg;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2706. GetLastInstruction(p, hp2) and
  2707. (hp2.typ = ait_instruction) and
  2708. { Have to make sure it's an instruction that only reads from
  2709. the first operands and only writes (not reads or modifies) to
  2710. the last one; in essence, a pure function such as BSR, POPCNT
  2711. or ANDN }
  2712. (
  2713. (
  2714. (taicpu(hp2).ops = 1) and
  2715. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2716. ) or
  2717. (
  2718. (taicpu(hp2).ops = 2) and
  2719. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2720. ) or
  2721. (
  2722. (taicpu(hp2).ops = 3) and
  2723. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2724. ) or
  2725. (
  2726. (taicpu(hp2).ops = 4) and
  2727. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2728. )
  2729. ) and
  2730. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2732. begin
  2733. case taicpu(hp2).opcode of
  2734. A_FSTSW, A_FNSTSW,
  2735. A_IN, A_INS, A_OUT, A_OUTS,
  2736. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2737. { These routines have explicit operands, but they are restricted in
  2738. what they can be (e.g. IN and OUT can only read from AL, AX or
  2739. EAX. }
  2740. ;
  2741. else
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2744. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2745. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2746. if Assigned(hp_regalloc) then
  2747. begin
  2748. Asml.Remove(hp_regalloc);
  2749. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2750. begin
  2751. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2752. hp_regalloc.Free;
  2753. end
  2754. else
  2755. { If the register is not explicitly deallocated, it's
  2756. being reused, so move the allocation to after func. }
  2757. AsmL.InsertAfter(hp_regalloc, hp2);
  2758. end;
  2759. if not RegInInstruction(p_TargetReg, hp2) then
  2760. begin
  2761. TransferUsedRegs(TmpUsedRegs);
  2762. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2763. end;
  2764. { Actually make the changes }
  2765. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2766. RemoveCurrentp(p, hp1);
  2767. { If the Func was another MOV instruction, we might get
  2768. "mov %reg,%reg" that doesn't get removed in Pass 2
  2769. otherwise, so deal with it here (also do something
  2770. similar with lea (%reg),%reg}
  2771. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2772. begin
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2774. if p = hp2 then
  2775. RemoveCurrentp(p)
  2776. else
  2777. RemoveInstruction(hp2);
  2778. end;
  2779. Result := True;
  2780. Exit;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2787. begin
  2788. Result := False;
  2789. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2790. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2792. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2793. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2794. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2795. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2799. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2800. Result := True;
  2801. Include(OptsToCheck, aoc_ForceNewIteration);
  2802. end;
  2803. end;
  2804. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2805. var
  2806. hp1, hp2, hp3, hp4: tai;
  2807. DoOptimisation, TempBool: Boolean;
  2808. {$ifdef x86_64}
  2809. NewConst: TCGInt;
  2810. {$endif x86_64}
  2811. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2812. begin
  2813. if taicpu(hp1).opcode = signed_movop then
  2814. begin
  2815. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2816. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2817. end
  2818. else
  2819. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2820. end;
  2821. function TryConstMerge(var p1, p2: tai): Boolean;
  2822. var
  2823. ThisRef: TReference;
  2824. begin
  2825. Result := False;
  2826. ThisRef := taicpu(p2).oper[1]^.ref^;
  2827. { Only permit writes to the stack, since we can guarantee alignment with that }
  2828. if (ThisRef.index = NR_NO) and
  2829. (
  2830. (ThisRef.base = NR_STACK_POINTER_REG) or
  2831. (ThisRef.base = current_procinfo.framepointer)
  2832. ) then
  2833. begin
  2834. case taicpu(p).opsize of
  2835. S_B:
  2836. begin
  2837. { Word writes must be on a 2-byte boundary }
  2838. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2839. begin
  2840. { Reduce offset of second reference to see if it is sequential with the first }
  2841. Dec(ThisRef.offset, 1);
  2842. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2843. begin
  2844. { Make sure the constants aren't represented as a
  2845. negative number, as these won't merge properly }
  2846. taicpu(p1).opsize := S_W;
  2847. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2848. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2849. RemoveInstruction(p2);
  2850. Result := True;
  2851. end;
  2852. end;
  2853. end;
  2854. S_W:
  2855. begin
  2856. { Longword writes must be on a 4-byte boundary }
  2857. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2858. begin
  2859. { Reduce offset of second reference to see if it is sequential with the first }
  2860. Dec(ThisRef.offset, 2);
  2861. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2862. begin
  2863. { Make sure the constants aren't represented as a
  2864. negative number, as these won't merge properly }
  2865. taicpu(p1).opsize := S_L;
  2866. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2867. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2868. RemoveInstruction(p2);
  2869. Result := True;
  2870. end;
  2871. end;
  2872. end;
  2873. {$ifdef x86_64}
  2874. S_L:
  2875. begin
  2876. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2877. see if the constants can be encoded this way. }
  2878. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2879. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2880. { Quadword writes must be on an 8-byte boundary }
  2881. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2882. begin
  2883. { Reduce offset of second reference to see if it is sequential with the first }
  2884. Dec(ThisRef.offset, 4);
  2885. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2886. begin
  2887. { Make sure the constants aren't represented as a
  2888. negative number, as these won't merge properly }
  2889. taicpu(p1).opsize := S_Q;
  2890. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2891. taicpu(p1).oper[0]^.val := NewConst;
  2892. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2893. RemoveInstruction(p2);
  2894. Result := True;
  2895. end;
  2896. end;
  2897. end;
  2898. {$endif x86_64}
  2899. else
  2900. ;
  2901. end;
  2902. end;
  2903. end;
  2904. var
  2905. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2906. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2907. NewSize: topsize; NewOffset: asizeint;
  2908. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2909. SourceRef, TargetRef: TReference;
  2910. MovAligned, MovUnaligned: TAsmOp;
  2911. ThisRef: TReference;
  2912. JumpTracking: TLinkedList;
  2913. begin
  2914. Result:=false;
  2915. { remove mov reg1,reg1? }
  2916. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2917. then
  2918. begin
  2919. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2920. { take care of the register (de)allocs following p }
  2921. RemoveCurrentP(p);
  2922. Result := True;
  2923. exit;
  2924. end;
  2925. { Prevent compiler warnings }
  2926. p_SourceReg := NR_NO;
  2927. p_TargetReg := NR_NO;
  2928. if taicpu(p).oper[1]^.typ = top_reg then
  2929. begin
  2930. { Saves on a large number of dereferences }
  2931. p_TargetReg := taicpu(p).oper[1]^.reg;
  2932. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2933. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2934. else
  2935. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2936. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2937. begin
  2938. if (taicpu(hp1).opcode = A_AND) and
  2939. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2940. begin
  2941. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2942. begin
  2943. case taicpu(p).opsize of
  2944. S_L:
  2945. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2946. begin
  2947. { Optimize out:
  2948. mov x, %reg
  2949. and ffffffffh, %reg
  2950. }
  2951. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2952. RemoveInstruction(hp1);
  2953. Result:=true;
  2954. exit;
  2955. end;
  2956. S_Q: { TODO: Confirm if this is even possible }
  2957. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2958. begin
  2959. { Optimize out:
  2960. mov x, %reg
  2961. and ffffffffffffffffh, %reg
  2962. }
  2963. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2964. RemoveInstruction(hp1);
  2965. Result:=true;
  2966. exit;
  2967. end;
  2968. else
  2969. ;
  2970. end;
  2971. if (
  2972. { Make sure that if a reference is used, its registers
  2973. are not modified in between }
  2974. (
  2975. (taicpu(p).oper[0]^.typ = top_reg) and
  2976. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2977. ) or
  2978. (
  2979. (taicpu(p).oper[0]^.typ = top_ref) and
  2980. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2981. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2982. )
  2983. ) and
  2984. GetNextInstruction(hp1,hp2) and
  2985. MatchInstruction(hp2,A_TEST,[]) and
  2986. (
  2987. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2988. (
  2989. { If the register being tested is smaller than the one
  2990. that received a bitwise AND, permit it if the constant
  2991. fits into the smaller size }
  2992. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2993. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2994. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2995. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2996. (
  2997. (
  2998. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2999. (taicpu(hp1).oper[0]^.val <= $FF)
  3000. ) or
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3003. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3004. {$ifdef x86_64}
  3005. ) or
  3006. (
  3007. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3008. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3009. {$endif x86_64}
  3010. )
  3011. )
  3012. )
  3013. ) and
  3014. (
  3015. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3016. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3017. ) and
  3018. GetNextInstruction(hp2,hp3) and
  3019. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3020. (taicpu(hp3).condition in [C_E,C_NE]) then
  3021. begin
  3022. TransferUsedRegs(TmpUsedRegs);
  3023. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3024. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3025. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3026. begin
  3027. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3028. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3029. taicpu(hp1).opcode:=A_TEST;
  3030. { Shrink the TEST instruction down to the smallest possible size }
  3031. case taicpu(hp1).oper[0]^.val of
  3032. 0..255:
  3033. if (taicpu(hp1).opsize <> S_B)
  3034. {$ifndef x86_64}
  3035. and (
  3036. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3037. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3038. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3039. )
  3040. {$endif x86_64}
  3041. then
  3042. begin
  3043. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3044. { Only print debug message if the TEST instruction
  3045. is a different size before and after }
  3046. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3047. taicpu(hp1).opsize := S_B;
  3048. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3050. end;
  3051. 256..65535:
  3052. if (taicpu(hp1).opsize <> S_W) then
  3053. begin
  3054. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3055. { Only print debug message if the TEST instruction
  3056. is a different size before and after }
  3057. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3058. taicpu(hp1).opsize := S_W;
  3059. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3060. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3061. end;
  3062. {$ifdef x86_64}
  3063. 65536..$7FFFFFFF:
  3064. if (taicpu(hp1).opsize <> S_L) then
  3065. begin
  3066. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3067. { Only print debug message if the TEST instruction
  3068. is a different size before and after }
  3069. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3070. taicpu(hp1).opsize := S_L;
  3071. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3072. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3073. end;
  3074. {$endif x86_64}
  3075. else
  3076. ;
  3077. end;
  3078. RemoveInstruction(hp2);
  3079. RemoveCurrentP(p);
  3080. Result:=true;
  3081. exit;
  3082. end;
  3083. end;
  3084. end;
  3085. if IsMOVZXAcceptable and
  3086. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3087. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3088. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3089. then
  3090. begin
  3091. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3092. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3093. case taicpu(p).opsize of
  3094. S_B:
  3095. if (taicpu(hp1).oper[0]^.val = $ff) then
  3096. begin
  3097. { Convert:
  3098. movb x, %regl movb x, %regl
  3099. andw ffh, %regw andl ffh, %regd
  3100. To:
  3101. movzbw x, %regd movzbl x, %regd
  3102. (Identical registers, just different sizes)
  3103. }
  3104. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3105. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3106. case taicpu(hp1).opsize of
  3107. S_W: NewSize := S_BW;
  3108. S_L: NewSize := S_BL;
  3109. {$ifdef x86_64}
  3110. S_Q: NewSize := S_BQ;
  3111. {$endif x86_64}
  3112. else
  3113. InternalError(2018011510);
  3114. end;
  3115. end
  3116. else
  3117. NewSize := S_NO;
  3118. S_W:
  3119. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3120. begin
  3121. { Convert:
  3122. movw x, %regw
  3123. andl ffffh, %regd
  3124. To:
  3125. movzwl x, %regd
  3126. (Identical registers, just different sizes)
  3127. }
  3128. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3129. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3130. case taicpu(hp1).opsize of
  3131. S_L: NewSize := S_WL;
  3132. {$ifdef x86_64}
  3133. S_Q: NewSize := S_WQ;
  3134. {$endif x86_64}
  3135. else
  3136. InternalError(2018011511);
  3137. end;
  3138. end
  3139. else
  3140. NewSize := S_NO;
  3141. else
  3142. NewSize := S_NO;
  3143. end;
  3144. if NewSize <> S_NO then
  3145. begin
  3146. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3147. { The actual optimization }
  3148. taicpu(p).opcode := A_MOVZX;
  3149. taicpu(p).changeopsize(NewSize);
  3150. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3151. { Make sure we deal with any reference counts that were increased }
  3152. if taicpu(hp1).oper[1]^.typ = top_ref then
  3153. begin
  3154. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3155. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3156. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3157. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3158. end;
  3159. { Safeguard if "and" is followed by a conditional command }
  3160. TransferUsedRegs(TmpUsedRegs);
  3161. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3162. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3163. begin
  3164. { At this point, the "and" command is effectively equivalent to
  3165. "test %reg,%reg". This will be handled separately by the
  3166. Peephole Optimizer. [Kit] }
  3167. DebugMsg(SPeepholeOptimization + PreMessage +
  3168. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3169. end
  3170. else
  3171. begin
  3172. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3173. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3174. RemoveInstruction(hp1);
  3175. end;
  3176. Result := True;
  3177. Exit;
  3178. end;
  3179. end;
  3180. end;
  3181. if taicpu(p).oper[0]^.typ = top_reg then
  3182. begin
  3183. p_SourceReg := taicpu(p).oper[0]^.reg;
  3184. { Look for:
  3185. mov %reg1,%reg2
  3186. ??? %reg2,r/m
  3187. Change to:
  3188. mov %reg1,%reg2
  3189. ??? %reg1,r/m
  3190. }
  3191. if RegReadByInstruction(p_TargetReg, hp1) and
  3192. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3193. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3194. begin
  3195. { A change has occurred, just not in p }
  3196. Include(OptsToCheck, aoc_ForceNewIteration);
  3197. TransferUsedRegs(TmpUsedRegs);
  3198. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3199. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3200. { Just in case something didn't get modified (e.g. an
  3201. implicit register) }
  3202. not RegReadByInstruction(p_TargetReg, hp1) then
  3203. begin
  3204. { We can remove the original MOV }
  3205. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3206. RemoveCurrentP(p);
  3207. { UsedRegs got updated by RemoveCurrentp }
  3208. Result := True;
  3209. Exit;
  3210. end;
  3211. { If we know a MOV instruction has become a null operation, we might as well
  3212. get rid of it now to save time. }
  3213. if (taicpu(hp1).opcode = A_MOV) and
  3214. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3215. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3216. { Just being a register is enough to confirm it's a null operation }
  3217. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3218. begin
  3219. Result := True;
  3220. { Speed-up to reduce a pipeline stall... if we had something like...
  3221. movl %eax,%edx
  3222. movw %dx,%ax
  3223. ... the second instruction would change to movw %ax,%ax, but
  3224. given that it is now %ax that's active rather than %eax,
  3225. penalties might occur due to a partial register write, so instead,
  3226. change it to a MOVZX instruction when optimising for speed.
  3227. }
  3228. if not (cs_opt_size in current_settings.optimizerswitches) and
  3229. IsMOVZXAcceptable and
  3230. (taicpu(hp1).opsize < taicpu(p).opsize)
  3231. {$ifdef x86_64}
  3232. { operations already implicitly set the upper 64 bits to zero }
  3233. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3234. {$endif x86_64}
  3235. then
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3238. case taicpu(p).opsize of
  3239. S_W:
  3240. if taicpu(hp1).opsize = S_B then
  3241. taicpu(hp1).opsize := S_BL
  3242. else
  3243. InternalError(2020012911);
  3244. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3245. case taicpu(hp1).opsize of
  3246. S_B:
  3247. taicpu(hp1).opsize := S_BL;
  3248. S_W:
  3249. taicpu(hp1).opsize := S_WL;
  3250. else
  3251. InternalError(2020012912);
  3252. end;
  3253. else
  3254. InternalError(2020012910);
  3255. end;
  3256. taicpu(hp1).opcode := A_MOVZX;
  3257. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3258. end
  3259. else
  3260. begin
  3261. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3262. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3263. RemoveInstruction(hp1);
  3264. { The instruction after what was hp1 is now the immediate next instruction,
  3265. so we can continue to make optimisations if it's present }
  3266. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3267. Exit;
  3268. hp1 := hp2;
  3269. end;
  3270. end;
  3271. end;
  3272. {$ifdef x86_64}
  3273. { Change:
  3274. movl %reg1l,%reg2l
  3275. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3276. To:
  3277. movl %reg1l,%reg2l
  3278. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3279. If %reg1 = %reg3, convert to:
  3280. movl %reg1l,%reg2l
  3281. andl %reg1l,%reg1l
  3282. }
  3283. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3284. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3285. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3286. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3287. begin
  3288. TransferUsedRegs(TmpUsedRegs);
  3289. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3290. taicpu(hp1).opsize := S_L;
  3291. taicpu(hp1).loadreg(0, p_SourceReg);
  3292. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3293. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3294. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3295. begin
  3296. { %reg1 = %reg3 }
  3297. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3298. taicpu(hp1).opcode := A_AND;
  3299. end
  3300. else
  3301. begin
  3302. { %reg1 <> %reg3 }
  3303. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3304. end;
  3305. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3306. begin
  3307. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3308. RemoveCurrentP(p);
  3309. Result := True;
  3310. Exit;
  3311. end
  3312. else
  3313. begin
  3314. { Initial instruction wasn't actually changed }
  3315. Include(OptsToCheck, aoc_ForceNewIteration);
  3316. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3317. appears below since %reg1 has technically changed }
  3318. if taicpu(hp1).opcode = A_AND then
  3319. Exit;
  3320. end;
  3321. end;
  3322. {$endif x86_64}
  3323. end
  3324. else if taicpu(p).oper[0]^.typ = top_const then
  3325. begin
  3326. if (taicpu(hp1).opcode = A_OR) and
  3327. (taicpu(p).oper[1]^.typ = top_reg) and
  3328. MatchOperand(taicpu(p).oper[0]^, 0) and
  3329. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3330. begin
  3331. { mov 0, %reg
  3332. or ###,%reg
  3333. Change to (only if the flags are not used):
  3334. mov ###,%reg
  3335. }
  3336. TransferUsedRegs(TmpUsedRegs);
  3337. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3338. DoOptimisation := True;
  3339. { Even if the flags are used, we might be able to do the optimisation
  3340. if the conditions are predictable }
  3341. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3342. begin
  3343. { Only perform if ### = %reg (the same register) or equal to 0,
  3344. so %reg is guaranteed to still have a value of zero }
  3345. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3346. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3347. begin
  3348. hp2 := hp1;
  3349. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3350. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3351. GetNextInstruction(hp2, hp3) do
  3352. begin
  3353. { Don't continue modifying if the flags state is getting changed }
  3354. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3355. Break;
  3356. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3357. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3358. begin
  3359. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3360. begin
  3361. { Condition is always true }
  3362. case taicpu(hp3).opcode of
  3363. A_Jcc:
  3364. begin
  3365. { Check for jump shortcuts before we destroy the condition }
  3366. hp4 := hp3;
  3367. DoJumpOptimizations(hp3, TempBool);
  3368. { Make sure hp3 hasn't changed }
  3369. if (hp4 = hp3) then
  3370. begin
  3371. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3372. MakeUnconditional(taicpu(hp3));
  3373. end;
  3374. Result := True;
  3375. end;
  3376. A_CMOVcc:
  3377. begin
  3378. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3379. taicpu(hp3).opcode := A_MOV;
  3380. taicpu(hp3).condition := C_None;
  3381. Result := True;
  3382. end;
  3383. A_SETcc:
  3384. begin
  3385. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3386. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3387. taicpu(hp3).opcode := A_MOV;
  3388. taicpu(hp3).ops := 2;
  3389. taicpu(hp3).condition := C_None;
  3390. taicpu(hp3).opsize := S_B;
  3391. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3392. taicpu(hp3).loadconst(0, 1);
  3393. Result := True;
  3394. end;
  3395. else
  3396. InternalError(2021090701);
  3397. end;
  3398. end
  3399. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3400. begin
  3401. { Condition is always false }
  3402. case taicpu(hp3).opcode of
  3403. A_Jcc:
  3404. begin
  3405. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3406. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3407. RemoveInstruction(hp3);
  3408. Result := True;
  3409. { Since hp3 was deleted, hp2 must not be updated }
  3410. Continue;
  3411. end;
  3412. A_CMOVcc:
  3413. begin
  3414. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3415. RemoveInstruction(hp3);
  3416. Result := True;
  3417. { Since hp3 was deleted, hp2 must not be updated }
  3418. Continue;
  3419. end;
  3420. A_SETcc:
  3421. begin
  3422. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3423. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3424. taicpu(hp3).opcode := A_MOV;
  3425. taicpu(hp3).ops := 2;
  3426. taicpu(hp3).condition := C_None;
  3427. taicpu(hp3).opsize := S_B;
  3428. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3429. taicpu(hp3).loadconst(0, 0);
  3430. Result := True;
  3431. end;
  3432. else
  3433. InternalError(2021090702);
  3434. end;
  3435. end
  3436. else
  3437. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3438. DoOptimisation := False;
  3439. end;
  3440. hp2 := hp3;
  3441. end;
  3442. if DoOptimisation then
  3443. begin
  3444. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3445. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3446. { Flags are still in use - don't optimise }
  3447. DoOptimisation := False;
  3448. end;
  3449. end
  3450. else
  3451. DoOptimisation := False;
  3452. end;
  3453. if DoOptimisation then
  3454. begin
  3455. {$ifdef x86_64}
  3456. { OR only supports 32-bit sign-extended constants for 64-bit
  3457. instructions, so compensate for this if the constant is
  3458. encoded as a value greater than or equal to 2^31 }
  3459. if (taicpu(hp1).opsize = S_Q) and
  3460. (taicpu(hp1).oper[0]^.typ = top_const) and
  3461. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3462. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3463. {$endif x86_64}
  3464. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3465. taicpu(hp1).opcode := A_MOV;
  3466. RemoveCurrentP(p);
  3467. Result := True;
  3468. Exit;
  3469. end;
  3470. end;
  3471. end;
  3472. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3473. overwrites the original destination register. e.g.
  3474. movl ###,%reg2d
  3475. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3476. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3477. }
  3478. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3479. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3480. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3481. begin
  3482. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3483. begin
  3484. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3485. case taicpu(p).oper[0]^.typ of
  3486. top_const:
  3487. { We have something like:
  3488. movb $x, %regb
  3489. movzbl %regb,%regd
  3490. Change to:
  3491. movl $x, %regd
  3492. }
  3493. begin
  3494. case taicpu(hp1).opsize of
  3495. S_BW:
  3496. begin
  3497. convert_mov_value(A_MOVSX, $FF);
  3498. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3499. taicpu(p).opsize := S_W;
  3500. end;
  3501. S_BL:
  3502. begin
  3503. convert_mov_value(A_MOVSX, $FF);
  3504. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3505. taicpu(p).opsize := S_L;
  3506. end;
  3507. S_WL:
  3508. begin
  3509. convert_mov_value(A_MOVSX, $FFFF);
  3510. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3511. taicpu(p).opsize := S_L;
  3512. end;
  3513. {$ifdef x86_64}
  3514. S_BQ:
  3515. begin
  3516. convert_mov_value(A_MOVSX, $FF);
  3517. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3518. taicpu(p).opsize := S_Q;
  3519. end;
  3520. S_WQ:
  3521. begin
  3522. convert_mov_value(A_MOVSX, $FFFF);
  3523. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3524. taicpu(p).opsize := S_Q;
  3525. end;
  3526. S_LQ:
  3527. begin
  3528. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3529. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3530. taicpu(p).opsize := S_Q;
  3531. end;
  3532. {$endif x86_64}
  3533. else
  3534. { If hp1 was a MOV instruction, it should have been
  3535. optimised already }
  3536. InternalError(2020021001);
  3537. end;
  3538. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3539. RemoveInstruction(hp1);
  3540. Result := True;
  3541. Exit;
  3542. end;
  3543. top_ref:
  3544. begin
  3545. { We have something like:
  3546. movb mem, %regb
  3547. movzbl %regb,%regd
  3548. Change to:
  3549. movzbl mem, %regd
  3550. }
  3551. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3552. begin
  3553. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3554. taicpu(p).opcode := taicpu(hp1).opcode;
  3555. taicpu(p).opsize := taicpu(hp1).opsize;
  3556. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3557. RemoveInstruction(hp1);
  3558. Result := True;
  3559. Exit;
  3560. end;
  3561. end;
  3562. else
  3563. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3564. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3565. Exit;
  3566. end;
  3567. end
  3568. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3569. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3570. optimised }
  3571. else
  3572. begin
  3573. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3574. RemoveCurrentP(p);
  3575. Result := True;
  3576. Exit;
  3577. end;
  3578. end;
  3579. if (taicpu(hp1).opcode = A_MOV) and
  3580. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3581. begin
  3582. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3583. TransferUsedRegs(TmpUsedRegs);
  3584. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3585. { we have
  3586. mov x, %treg
  3587. mov %treg, y
  3588. }
  3589. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3590. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3591. begin
  3592. { we've got
  3593. mov x, %treg
  3594. mov %treg, y
  3595. with %treg is not used after }
  3596. case taicpu(p).oper[0]^.typ Of
  3597. { top_reg is covered by DeepMOVOpt }
  3598. top_const:
  3599. begin
  3600. { change
  3601. mov const, %treg
  3602. mov %treg, y
  3603. to
  3604. mov const, y
  3605. }
  3606. {$ifdef x86_64}
  3607. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3608. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3609. {$endif x86_64}
  3610. begin
  3611. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3612. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3613. RemoveCurrentP(p);
  3614. Result := True;
  3615. Exit;
  3616. end;
  3617. end;
  3618. top_ref:
  3619. case taicpu(hp1).oper[1]^.typ of
  3620. top_reg:
  3621. { change
  3622. mov mem, %treg
  3623. mov %treg, %reg
  3624. to
  3625. mov mem, %reg"
  3626. }
  3627. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3628. begin
  3629. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3630. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3631. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3632. RemoveInstruction(hp1);
  3633. Result := True;
  3634. Exit;
  3635. end
  3636. else if
  3637. { Make sure that if a reference is used, its
  3638. registers are not modified in between }
  3639. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3640. begin
  3641. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3642. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3643. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3644. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3645. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3646. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3647. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3648. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3649. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3650. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3651. RemoveCurrentP(p);
  3652. Result := True;
  3653. Exit;
  3654. end;
  3655. top_ref:
  3656. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3657. begin
  3658. {$ifdef x86_64}
  3659. { Look for the following to simplify:
  3660. mov x(mem1), %reg
  3661. mov %reg, y(mem2)
  3662. mov x+8(mem1), %reg
  3663. mov %reg, y+8(mem2)
  3664. Change to:
  3665. movdqu x(mem1), %xmmreg
  3666. movdqu %xmmreg, y(mem2)
  3667. ...but only as long as the memory blocks don't overlap
  3668. }
  3669. SourceRef := taicpu(p).oper[0]^.ref^;
  3670. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3671. if (taicpu(p).opsize = S_Q) and
  3672. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3673. GetNextInstruction(hp1, hp2) and
  3674. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3675. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3676. begin
  3677. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3678. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3679. Inc(SourceRef.offset, 8);
  3680. if UseAVX then
  3681. begin
  3682. MovAligned := A_VMOVDQA;
  3683. MovUnaligned := A_VMOVDQU;
  3684. end
  3685. else
  3686. begin
  3687. MovAligned := A_MOVDQA;
  3688. MovUnaligned := A_MOVDQU;
  3689. end;
  3690. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3691. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3692. begin
  3693. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3694. Inc(TargetRef.offset, 8);
  3695. if GetNextInstruction(hp2, hp3) and
  3696. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3697. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3698. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3699. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3700. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3701. begin
  3702. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3703. if NewMMReg <> NR_NO then
  3704. begin
  3705. { Remember that the offsets are 8 ahead }
  3706. if ((SourceRef.offset mod 16) = 8) and
  3707. (
  3708. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3709. (SourceRef.base = current_procinfo.framepointer) or
  3710. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3711. ) then
  3712. taicpu(p).opcode := MovAligned
  3713. else
  3714. taicpu(p).opcode := MovUnaligned;
  3715. taicpu(p).opsize := S_XMM;
  3716. taicpu(p).oper[1]^.reg := NewMMReg;
  3717. if ((TargetRef.offset mod 16) = 8) and
  3718. (
  3719. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3720. (TargetRef.base = current_procinfo.framepointer) or
  3721. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3722. ) then
  3723. taicpu(hp1).opcode := MovAligned
  3724. else
  3725. taicpu(hp1).opcode := MovUnaligned;
  3726. taicpu(hp1).opsize := S_XMM;
  3727. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3728. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3729. RemoveInstruction(hp2);
  3730. RemoveInstruction(hp3);
  3731. Result := True;
  3732. Exit;
  3733. end;
  3734. end;
  3735. end
  3736. else
  3737. begin
  3738. { See if the next references are 8 less rather than 8 greater }
  3739. Dec(SourceRef.offset, 16); { -8 the other way }
  3740. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3741. begin
  3742. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3743. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3744. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3745. GetNextInstruction(hp2, hp3) and
  3746. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3747. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3748. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3749. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3750. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3751. begin
  3752. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3753. if NewMMReg <> NR_NO then
  3754. begin
  3755. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3756. if ((SourceRef.offset mod 16) = 0) and
  3757. (
  3758. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3759. (SourceRef.base = current_procinfo.framepointer) or
  3760. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3761. ) then
  3762. taicpu(hp2).opcode := MovAligned
  3763. else
  3764. taicpu(hp2).opcode := MovUnaligned;
  3765. taicpu(hp2).opsize := S_XMM;
  3766. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3767. if ((TargetRef.offset mod 16) = 0) and
  3768. (
  3769. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3770. (TargetRef.base = current_procinfo.framepointer) or
  3771. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3772. ) then
  3773. taicpu(hp3).opcode := MovAligned
  3774. else
  3775. taicpu(hp3).opcode := MovUnaligned;
  3776. taicpu(hp3).opsize := S_XMM;
  3777. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3778. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3779. RemoveInstruction(hp1);
  3780. RemoveCurrentP(p);
  3781. Result := True;
  3782. Exit;
  3783. end;
  3784. end;
  3785. end;
  3786. end;
  3787. end;
  3788. {$endif x86_64}
  3789. end;
  3790. else
  3791. { The write target should be a reg or a ref }
  3792. InternalError(2021091601);
  3793. end;
  3794. else
  3795. ;
  3796. end;
  3797. end
  3798. else if (taicpu(p).oper[0]^.typ = top_const) and
  3799. { %treg is used afterwards, but all eventualities other
  3800. than the first MOV instruction being a constant are
  3801. covered by DeepMOVOpt, so only check for that }
  3802. (
  3803. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3804. not (cs_opt_size in current_settings.optimizerswitches) or
  3805. (taicpu(hp1).opsize = S_B)
  3806. ) and
  3807. (
  3808. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3809. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3810. ) then
  3811. begin
  3812. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3813. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3814. Include(OptsToCheck, aoc_ForceNewIteration);
  3815. end;
  3816. end;
  3817. end;
  3818. end;
  3819. if taicpu(p).oper[0]^.typ = top_reg then
  3820. begin
  3821. { oper[1] is a reference }
  3822. { Saves on a large number of dereferences }
  3823. p_SourceReg := taicpu(p).oper[0]^.reg;
  3824. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3825. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3826. else
  3827. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3828. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3829. begin
  3830. if taicpu(p).oper[1]^.typ = top_reg then
  3831. begin
  3832. p_TargetReg := taicpu(p).oper[1]^.reg;
  3833. { Change:
  3834. movl %reg1,%reg2
  3835. ...
  3836. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3837. ...
  3838. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3839. To:
  3840. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3841. ...
  3842. movl x(%reg1),%reg1
  3843. ...
  3844. movl %reg1,%regX
  3845. }
  3846. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3847. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3848. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3849. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3850. not RegModifiedBetween(p_TargetReg, p, hp1) and
  3851. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  3852. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3853. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3854. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  3855. begin
  3856. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3857. if RegInRef(p_TargetReg, SourceRef) and
  3858. { If %reg1 also appears in the second reference, then it will
  3859. not refer to the same memory block as the first reference }
  3860. not RegInRef(p_SourceReg, SourceRef) then
  3861. begin
  3862. { Check to see if the references match if %reg2 is changed to %reg1 }
  3863. if SourceRef.base = p_TargetReg then
  3864. SourceRef.base := p_SourceReg;
  3865. if SourceRef.index = p_TargetReg then
  3866. SourceRef.index := p_SourceReg;
  3867. { RefsEqual also checks to ensure both references are non-volatile }
  3868. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3869. begin
  3870. taicpu(hp2).loadreg(0, p_SourceReg);
  3871. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3872. Result := True;
  3873. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3874. begin
  3875. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3876. RemoveCurrentP(p);
  3877. Exit;
  3878. end
  3879. else
  3880. begin
  3881. { Check to see if %reg2 is no longer in use }
  3882. TransferUsedRegs(TmpUsedRegs);
  3883. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3884. UpdateUsedRegsBetween(TmpUsedRegs, tai(hp1.Next), hp2);
  3885. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3886. begin
  3887. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3888. RemoveCurrentP(p);
  3889. Exit;
  3890. end;
  3891. end;
  3892. { If we reach this point, p and hp1 weren't actually modified,
  3893. so we can do a bit more work on this pass }
  3894. end;
  3895. end;
  3896. end;
  3897. end;
  3898. end;
  3899. end;
  3900. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3901. { All the next optimisations require a next instruction }
  3902. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3903. Exit;
  3904. { Next instruction is also a MOV ? }
  3905. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3906. begin
  3907. if MatchOpType(taicpu(p), top_const, top_ref) and
  3908. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3909. TryConstMerge(p, hp1) then
  3910. begin
  3911. Result := True;
  3912. { In case we have four byte writes in a row, check for 2 more
  3913. right now so we don't have to wait for another iteration of
  3914. pass 1
  3915. }
  3916. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3917. case taicpu(p).opsize of
  3918. S_W:
  3919. begin
  3920. if GetNextInstruction(p, hp1) and
  3921. MatchInstruction(hp1, A_MOV, [S_B]) and
  3922. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3923. GetNextInstruction(hp1, hp2) and
  3924. MatchInstruction(hp2, A_MOV, [S_B]) and
  3925. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3926. { Try to merge the two bytes }
  3927. TryConstMerge(hp1, hp2) then
  3928. { Now try to merge the two words (hp2 will get deleted) }
  3929. TryConstMerge(p, hp1);
  3930. end;
  3931. S_L:
  3932. begin
  3933. { Though this only really benefits x86_64 and not i386, it
  3934. gets a potential optimisation done faster and hence
  3935. reduces the number of times OptPass1MOV is entered }
  3936. if GetNextInstruction(p, hp1) and
  3937. MatchInstruction(hp1, A_MOV, [S_W]) and
  3938. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3939. GetNextInstruction(hp1, hp2) and
  3940. MatchInstruction(hp2, A_MOV, [S_W]) and
  3941. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3942. { Try to merge the two words }
  3943. TryConstMerge(hp1, hp2) then
  3944. { This will always fail on i386, so don't bother
  3945. calling it unless we're doing x86_64 }
  3946. {$ifdef x86_64}
  3947. { Now try to merge the two longwords (hp2 will get deleted) }
  3948. TryConstMerge(p, hp1)
  3949. {$endif x86_64}
  3950. ;
  3951. end;
  3952. else
  3953. ;
  3954. end;
  3955. Exit;
  3956. end;
  3957. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3958. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3959. { mov reg1, mem1 or mov mem1, reg1
  3960. mov mem2, reg2 mov reg2, mem2}
  3961. begin
  3962. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3963. { mov reg1, mem1 or mov mem1, reg1
  3964. mov mem2, reg1 mov reg2, mem1}
  3965. begin
  3966. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3967. { Removes the second statement from
  3968. mov reg1, mem1/reg2
  3969. mov mem1/reg2, reg1 }
  3970. begin
  3971. if taicpu(p).oper[0]^.typ=top_reg then
  3972. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3973. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3974. RemoveInstruction(hp1);
  3975. Result:=true;
  3976. exit;
  3977. end
  3978. else
  3979. begin
  3980. TransferUsedRegs(TmpUsedRegs);
  3981. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3982. if (taicpu(p).oper[1]^.typ = top_ref) and
  3983. { mov reg1, mem1
  3984. mov mem2, reg1 }
  3985. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3986. GetNextInstruction(hp1, hp2) and
  3987. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3988. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3989. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3990. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3991. { change to
  3992. mov reg1, mem1 mov reg1, mem1
  3993. mov mem2, reg1 cmp reg1, mem2
  3994. cmp mem1, reg1
  3995. }
  3996. begin
  3997. RemoveInstruction(hp2);
  3998. taicpu(hp1).opcode := A_CMP;
  3999. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4000. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4001. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4002. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4003. end;
  4004. end;
  4005. end
  4006. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4007. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4008. begin
  4009. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4010. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4011. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4012. end
  4013. else
  4014. begin
  4015. TransferUsedRegs(TmpUsedRegs);
  4016. if GetNextInstruction(hp1, hp2) and
  4017. MatchOpType(taicpu(p),top_ref,top_reg) and
  4018. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4019. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4020. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4021. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4022. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4023. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4024. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4025. { mov mem1, %reg1
  4026. mov %reg1, mem2
  4027. mov mem2, reg2
  4028. to:
  4029. mov mem1, reg2
  4030. mov reg2, mem2}
  4031. begin
  4032. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4033. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4034. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4035. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4036. RemoveInstruction(hp2);
  4037. Result := True;
  4038. end
  4039. {$ifdef i386}
  4040. { this is enabled for i386 only, as the rules to create the reg sets below
  4041. are too complicated for x86-64, so this makes this code too error prone
  4042. on x86-64
  4043. }
  4044. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4045. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4046. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4047. { mov mem1, reg1 mov mem1, reg1
  4048. mov reg1, mem2 mov reg1, mem2
  4049. mov mem2, reg2 mov mem2, reg1
  4050. to: to:
  4051. mov mem1, reg1 mov mem1, reg1
  4052. mov mem1, reg2 mov reg1, mem2
  4053. mov reg1, mem2
  4054. or (if mem1 depends on reg1
  4055. and/or if mem2 depends on reg2)
  4056. to:
  4057. mov mem1, reg1
  4058. mov reg1, mem2
  4059. mov reg1, reg2
  4060. }
  4061. begin
  4062. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4063. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4064. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4065. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4066. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4067. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4068. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4069. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4070. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4071. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4072. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4073. end
  4074. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4075. begin
  4076. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4077. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4078. end
  4079. else
  4080. begin
  4081. RemoveInstruction(hp2);
  4082. end
  4083. {$endif i386}
  4084. ;
  4085. end;
  4086. end
  4087. { movl [mem1],reg1
  4088. movl [mem1],reg2
  4089. to
  4090. movl [mem1],reg1
  4091. movl reg1,reg2
  4092. }
  4093. else if not CheckMovMov2MovMov2(p, hp1) and
  4094. { movl const1,[mem1]
  4095. movl [mem1],reg1
  4096. to
  4097. movl const1,reg1
  4098. movl reg1,[mem1]
  4099. }
  4100. MatchOpType(Taicpu(p),top_const,top_ref) and
  4101. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4102. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4103. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4104. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4105. begin
  4106. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4107. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4108. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4109. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4110. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4111. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4112. Result:=true;
  4113. exit;
  4114. end;
  4115. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4116. end;
  4117. { search further than the next instruction for a mov (as long as it's not a jump) }
  4118. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4119. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4120. (taicpu(p).oper[1]^.typ = top_reg) and
  4121. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4122. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4123. begin
  4124. { we work with hp2 here, so hp1 can be still used later on when
  4125. checking for GetNextInstruction_p }
  4126. hp3 := hp1;
  4127. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4128. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4129. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4130. TransferUsedRegs(TmpUsedRegs);
  4131. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4132. if NotFirstIteration then
  4133. JumpTracking := TLinkedList.Create
  4134. else
  4135. JumpTracking := nil;
  4136. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4137. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4138. (hp2.typ=ait_instruction) do
  4139. begin
  4140. case taicpu(hp2).opcode of
  4141. A_POP:
  4142. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4143. begin
  4144. if not CrossJump and
  4145. not RegUsedBetween(p_TargetReg, p, hp2) then
  4146. begin
  4147. { We can remove the original MOV since the register
  4148. wasn't used between it and its popping from the stack }
  4149. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4150. RemoveCurrentp(p, hp1);
  4151. Result := True;
  4152. JumpTracking.Free;
  4153. Exit;
  4154. end;
  4155. { Can't go any further }
  4156. Break;
  4157. end;
  4158. A_MOV:
  4159. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4160. ((taicpu(p).oper[0]^.typ=top_const) or
  4161. ((taicpu(p).oper[0]^.typ=top_reg) and
  4162. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4163. )
  4164. ) then
  4165. begin
  4166. { we have
  4167. mov x, %treg
  4168. mov %treg, y
  4169. }
  4170. { We don't need to call UpdateUsedRegs for every instruction between
  4171. p and hp2 because the register we're concerned about will not
  4172. become deallocated (otherwise GetNextInstructionUsingReg would
  4173. have stopped at an earlier instruction). [Kit] }
  4174. TempRegUsed :=
  4175. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4176. RegReadByInstruction(p_TargetReg, hp3) or
  4177. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4178. case taicpu(p).oper[0]^.typ Of
  4179. top_reg:
  4180. begin
  4181. { change
  4182. mov %reg, %treg
  4183. mov %treg, y
  4184. to
  4185. mov %reg, y
  4186. }
  4187. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4188. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4189. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4190. begin
  4191. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4192. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4193. if TempRegUsed then
  4194. begin
  4195. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4196. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4197. { Set the start of the next GetNextInstructionUsingRegCond search
  4198. to start at the entry right before hp2 (which is about to be removed) }
  4199. hp3 := tai(hp2.Previous);
  4200. RemoveInstruction(hp2);
  4201. Include(OptsToCheck, aoc_ForceNewIteration);
  4202. { See if there's more we can optimise }
  4203. Continue;
  4204. end
  4205. else
  4206. begin
  4207. RemoveInstruction(hp2);
  4208. { We can remove the original MOV too }
  4209. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4210. RemoveCurrentP(p, hp1);
  4211. Result:=true;
  4212. JumpTracking.Free;
  4213. Exit;
  4214. end;
  4215. end
  4216. else
  4217. begin
  4218. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4219. taicpu(hp2).loadReg(0, p_SourceReg);
  4220. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4221. { Check to see if the register also appears in the reference }
  4222. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4223. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4224. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4225. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4226. begin
  4227. { Don't remove the first instruction if the temporary register is in use }
  4228. if not TempRegUsed then
  4229. begin
  4230. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4231. RemoveCurrentP(p, hp1);
  4232. Result:=true;
  4233. JumpTracking.Free;
  4234. Exit;
  4235. end;
  4236. { No need to set Result to True here. If there's another instruction later
  4237. on that can be optimised, it will be detected when the main Pass 1 loop
  4238. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4239. hp3 := hp2;
  4240. Continue;
  4241. end;
  4242. end;
  4243. end;
  4244. top_const:
  4245. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4246. begin
  4247. { change
  4248. mov const, %treg
  4249. mov %treg, y
  4250. to
  4251. mov const, y
  4252. }
  4253. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4254. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4255. begin
  4256. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4257. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4258. if TempRegUsed then
  4259. begin
  4260. { Don't remove the first instruction if the temporary register is in use }
  4261. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4262. { No need to set Result to True. If there's another instruction later on
  4263. that can be optimised, it will be detected when the main Pass 1 loop
  4264. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4265. end
  4266. else
  4267. begin
  4268. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4269. RemoveCurrentP(p, hp1);
  4270. Result:=true;
  4271. Exit;
  4272. end;
  4273. end;
  4274. end;
  4275. else
  4276. Internalerror(2019103001);
  4277. end;
  4278. end
  4279. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4280. begin
  4281. if not CrossJump and
  4282. not RegUsedBetween(p_TargetReg, p, hp2) and
  4283. not RegReadByInstruction(p_TargetReg, hp2) then
  4284. begin
  4285. { Register is not used before it is overwritten }
  4286. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4287. RemoveCurrentp(p, hp1);
  4288. Result := True;
  4289. Exit;
  4290. end;
  4291. if (taicpu(p).oper[0]^.typ = top_const) and
  4292. (taicpu(hp2).oper[0]^.typ = top_const) then
  4293. begin
  4294. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4295. begin
  4296. { Same value - register hasn't changed }
  4297. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4298. RemoveInstruction(hp2);
  4299. Include(OptsToCheck, aoc_ForceNewIteration);
  4300. { See if there's more we can optimise }
  4301. Continue;
  4302. end;
  4303. end;
  4304. {$ifdef x86_64}
  4305. end
  4306. { Change:
  4307. movl %reg1l,%reg2l
  4308. ...
  4309. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4310. To:
  4311. movl %reg1l,%reg2l
  4312. ...
  4313. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4314. If %reg1 = %reg3, convert to:
  4315. movl %reg1l,%reg2l
  4316. ...
  4317. andl %reg1l,%reg1l
  4318. }
  4319. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4320. (taicpu(p).oper[0]^.typ = top_reg) and
  4321. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4322. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4323. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4324. begin
  4325. TempRegUsed :=
  4326. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4327. RegReadByInstruction(p_TargetReg, hp3) or
  4328. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4329. taicpu(hp2).opsize := S_L;
  4330. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4331. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4332. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4333. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4334. begin
  4335. { %reg1 = %reg3 }
  4336. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4337. taicpu(hp2).opcode := A_AND;
  4338. end
  4339. else
  4340. begin
  4341. { %reg1 <> %reg3 }
  4342. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4343. end;
  4344. if not TempRegUsed then
  4345. begin
  4346. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4347. RemoveCurrentP(p, hp1);
  4348. Result := True;
  4349. Exit;
  4350. end
  4351. else
  4352. begin
  4353. { Initial instruction wasn't actually changed }
  4354. Include(OptsToCheck, aoc_ForceNewIteration);
  4355. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4356. appears below since %reg1 has technically changed }
  4357. if taicpu(hp2).opcode = A_AND then
  4358. Break;
  4359. end;
  4360. {$endif x86_64}
  4361. end
  4362. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4363. GetNextInstruction(hp2, hp4) and
  4364. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4365. { Optimise the following first:
  4366. movl [mem1],reg1
  4367. movl [mem1],reg2
  4368. to
  4369. movl [mem1],reg1
  4370. movl reg1,reg2
  4371. If [mem1] contains the target register and reg1 is the
  4372. the source register, this optimisation will get missed
  4373. and produce less efficient code later on.
  4374. }
  4375. if CheckMovMov2MovMov2(hp2, hp4) then
  4376. { Initial instruction wasn't actually changed }
  4377. Include(OptsToCheck, aoc_ForceNewIteration);
  4378. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4379. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4380. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4381. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4382. begin
  4383. {
  4384. Change from:
  4385. mov ###, %reg
  4386. ...
  4387. movs/z %reg,%reg (Same register, just different sizes)
  4388. To:
  4389. movs/z ###, %reg (Longer version)
  4390. ...
  4391. (remove)
  4392. }
  4393. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4394. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4395. { Keep the first instruction as mov if ### is a constant }
  4396. if taicpu(p).oper[0]^.typ = top_const then
  4397. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4398. else
  4399. begin
  4400. taicpu(p).opcode := taicpu(hp2).opcode;
  4401. taicpu(p).opsize := taicpu(hp2).opsize;
  4402. end;
  4403. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4404. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4405. RemoveInstruction(hp2);
  4406. Result := True;
  4407. JumpTracking.Free;
  4408. Exit;
  4409. end;
  4410. else
  4411. { Move down to the if-block below };
  4412. end;
  4413. { Also catches MOV/S/Z instructions that aren't modified }
  4414. if taicpu(p).oper[0]^.typ = top_reg then
  4415. begin
  4416. p_SourceReg := taicpu(p).oper[0]^.reg;
  4417. if
  4418. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4419. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4420. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4421. begin
  4422. Result := True;
  4423. { Just in case something didn't get modified (e.g. an
  4424. implicit register). Also, if it does read from this
  4425. register, then there's no longer an advantage to
  4426. changing the register on subsequent instructions.}
  4427. if not RegReadByInstruction(p_TargetReg, hp2) then
  4428. begin
  4429. { If a conditional jump was crossed, do not delete
  4430. the original MOV no matter what }
  4431. if not CrossJump and
  4432. { RegEndOfLife returns True if the register is
  4433. deallocated before the next instruction or has
  4434. been loaded with a new value }
  4435. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4436. begin
  4437. { We can remove the original MOV }
  4438. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4439. RemoveCurrentp(p, hp1);
  4440. JumpTracking.Free;
  4441. Result := True;
  4442. Exit;
  4443. end;
  4444. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4445. begin
  4446. { See if there's more we can optimise }
  4447. hp3 := hp2;
  4448. Continue;
  4449. end;
  4450. end;
  4451. end;
  4452. end;
  4453. { Break out of the while loop under normal circumstances }
  4454. Break;
  4455. end;
  4456. JumpTracking.Free;
  4457. end;
  4458. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4459. (taicpu(p).oper[1]^.typ = top_reg) and
  4460. (taicpu(p).opsize = S_L) and
  4461. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4462. (hp2.typ = ait_instruction) and
  4463. (taicpu(hp2).opcode = A_AND) and
  4464. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4465. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4466. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4467. ) then
  4468. begin
  4469. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4470. begin
  4471. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4472. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4473. begin
  4474. { Optimize out:
  4475. mov x, %reg
  4476. and ffffffffh, %reg
  4477. }
  4478. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4479. RemoveInstruction(hp2);
  4480. Result:=true;
  4481. exit;
  4482. end;
  4483. end;
  4484. end;
  4485. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4486. x >= RetOffset) as it doesn't do anything (it writes either to a
  4487. parameter or to the temporary storage room for the function
  4488. result)
  4489. }
  4490. if IsExitCode(hp1) and
  4491. (taicpu(p).oper[1]^.typ = top_ref) and
  4492. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4493. (
  4494. (
  4495. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4496. not (
  4497. assigned(current_procinfo.procdef.funcretsym) and
  4498. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4499. )
  4500. ) or
  4501. { Also discard writes to the stack that are below the base pointer,
  4502. as this is temporary storage rather than a function result on the
  4503. stack, say. }
  4504. (
  4505. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4506. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4507. )
  4508. ) then
  4509. begin
  4510. RemoveCurrentp(p, hp1);
  4511. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4512. RemoveLastDeallocForFuncRes(p);
  4513. Result:=true;
  4514. exit;
  4515. end;
  4516. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4517. begin
  4518. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4519. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4520. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4521. begin
  4522. { change
  4523. mov reg1, mem1
  4524. test/cmp x, mem1
  4525. to
  4526. mov reg1, mem1
  4527. test/cmp x, reg1
  4528. }
  4529. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4530. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4531. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4532. Result := True;
  4533. Exit;
  4534. end;
  4535. if DoMovCmpMemOpt(p, hp1) then
  4536. begin
  4537. Result := True;
  4538. Exit;
  4539. end;
  4540. end;
  4541. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4542. { If the flags register is in use, don't change the instruction to an
  4543. ADD otherwise this will scramble the flags. [Kit] }
  4544. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4545. begin
  4546. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4547. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4548. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4549. ) or
  4550. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4551. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4552. )
  4553. ) then
  4554. { mov reg1,ref
  4555. lea reg2,[reg1,reg2]
  4556. to
  4557. add reg2,ref}
  4558. begin
  4559. TransferUsedRegs(TmpUsedRegs);
  4560. { reg1 may not be used afterwards }
  4561. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4562. begin
  4563. Taicpu(hp1).opcode:=A_ADD;
  4564. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4565. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4566. RemoveCurrentp(p, hp1);
  4567. result:=true;
  4568. exit;
  4569. end;
  4570. end;
  4571. { If the LEA instruction can be converted into an arithmetic instruction,
  4572. it may be possible to then fold it in the next optimisation, otherwise
  4573. there's nothing more that can be optimised here. }
  4574. if not ConvertLEA(taicpu(hp1)) then
  4575. Exit;
  4576. end;
  4577. if (taicpu(p).oper[1]^.typ = top_reg) and
  4578. (hp1.typ = ait_instruction) and
  4579. GetNextInstruction(hp1, hp2) and
  4580. MatchInstruction(hp2,A_MOV,[]) and
  4581. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4582. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4583. (
  4584. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4585. {$ifdef x86_64}
  4586. or
  4587. (
  4588. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4589. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4590. )
  4591. {$endif x86_64}
  4592. ) then
  4593. begin
  4594. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4595. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4596. { change movsX/movzX reg/ref, reg2
  4597. add/sub/or/... reg3/$const, reg2
  4598. mov reg2 reg/ref
  4599. dealloc reg2
  4600. to
  4601. add/sub/or/... reg3/$const, reg/ref }
  4602. begin
  4603. TransferUsedRegs(TmpUsedRegs);
  4604. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4605. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4606. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4607. begin
  4608. { by example:
  4609. movswl %si,%eax movswl %si,%eax p
  4610. decl %eax addl %edx,%eax hp1
  4611. movw %ax,%si movw %ax,%si hp2
  4612. ->
  4613. movswl %si,%eax movswl %si,%eax p
  4614. decw %eax addw %edx,%eax hp1
  4615. movw %ax,%si movw %ax,%si hp2
  4616. }
  4617. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4618. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4619. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4620. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4621. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4622. {
  4623. ->
  4624. movswl %si,%eax movswl %si,%eax p
  4625. decw %si addw %dx,%si hp1
  4626. movw %ax,%si movw %ax,%si hp2
  4627. }
  4628. case taicpu(hp1).ops of
  4629. 1:
  4630. begin
  4631. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4632. if taicpu(hp1).oper[0]^.typ=top_reg then
  4633. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4634. end;
  4635. 2:
  4636. begin
  4637. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4638. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4639. (taicpu(hp1).opcode<>A_SHL) and
  4640. (taicpu(hp1).opcode<>A_SHR) and
  4641. (taicpu(hp1).opcode<>A_SAR) then
  4642. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4643. end;
  4644. else
  4645. internalerror(2008042701);
  4646. end;
  4647. {
  4648. ->
  4649. decw %si addw %dx,%si p
  4650. }
  4651. RemoveInstruction(hp2);
  4652. RemoveCurrentP(p, hp1);
  4653. Result:=True;
  4654. Exit;
  4655. end;
  4656. end;
  4657. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4658. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4659. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4660. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4661. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4662. )
  4663. {$ifdef i386}
  4664. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4665. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4666. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4667. {$endif i386}
  4668. then
  4669. { change movsX/movzX reg/ref, reg2
  4670. add/sub/or/... regX/$const, reg2
  4671. mov reg2, reg3
  4672. dealloc reg2
  4673. to
  4674. movsX/movzX reg/ref, reg3
  4675. add/sub/or/... reg3/$const, reg3
  4676. }
  4677. begin
  4678. TransferUsedRegs(TmpUsedRegs);
  4679. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4680. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4681. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4682. begin
  4683. { by example:
  4684. movswl %si,%eax movswl %si,%eax p
  4685. decl %eax addl %edx,%eax hp1
  4686. movw %ax,%si movw %ax,%si hp2
  4687. ->
  4688. movswl %si,%eax movswl %si,%eax p
  4689. decw %eax addw %edx,%eax hp1
  4690. movw %ax,%si movw %ax,%si hp2
  4691. }
  4692. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4693. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4694. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4695. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4696. { limit size of constants as well to avoid assembler errors, but
  4697. check opsize to avoid overflow when left shifting the 1 }
  4698. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4699. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4700. {$ifdef x86_64}
  4701. { Be careful of, for example:
  4702. movl %reg1,%reg2
  4703. addl %reg3,%reg2
  4704. movq %reg2,%reg4
  4705. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4706. }
  4707. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4708. begin
  4709. taicpu(hp2).changeopsize(S_L);
  4710. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4711. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4712. end;
  4713. {$endif x86_64}
  4714. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4715. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4716. if taicpu(p).oper[0]^.typ=top_reg then
  4717. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4718. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4719. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4720. {
  4721. ->
  4722. movswl %si,%eax movswl %si,%eax p
  4723. decw %si addw %dx,%si hp1
  4724. movw %ax,%si movw %ax,%si hp2
  4725. }
  4726. case taicpu(hp1).ops of
  4727. 1:
  4728. begin
  4729. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4730. if taicpu(hp1).oper[0]^.typ=top_reg then
  4731. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4732. end;
  4733. 2:
  4734. begin
  4735. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4736. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4737. (taicpu(hp1).opcode<>A_SHL) and
  4738. (taicpu(hp1).opcode<>A_SHR) and
  4739. (taicpu(hp1).opcode<>A_SAR) then
  4740. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4741. end;
  4742. else
  4743. internalerror(2018111801);
  4744. end;
  4745. {
  4746. ->
  4747. decw %si addw %dx,%si p
  4748. }
  4749. RemoveInstruction(hp2);
  4750. end;
  4751. end;
  4752. end;
  4753. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4754. GetNextInstruction(hp1, hp2) and
  4755. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4756. MatchOperand(Taicpu(p).oper[0]^,0) and
  4757. (Taicpu(p).oper[1]^.typ = top_reg) and
  4758. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4759. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4760. { mov reg1,0
  4761. bts reg1,operand1 --> mov reg1,operand2
  4762. or reg1,operand2 bts reg1,operand1}
  4763. begin
  4764. Taicpu(hp2).opcode:=A_MOV;
  4765. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4766. asml.remove(hp1);
  4767. insertllitem(hp2,hp2.next,hp1);
  4768. RemoveCurrentp(p, hp1);
  4769. Result:=true;
  4770. exit;
  4771. end;
  4772. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4773. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4774. GetNextInstruction(hp1, hp2) and
  4775. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4776. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4777. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4778. { change
  4779. mov reg1,reg2
  4780. sub reg3,reg2
  4781. cmp reg3,reg1
  4782. into
  4783. mov reg1,reg2
  4784. sub reg3,reg2
  4785. }
  4786. begin
  4787. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4788. RemoveInstruction(hp2);
  4789. Result:=true;
  4790. exit;
  4791. end;
  4792. {
  4793. mov ref,reg0
  4794. <op> reg0,reg1
  4795. dealloc reg0
  4796. to
  4797. <op> ref,reg1
  4798. }
  4799. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4800. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4801. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4802. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4803. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4804. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4805. begin
  4806. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4807. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4808. RemoveCurrentp(p, hp1);
  4809. Result:=true;
  4810. exit;
  4811. end;
  4812. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4813. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4814. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4815. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4816. begin
  4817. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4818. {$ifdef x86_64}
  4819. { Convert:
  4820. movq x(ref),%reg64
  4821. shrq y,%reg64
  4822. To:
  4823. movl x+4(ref),%reg32
  4824. shrl y-32,%reg32 (Remove if y = 32)
  4825. }
  4826. if (taicpu(p).opsize = S_Q) and
  4827. (taicpu(hp1).opcode = A_SHR) and
  4828. (taicpu(hp1).oper[0]^.val >= 32) then
  4829. begin
  4830. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4831. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4832. { Convert to 32-bit }
  4833. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4834. taicpu(p).opsize := S_L;
  4835. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4836. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4837. if (taicpu(hp1).oper[0]^.val = 32) then
  4838. begin
  4839. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4840. RemoveInstruction(hp1);
  4841. end
  4842. else
  4843. begin
  4844. { This will potentially open up more arithmetic operations since
  4845. the peephole optimizer now has a big hint that only the lower
  4846. 32 bits are currently in use (and opcodes are smaller in size) }
  4847. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4848. taicpu(hp1).opsize := S_L;
  4849. Dec(taicpu(hp1).oper[0]^.val, 32);
  4850. DebugMsg(SPeepholeOptimization + PreMessage +
  4851. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4852. end;
  4853. Result := True;
  4854. Exit;
  4855. end;
  4856. {$endif x86_64}
  4857. { Convert:
  4858. movl x(ref),%reg
  4859. shrl $24,%reg
  4860. To:
  4861. movzbl x+3(ref),%reg
  4862. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4863. Also accept sar instead of shr, but convert to movsx instead of movzx
  4864. }
  4865. if taicpu(hp1).opcode = A_SHR then
  4866. MovUnaligned := A_MOVZX
  4867. else
  4868. MovUnaligned := A_MOVSX;
  4869. NewSize := S_NO;
  4870. NewOffset := 0;
  4871. case taicpu(p).opsize of
  4872. S_B:
  4873. { No valid combinations };
  4874. S_W:
  4875. if (taicpu(hp1).oper[0]^.val = 8) then
  4876. begin
  4877. NewSize := S_BW;
  4878. NewOffset := 1;
  4879. end;
  4880. S_L:
  4881. case taicpu(hp1).oper[0]^.val of
  4882. 16:
  4883. begin
  4884. NewSize := S_WL;
  4885. NewOffset := 2;
  4886. end;
  4887. 24:
  4888. begin
  4889. NewSize := S_BL;
  4890. NewOffset := 3;
  4891. end;
  4892. else
  4893. ;
  4894. end;
  4895. {$ifdef x86_64}
  4896. S_Q:
  4897. case taicpu(hp1).oper[0]^.val of
  4898. 32:
  4899. begin
  4900. if taicpu(hp1).opcode = A_SAR then
  4901. begin
  4902. { 32-bit to 64-bit is a distinct instruction }
  4903. MovUnaligned := A_MOVSXD;
  4904. NewSize := S_LQ;
  4905. NewOffset := 4;
  4906. end
  4907. else
  4908. { Should have been handled by MovShr2Mov above }
  4909. InternalError(2022081811);
  4910. end;
  4911. 48:
  4912. begin
  4913. NewSize := S_WQ;
  4914. NewOffset := 6;
  4915. end;
  4916. 56:
  4917. begin
  4918. NewSize := S_BQ;
  4919. NewOffset := 7;
  4920. end;
  4921. else
  4922. ;
  4923. end;
  4924. {$endif x86_64}
  4925. else
  4926. InternalError(2022081810);
  4927. end;
  4928. if (NewSize <> S_NO) and
  4929. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4930. begin
  4931. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4932. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4933. debug_op2str(MovUnaligned);
  4934. {$ifdef x86_64}
  4935. if MovUnaligned <> A_MOVSXD then
  4936. { Don't add size suffix for MOVSXD }
  4937. {$endif x86_64}
  4938. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4939. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4940. taicpu(p).opcode := MovUnaligned;
  4941. taicpu(p).opsize := NewSize;
  4942. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4943. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4944. RemoveInstruction(hp1);
  4945. Result := True;
  4946. Exit;
  4947. end;
  4948. end;
  4949. { Backward optimisation shared with OptPass2MOV }
  4950. if FuncMov2Func(p, hp1) then
  4951. begin
  4952. Result := True;
  4953. Exit;
  4954. end;
  4955. end;
  4956. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4957. var
  4958. hp1 : tai;
  4959. begin
  4960. Result:=false;
  4961. if taicpu(p).ops <> 2 then
  4962. exit;
  4963. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4964. GetNextInstruction(p,hp1) then
  4965. begin
  4966. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4967. (taicpu(hp1).ops = 2) then
  4968. begin
  4969. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4970. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4971. { movXX reg1, mem1 or movXX mem1, reg1
  4972. movXX mem2, reg2 movXX reg2, mem2}
  4973. begin
  4974. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4975. { movXX reg1, mem1 or movXX mem1, reg1
  4976. movXX mem2, reg1 movXX reg2, mem1}
  4977. begin
  4978. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4979. begin
  4980. { Removes the second statement from
  4981. movXX reg1, mem1/reg2
  4982. movXX mem1/reg2, reg1
  4983. }
  4984. if taicpu(p).oper[0]^.typ=top_reg then
  4985. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4986. { Removes the second statement from
  4987. movXX mem1/reg1, reg2
  4988. movXX reg2, mem1/reg1
  4989. }
  4990. if (taicpu(p).oper[1]^.typ=top_reg) and
  4991. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4992. begin
  4993. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4994. RemoveInstruction(hp1);
  4995. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4996. Result:=true;
  4997. exit;
  4998. end
  4999. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5000. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5001. begin
  5002. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5003. RemoveInstruction(hp1);
  5004. Result:=true;
  5005. exit;
  5006. end;
  5007. end
  5008. end;
  5009. end;
  5010. end;
  5011. end;
  5012. end;
  5013. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5014. var
  5015. hp1 : tai;
  5016. begin
  5017. result:=false;
  5018. { replace
  5019. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5020. MovX %mreg2,%mreg1
  5021. dealloc %mreg2
  5022. by
  5023. <Op>X %mreg2,%mreg1
  5024. ?
  5025. }
  5026. if GetNextInstruction(p,hp1) and
  5027. { we mix single and double opperations here because we assume that the compiler
  5028. generates vmovapd only after double operations and vmovaps only after single operations }
  5029. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5030. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5031. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5032. (taicpu(p).oper[0]^.typ=top_reg) then
  5033. begin
  5034. TransferUsedRegs(TmpUsedRegs);
  5035. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5036. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5037. begin
  5038. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5039. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5040. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5041. RemoveInstruction(hp1);
  5042. result:=true;
  5043. end;
  5044. end;
  5045. end;
  5046. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5047. var
  5048. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5049. JumpLabel, JumpLabel_dist: TAsmLabel;
  5050. FirstValue, SecondValue: TCGInt;
  5051. function OptimizeJump(var InputP: tai): Boolean;
  5052. var
  5053. TempBool: Boolean;
  5054. begin
  5055. Result := False;
  5056. TempBool := True;
  5057. if DoJumpOptimizations(InputP, TempBool) or
  5058. not TempBool then
  5059. begin
  5060. Result := True;
  5061. if Assigned(InputP) then
  5062. begin
  5063. { CollapseZeroDistJump will be set to the label or an align
  5064. before it after the jump if it optimises, whether or not
  5065. the label is live or dead }
  5066. if (InputP.typ = ait_align) or
  5067. (
  5068. (InputP.typ = ait_label) and
  5069. not (tai_label(InputP).labsym.is_used)
  5070. ) then
  5071. GetNextInstruction(InputP, InputP);
  5072. end;
  5073. Exit;
  5074. end;
  5075. end;
  5076. begin
  5077. Result := False;
  5078. if (taicpu(p).oper[0]^.typ = top_const) and
  5079. (taicpu(p).oper[0]^.val <> -1) then
  5080. begin
  5081. { Convert unsigned maximum constants to -1 to aid optimisation }
  5082. case taicpu(p).opsize of
  5083. S_B:
  5084. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5085. begin
  5086. taicpu(p).oper[0]^.val := -1;
  5087. Result := True;
  5088. Exit;
  5089. end;
  5090. S_W:
  5091. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5092. begin
  5093. taicpu(p).oper[0]^.val := -1;
  5094. Result := True;
  5095. Exit;
  5096. end;
  5097. S_L:
  5098. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5099. begin
  5100. taicpu(p).oper[0]^.val := -1;
  5101. Result := True;
  5102. Exit;
  5103. end;
  5104. {$ifdef x86_64}
  5105. S_Q:
  5106. { Storing anything greater than $7FFFFFFF is not possible so do
  5107. nothing };
  5108. {$endif x86_64}
  5109. else
  5110. InternalError(2021121001);
  5111. end;
  5112. end;
  5113. if GetNextInstruction(p, hp1) and
  5114. TrySwapMovCmp(p, hp1) then
  5115. begin
  5116. Result := True;
  5117. Exit;
  5118. end;
  5119. p_label := nil;
  5120. JumpLabel := nil;
  5121. if MatchInstruction(hp1, A_Jcc, []) then
  5122. begin
  5123. if OptimizeJump(hp1) then
  5124. begin
  5125. Result := True;
  5126. if Assigned(hp1) then
  5127. begin
  5128. { CollapseZeroDistJump will be set to the label or an align
  5129. before it after the jump if it optimises, whether or not
  5130. the label is live or dead }
  5131. if (hp1.typ = ait_align) or
  5132. (
  5133. (hp1.typ = ait_label) and
  5134. not (tai_label(hp1).labsym.is_used)
  5135. ) then
  5136. GetNextInstruction(hp1, hp1);
  5137. end;
  5138. TransferUsedRegs(TmpUsedRegs);
  5139. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5140. if not Assigned(hp1) or
  5141. (
  5142. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5143. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5144. ) then
  5145. begin
  5146. { No more conditional jumps; conditional statement is no longer required }
  5147. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5148. RemoveCurrentP(p);
  5149. end;
  5150. Exit;
  5151. end;
  5152. if IsJumpToLabel(taicpu(hp1)) then
  5153. begin
  5154. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5155. if Assigned(JumpLabel) then
  5156. p_label := getlabelwithsym(JumpLabel);
  5157. end;
  5158. end;
  5159. { Search for:
  5160. test $x,(reg/ref)
  5161. jne @lbl1
  5162. test $y,(reg/ref) (same register or reference)
  5163. jne @lbl1
  5164. Change to:
  5165. test $(x or y),(reg/ref)
  5166. jne @lbl1
  5167. (Note, this doesn't work with je instead of jne)
  5168. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5169. Also search for:
  5170. test $x,(reg/ref)
  5171. je @lbl1
  5172. ...
  5173. test $y,(reg/ref)
  5174. je/jne @lbl2
  5175. If (x or y) = x, then the second jump is deterministic
  5176. }
  5177. if (
  5178. (
  5179. (taicpu(p).oper[0]^.typ = top_const) or
  5180. (
  5181. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5182. (taicpu(p).oper[0]^.typ = top_reg) and
  5183. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5184. )
  5185. ) and
  5186. MatchInstruction(hp1, A_JCC, [])
  5187. ) then
  5188. begin
  5189. if (taicpu(p).oper[0]^.typ = top_reg) and
  5190. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5191. FirstValue := -1
  5192. else
  5193. FirstValue := taicpu(p).oper[0]^.val;
  5194. { If we have several test/jne's in a row, it might be the case that
  5195. the second label doesn't go to the same location, but the one
  5196. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5197. so accommodate for this with a while loop.
  5198. }
  5199. hp1_last := hp1;
  5200. while (
  5201. (
  5202. (taicpu(p).oper[1]^.typ = top_reg) and
  5203. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5204. ) or GetNextInstruction(hp1_last, p_dist)
  5205. ) and (p_dist.typ = ait_instruction) do
  5206. begin
  5207. if (
  5208. (
  5209. (taicpu(p_dist).opcode = A_TEST) and
  5210. (
  5211. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5212. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5213. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5214. )
  5215. ) or
  5216. (
  5217. { cmp 0,%reg = test %reg,%reg }
  5218. (taicpu(p_dist).opcode = A_CMP) and
  5219. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5220. )
  5221. ) and
  5222. { Make sure the destination operands are actually the same }
  5223. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5224. GetNextInstruction(p_dist, hp1_dist) and
  5225. MatchInstruction(hp1_dist, A_JCC, []) then
  5226. begin
  5227. if OptimizeJump(hp1_dist) then
  5228. begin
  5229. Result := True;
  5230. Exit;
  5231. end;
  5232. if
  5233. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5234. (
  5235. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5236. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5237. ) then
  5238. SecondValue := -1
  5239. else
  5240. SecondValue := taicpu(p_dist).oper[0]^.val;
  5241. { If both of the TEST constants are identical, delete the
  5242. second TEST that is unnecessary (be careful though, just
  5243. in case the flags are modified in between) }
  5244. if (FirstValue = SecondValue) then
  5245. begin
  5246. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5247. begin
  5248. { Since the second jump's condition is a subset of the first, we
  5249. know it will never branch because the first jump dominates it.
  5250. Get it out of the way now rather than wait for the jump
  5251. optimisations for a speed boost. }
  5252. if IsJumpToLabel(taicpu(hp1_dist)) then
  5253. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5254. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5255. RemoveInstruction(hp1_dist);
  5256. Result := True;
  5257. end
  5258. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5259. begin
  5260. { If the inverse of the first condition is a subset of the second,
  5261. the second one will definitely branch if the first one doesn't }
  5262. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5263. { We can remove the TEST instruction too }
  5264. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5265. RemoveInstruction(p_dist);
  5266. MakeUnconditional(taicpu(hp1_dist));
  5267. RemoveDeadCodeAfterJump(hp1_dist);
  5268. { Since the jump is now unconditional, we can't
  5269. continue any further with this particular
  5270. optimisation. The original TEST is still intact
  5271. though, so there might be something else we can
  5272. do }
  5273. Include(OptsToCheck, aoc_ForceNewIteration);
  5274. Break;
  5275. end;
  5276. if Result or
  5277. { If a jump wasn't removed or made unconditional, only
  5278. remove the identical TEST instruction if the flags
  5279. weren't modified }
  5280. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5281. begin
  5282. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5283. RemoveInstruction(p_dist);
  5284. { If the jump was removed or made unconditional, we
  5285. don't need to allocate NR_DEFAULTFLAGS over the
  5286. entire range }
  5287. if not Result then
  5288. begin
  5289. { Mark the flags as 'in use' over the entire range }
  5290. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5291. { Speed gain - continue search from the Jcc instruction }
  5292. hp1_last := hp1_dist;
  5293. { Only the TEST instruction was removed, and the
  5294. original was unchanged, so we can safely do
  5295. another iteration of the while loop }
  5296. Include(OptsToCheck, aoc_ForceNewIteration);
  5297. Continue;
  5298. end;
  5299. Exit;
  5300. end;
  5301. end;
  5302. hp1_last := nil;
  5303. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5304. (
  5305. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5306. { Always adjacent under -O2 and under }
  5307. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5308. (
  5309. GetNextInstruction(hp1, hp1_last) and
  5310. (hp1_last = p_dist)
  5311. )
  5312. ) and
  5313. (
  5314. (
  5315. { Test the following variant:
  5316. test $x,(reg/ref)
  5317. jne @lbl1
  5318. test $y,(reg/ref)
  5319. je @lbl2
  5320. @lbl1:
  5321. Becomes:
  5322. test $(x or y),(reg/ref)
  5323. je @lbl2
  5324. @lbl1: (may become a dead label)
  5325. }
  5326. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5327. GetNextInstruction(hp1_dist, hp1_last) and
  5328. (hp1_last = p_label)
  5329. ) or
  5330. (
  5331. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5332. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5333. then the second jump will never branch, so it can also be
  5334. removed regardless of where it goes }
  5335. (
  5336. (FirstValue = -1) or
  5337. (SecondValue = -1) or
  5338. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5339. )
  5340. )
  5341. ) then
  5342. begin
  5343. { Same jump location... can be a register since nothing's changed }
  5344. { If any of the entries are equivalent to test %reg,%reg, then the
  5345. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5346. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5347. if (hp1_last = p_label) then
  5348. begin
  5349. { Variant }
  5350. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5351. RemoveInstruction(p_dist);
  5352. if Assigned(JumpLabel) then
  5353. JumpLabel.decrefs;
  5354. RemoveInstruction(hp1);
  5355. end
  5356. else
  5357. begin
  5358. { Only remove the second test if no jumps or other conditional instructions follow }
  5359. TransferUsedRegs(TmpUsedRegs);
  5360. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5361. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5362. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5363. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5364. begin
  5365. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5366. RemoveInstruction(p_dist);
  5367. { Remove the first jump, not the second, to keep
  5368. any register deallocations between the second
  5369. TEST/JNE pair in the same place. Aids future
  5370. optimisation. }
  5371. if Assigned(JumpLabel) then
  5372. JumpLabel.decrefs;
  5373. RemoveInstruction(hp1);
  5374. end
  5375. else
  5376. begin
  5377. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5378. if IsJumpToLabel(taicpu(hp1_dist)) then
  5379. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5380. { Remove second jump in this instance }
  5381. RemoveInstruction(hp1_dist);
  5382. end;
  5383. end;
  5384. Result := True;
  5385. Exit;
  5386. end;
  5387. end;
  5388. if { If -O2 and under, it may stop on any old instruction }
  5389. (cs_opt_level3 in current_settings.optimizerswitches) and
  5390. (taicpu(p).oper[1]^.typ = top_reg) and
  5391. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5392. begin
  5393. hp1_last := p_dist;
  5394. Continue;
  5395. end;
  5396. Break;
  5397. end;
  5398. end;
  5399. { Search for:
  5400. test %reg,%reg
  5401. j(c1) @lbl1
  5402. ...
  5403. @lbl:
  5404. test %reg,%reg (same register)
  5405. j(c2) @lbl2
  5406. If c2 is a subset of c1, change to:
  5407. test %reg,%reg
  5408. j(c1) @lbl2
  5409. (@lbl1 may become a dead label as a result)
  5410. }
  5411. if (taicpu(p).oper[1]^.typ = top_reg) and
  5412. (taicpu(p).oper[0]^.typ = top_reg) and
  5413. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5414. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5415. Assigned(p_label) and
  5416. GetNextInstruction(p_label, p_dist) and
  5417. MatchInstruction(p_dist, A_TEST, []) and
  5418. { It's fine if the second test uses smaller sub-registers }
  5419. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5420. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5421. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5422. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5423. GetNextInstruction(p_dist, hp1_dist) and
  5424. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5425. begin
  5426. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5427. if JumpLabel = JumpLabel_dist then
  5428. { This is an infinite loop }
  5429. Exit;
  5430. { Best optimisation when the first condition is a subset (or equal) of the second }
  5431. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5432. begin
  5433. { Any registers used here will already be allocated }
  5434. if Assigned(JumpLabel) then
  5435. JumpLabel.DecRefs;
  5436. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5437. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5438. Result := True;
  5439. Exit;
  5440. end;
  5441. end;
  5442. end;
  5443. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5444. var
  5445. hp1, hp2: tai;
  5446. ActiveReg: TRegister;
  5447. OldOffset: asizeint;
  5448. ThisConst: TCGInt;
  5449. function RegDeallocated: Boolean;
  5450. begin
  5451. TransferUsedRegs(TmpUsedRegs);
  5452. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5453. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5454. end;
  5455. begin
  5456. result:=false;
  5457. hp1 := nil;
  5458. { replace
  5459. addX const,%reg1
  5460. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5461. dealloc %reg1
  5462. by
  5463. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5464. }
  5465. if MatchOpType(taicpu(p),top_const,top_reg) then
  5466. begin
  5467. ActiveReg := taicpu(p).oper[1]^.reg;
  5468. { Ensures the entire register was updated }
  5469. if (taicpu(p).opsize >= S_L) and
  5470. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5471. MatchInstruction(hp1,A_LEA,[]) and
  5472. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5473. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5474. (
  5475. { Cover the case where the register in the reference is also the destination register }
  5476. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5477. (
  5478. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5479. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5480. RegDeallocated
  5481. )
  5482. ) then
  5483. begin
  5484. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5485. {$push}
  5486. {$R-}{$Q-}
  5487. { Explicitly disable overflow checking for these offset calculation
  5488. as those do not matter for the final result }
  5489. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5490. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5491. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5492. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5493. {$pop}
  5494. {$ifdef x86_64}
  5495. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5496. begin
  5497. { Overflow; abort }
  5498. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5499. end
  5500. else
  5501. {$endif x86_64}
  5502. begin
  5503. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5504. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5505. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5506. RemoveCurrentP(p, hp1)
  5507. else
  5508. RemoveCurrentP(p);
  5509. result:=true;
  5510. Exit;
  5511. end;
  5512. end;
  5513. if (
  5514. { Save calling GetNextInstructionUsingReg again }
  5515. Assigned(hp1) or
  5516. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5517. ) and
  5518. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5519. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5520. begin
  5521. if taicpu(hp1).oper[0]^.typ = top_const then
  5522. begin
  5523. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5524. if taicpu(hp1).opcode = A_ADD then
  5525. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5526. else
  5527. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5528. Result := True;
  5529. { Handle any overflows }
  5530. case taicpu(p).opsize of
  5531. S_B:
  5532. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5533. S_W:
  5534. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5535. S_L:
  5536. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5537. {$ifdef x86_64}
  5538. S_Q:
  5539. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5540. { Overflow; abort }
  5541. Result := False
  5542. else
  5543. taicpu(p).oper[0]^.val := ThisConst;
  5544. {$endif x86_64}
  5545. else
  5546. InternalError(2021102610);
  5547. end;
  5548. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5549. if Result then
  5550. begin
  5551. if (taicpu(p).oper[0]^.val < 0) and
  5552. (
  5553. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5554. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5555. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5556. ) then
  5557. begin
  5558. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5559. taicpu(p).opcode := A_SUB;
  5560. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5561. end
  5562. else
  5563. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5564. RemoveInstruction(hp1);
  5565. end;
  5566. end
  5567. else
  5568. begin
  5569. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5570. TransferUsedRegs(TmpUsedRegs);
  5571. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5572. hp2 := p;
  5573. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5574. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5575. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5576. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5577. begin
  5578. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5579. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5580. Asml.Remove(p);
  5581. Asml.InsertAfter(p, hp1);
  5582. p := hp1;
  5583. Result := True;
  5584. Exit;
  5585. end;
  5586. end;
  5587. end;
  5588. if DoArithCombineOpt(p) then
  5589. Result:=true;
  5590. end;
  5591. end;
  5592. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5593. var
  5594. hp1, hp2: tai;
  5595. ref: Integer;
  5596. saveref: treference;
  5597. offsetcalc: Int64;
  5598. TempReg: TRegister;
  5599. Multiple: TCGInt;
  5600. Adjacent, IntermediateRegDiscarded: Boolean;
  5601. begin
  5602. Result:=false;
  5603. { play save and throw an error if LEA uses a seg register prefix,
  5604. this is most likely an error somewhere else }
  5605. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5606. internalerror(2022022001);
  5607. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5608. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5609. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5610. (
  5611. { do not mess with leas accessing the stack pointer
  5612. unless it's a null operation }
  5613. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5614. (
  5615. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5616. (taicpu(p).oper[0]^.ref^.offset = 0)
  5617. )
  5618. ) and
  5619. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5620. begin
  5621. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5622. begin
  5623. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5624. begin
  5625. taicpu(p).opcode := A_MOV;
  5626. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5627. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5628. end
  5629. else
  5630. begin
  5631. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5632. RemoveCurrentP(p);
  5633. end;
  5634. Result:=true;
  5635. exit;
  5636. end
  5637. else if (
  5638. { continue to use lea to adjust the stack pointer,
  5639. it is the recommended way, but only if not optimizing for size }
  5640. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5641. (cs_opt_size in current_settings.optimizerswitches)
  5642. ) and
  5643. { If the flags register is in use, don't change the instruction
  5644. to an ADD otherwise this will scramble the flags. [Kit] }
  5645. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5646. ConvertLEA(taicpu(p)) then
  5647. begin
  5648. Result:=true;
  5649. exit;
  5650. end;
  5651. end;
  5652. { Don't optimise if the stack or frame pointer is the destination register }
  5653. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5654. Exit;
  5655. if GetNextInstruction(p,hp1) and
  5656. (hp1.typ=ait_instruction) then
  5657. begin
  5658. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5659. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5660. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5661. begin
  5662. TransferUsedRegs(TmpUsedRegs);
  5663. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5664. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5665. begin
  5666. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5667. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5668. RemoveInstruction(hp1);
  5669. result:=true;
  5670. exit;
  5671. end;
  5672. end;
  5673. { changes
  5674. lea <ref1>, reg1
  5675. <op> ...,<ref. with reg1>,...
  5676. to
  5677. <op> ...,<ref1>,... }
  5678. { find a reference which uses reg1 }
  5679. if (taicpu(hp1).ops>=1) and (taicpu(hp1).oper[0]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^) then
  5680. ref:=0
  5681. else if (taicpu(hp1).ops>=2) and (taicpu(hp1).oper[1]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^) then
  5682. ref:=1
  5683. else
  5684. ref:=-1;
  5685. if (ref<>-1) and
  5686. { reg1 must be either the base or the index }
  5687. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5688. begin
  5689. { reg1 can be removed from the reference }
  5690. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5691. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5692. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5693. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5694. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5695. else
  5696. Internalerror(2019111201);
  5697. { check if the can insert all data of the lea into the second instruction }
  5698. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5699. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5700. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5701. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5702. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5703. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5704. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5705. {$ifdef x86_64}
  5706. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5707. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5708. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5709. )
  5710. {$endif x86_64}
  5711. then
  5712. begin
  5713. { reg1 might not used by the second instruction after it is remove from the reference }
  5714. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5715. begin
  5716. TransferUsedRegs(TmpUsedRegs);
  5717. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5718. { reg1 is not updated so it might not be used afterwards }
  5719. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5720. begin
  5721. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5722. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5723. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5724. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5725. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5726. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5727. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5728. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5729. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5730. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5731. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5732. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5733. RemoveCurrentP(p, hp1);
  5734. result:=true;
  5735. exit;
  5736. end
  5737. end;
  5738. end;
  5739. { recover }
  5740. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5741. end;
  5742. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5743. if Adjacent or
  5744. { Check further ahead (up to 2 instructions ahead for -O2) }
  5745. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5746. begin
  5747. { Check common LEA/LEA conditions }
  5748. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5749. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5750. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5751. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5752. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5753. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5754. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5755. (
  5756. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5757. calling it (since it calls GetNextInstruction) }
  5758. Adjacent or
  5759. (
  5760. (
  5761. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5762. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5763. ) and (
  5764. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5765. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5766. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5767. )
  5768. )
  5769. ) then
  5770. begin
  5771. TransferUsedRegs(TmpUsedRegs);
  5772. hp2 := p;
  5773. repeat
  5774. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5775. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5776. IntermediateRegDiscarded :=
  5777. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5778. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5779. { changes
  5780. lea offset1(regX,scale), reg1
  5781. lea offset2(reg1,reg1), reg2
  5782. to
  5783. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5784. and
  5785. lea offset1(regX,scale1), reg1
  5786. lea offset2(reg1,scale2), reg2
  5787. to
  5788. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5789. and
  5790. lea offset1(regX,scale1), reg1
  5791. lea offset2(reg3,reg1,scale2), reg2
  5792. to
  5793. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5794. ... so long as the final scale does not exceed 8
  5795. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5796. }
  5797. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5798. (
  5799. { Don't optimise if size is a concern and the intermediate register remains in use }
  5800. IntermediateRegDiscarded or
  5801. not (cs_opt_size in current_settings.optimizerswitches)
  5802. ) and
  5803. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5804. (
  5805. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5806. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5807. ) and (
  5808. (
  5809. { lea (reg1,scale2), reg2 variant }
  5810. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5811. (
  5812. Adjacent or
  5813. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5814. ) and
  5815. (
  5816. (
  5817. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5818. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5819. ) or (
  5820. { lea (regX,regX), reg1 variant }
  5821. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5822. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5823. )
  5824. )
  5825. ) or (
  5826. { lea (reg1,reg1), reg1 variant }
  5827. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5828. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5829. )
  5830. ) then
  5831. begin
  5832. { Make everything homogeneous to make calculations easier }
  5833. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5834. begin
  5835. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5836. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5837. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5838. else
  5839. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5840. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5841. end;
  5842. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5843. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5844. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5845. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5846. begin
  5847. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5848. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5849. begin
  5850. { Put the register to change in the index register }
  5851. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5852. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5853. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5854. end;
  5855. { Change lea (reg,reg) to lea(,reg,2) }
  5856. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5857. begin
  5858. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5859. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5860. end;
  5861. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5862. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5863. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5864. { Just to prevent miscalculations }
  5865. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5866. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5867. else
  5868. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5869. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5870. if IntermediateRegDiscarded then
  5871. begin
  5872. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5873. RemoveCurrentP(p);
  5874. end
  5875. else
  5876. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5877. result:=true;
  5878. exit;
  5879. end;
  5880. end;
  5881. { changes
  5882. lea offset1(regX), reg1
  5883. lea offset2(reg1), reg2
  5884. to
  5885. lea offset1+offset2(regX), reg2 }
  5886. if (
  5887. { Don't optimise if size is a concern and the intermediate register remains in use }
  5888. IntermediateRegDiscarded or
  5889. not (cs_opt_size in current_settings.optimizerswitches)
  5890. ) and
  5891. (
  5892. (
  5893. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5894. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5895. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5896. ) or (
  5897. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5898. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5899. (
  5900. (
  5901. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5902. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5903. ) or (
  5904. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5905. (
  5906. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5907. (
  5908. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5909. (
  5910. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5911. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5912. )
  5913. )
  5914. )
  5915. )
  5916. )
  5917. )
  5918. ) then
  5919. begin
  5920. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5921. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5922. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5923. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5924. begin
  5925. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5926. begin
  5927. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5928. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5929. { if the register is used as index and base, we have to increase for base as well
  5930. and adapt base }
  5931. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5932. begin
  5933. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5934. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5935. end;
  5936. end
  5937. else
  5938. begin
  5939. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5940. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5941. end;
  5942. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5943. begin
  5944. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5945. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5946. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5947. { Catch the situation where the base = index
  5948. and treat this as *2. The scalefactor of
  5949. p will be 0 or 1 due to the conditional
  5950. checks above. Fixes i40647 }
  5951. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5952. else
  5953. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5954. end;
  5955. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5956. if IntermediateRegDiscarded then
  5957. begin
  5958. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5959. RemoveCurrentP(p);
  5960. end
  5961. else
  5962. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5963. result:=true;
  5964. exit;
  5965. end;
  5966. end;
  5967. end;
  5968. { Change:
  5969. leal/q $x(%reg1),%reg2
  5970. ...
  5971. shll/q $y,%reg2
  5972. To:
  5973. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5974. }
  5975. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5976. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5977. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5978. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5979. (taicpu(hp1).oper[0]^.val <= 3) then
  5980. begin
  5981. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5982. TransferUsedRegs(TmpUsedRegs);
  5983. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5984. if
  5985. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5986. (this works even if scalefactor is zero) }
  5987. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5988. { Ensure offset doesn't go out of bounds }
  5989. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5990. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5991. (
  5992. (
  5993. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5994. (
  5995. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5996. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5997. (
  5998. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5999. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6000. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6001. )
  6002. )
  6003. ) or (
  6004. (
  6005. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6006. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6007. ) and
  6008. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6009. )
  6010. ) then
  6011. begin
  6012. repeat
  6013. with taicpu(p).oper[0]^.ref^ do
  6014. begin
  6015. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6016. if index = base then
  6017. begin
  6018. if Multiple > 4 then
  6019. { Optimisation will no longer work because resultant
  6020. scale factor will exceed 8 }
  6021. Break;
  6022. base := NR_NO;
  6023. scalefactor := 2;
  6024. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6025. end
  6026. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6027. begin
  6028. { Scale factor only works on the index register }
  6029. index := base;
  6030. base := NR_NO;
  6031. end;
  6032. { For safety }
  6033. if scalefactor <= 1 then
  6034. begin
  6035. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6036. scalefactor := Multiple;
  6037. end
  6038. else
  6039. begin
  6040. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6041. scalefactor := scalefactor * Multiple;
  6042. end;
  6043. offset := offset * Multiple;
  6044. end;
  6045. RemoveInstruction(hp1);
  6046. Result := True;
  6047. Exit;
  6048. { This repeat..until loop exists for the benefit of Break }
  6049. until True;
  6050. end;
  6051. end;
  6052. end;
  6053. end;
  6054. end;
  6055. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6056. var
  6057. hp1 : tai;
  6058. SubInstr: Boolean;
  6059. ThisConst: TCGInt;
  6060. const
  6061. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6062. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6063. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6064. begin
  6065. Result := False;
  6066. if taicpu(p).oper[0]^.typ <> top_const then
  6067. { Should have been confirmed before calling }
  6068. InternalError(2021102601);
  6069. SubInstr := (taicpu(p).opcode = A_SUB);
  6070. if GetLastInstruction(p, hp1) and
  6071. (hp1.typ = ait_instruction) and
  6072. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6073. begin
  6074. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6075. { Bad size }
  6076. InternalError(2022042001);
  6077. case taicpu(hp1).opcode Of
  6078. A_INC:
  6079. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6080. begin
  6081. if SubInstr then
  6082. ThisConst := taicpu(p).oper[0]^.val - 1
  6083. else
  6084. ThisConst := taicpu(p).oper[0]^.val + 1;
  6085. end
  6086. else
  6087. Exit;
  6088. A_DEC:
  6089. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6090. begin
  6091. if SubInstr then
  6092. ThisConst := taicpu(p).oper[0]^.val + 1
  6093. else
  6094. ThisConst := taicpu(p).oper[0]^.val - 1;
  6095. end
  6096. else
  6097. Exit;
  6098. A_SUB:
  6099. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6100. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6101. begin
  6102. if SubInstr then
  6103. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6104. else
  6105. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6106. end
  6107. else
  6108. Exit;
  6109. A_ADD:
  6110. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6111. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6112. begin
  6113. if SubInstr then
  6114. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6115. else
  6116. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6117. end
  6118. else
  6119. Exit;
  6120. else
  6121. Exit;
  6122. end;
  6123. { Check that the values are in range }
  6124. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6125. { Overflow; abort }
  6126. Exit;
  6127. if (ThisConst = 0) then
  6128. begin
  6129. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6130. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6131. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6132. RemoveInstruction(hp1);
  6133. hp1 := tai(p.next);
  6134. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6135. if not GetLastInstruction(hp1, p) then
  6136. p := hp1;
  6137. end
  6138. else
  6139. begin
  6140. if taicpu(hp1).opercnt=1 then
  6141. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6142. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6143. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6144. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6145. else
  6146. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6147. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6148. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6149. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6150. RemoveInstruction(hp1);
  6151. taicpu(p).loadconst(0, ThisConst);
  6152. end;
  6153. Result := True;
  6154. end;
  6155. end;
  6156. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6157. begin
  6158. Result := False;
  6159. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6160. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6161. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6162. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6163. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6164. (
  6165. (
  6166. (taicpu(hp1).opcode = A_TEST)
  6167. ) or (
  6168. (taicpu(hp1).opcode = A_CMP) and
  6169. { A sanity check more than anything }
  6170. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6171. )
  6172. ) then
  6173. begin
  6174. { change
  6175. mov mem, %reg
  6176. ...
  6177. cmp/test x, %reg / test %reg,%reg
  6178. (reg deallocated)
  6179. to
  6180. cmp/test x, mem / cmp 0, mem
  6181. }
  6182. TransferUsedRegs(TmpUsedRegs);
  6183. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6184. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6185. begin
  6186. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6187. if (taicpu(hp1).opcode = A_TEST) and
  6188. (
  6189. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6190. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6191. ) then
  6192. begin
  6193. taicpu(hp1).opcode := A_CMP;
  6194. taicpu(hp1).loadconst(0, 0);
  6195. end;
  6196. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6197. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6198. RemoveCurrentP(p);
  6199. if (p <> hp1) then
  6200. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6201. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6202. { Make sure the flags are allocated across the CMP instruction }
  6203. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6204. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6205. Result := True;
  6206. Exit;
  6207. end;
  6208. end;
  6209. end;
  6210. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6211. var
  6212. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6213. ThisReg, SecondReg: TRegister;
  6214. JumpLoc: TAsmLabel;
  6215. NewSize: TOpSize;
  6216. begin
  6217. Result := False;
  6218. {
  6219. Convert:
  6220. j<c> .L1
  6221. .L2:
  6222. mov 1,reg
  6223. jmp .L3 (or ret, although it might not be a RET yet)
  6224. .L1:
  6225. mov 0,reg
  6226. jmp .L3 (or ret)
  6227. ( As long as .L3 <> .L1 or .L2)
  6228. To:
  6229. mov 0,reg
  6230. set<not(c)> reg
  6231. jmp .L3 (or ret)
  6232. .L2:
  6233. mov 1,reg
  6234. jmp .L3 (or ret)
  6235. .L1:
  6236. mov 0,reg
  6237. jmp .L3 (or ret)
  6238. }
  6239. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6240. Exit;
  6241. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6242. if GetNextInstruction(hp_label, hp2) and
  6243. MatchInstruction(hp2,A_MOV,[]) and
  6244. (taicpu(hp2).oper[0]^.typ = top_const) and
  6245. (
  6246. (
  6247. (taicpu(hp2).oper[1]^.typ = top_reg)
  6248. {$ifdef i386}
  6249. { Under i386, ESI, EDI, EBP and ESP
  6250. don't have an 8-bit representation }
  6251. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6252. {$endif i386}
  6253. ) or (
  6254. {$ifdef i386}
  6255. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6256. {$endif i386}
  6257. (taicpu(hp2).opsize = S_B)
  6258. )
  6259. ) and
  6260. GetNextInstruction(hp2, hp3) and
  6261. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6262. (
  6263. (taicpu(hp3).opcode=A_RET) or
  6264. (
  6265. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6266. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6267. )
  6268. ) and
  6269. GetNextInstruction(hp3, hp4) and
  6270. (hp4.typ=ait_label) and
  6271. (tai_label(hp4).labsym=JumpLoc) and
  6272. (
  6273. not (cs_opt_size in current_settings.optimizerswitches) or
  6274. { If the initial jump is the label's only reference, then it will
  6275. become a dead label if the other conditions are met and hence
  6276. remove at least 2 instructions, including a jump }
  6277. (JumpLoc.getrefs = 1)
  6278. ) and
  6279. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6280. that will be optimised out }
  6281. GetNextInstruction(hp4, hp5) and
  6282. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6283. (taicpu(hp5).oper[0]^.typ = top_const) and
  6284. (
  6285. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6286. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6287. ) and
  6288. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6289. GetNextInstruction(hp5,hp6) and
  6290. (
  6291. (hp6.typ<>ait_label) or
  6292. SkipLabels(hp6, hp6)
  6293. ) and
  6294. (hp6.typ=ait_instruction) then
  6295. begin
  6296. { First, let's look at the two jumps that are hp3 and hp6 }
  6297. if not
  6298. (
  6299. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6300. (
  6301. (taicpu(hp6).opcode=A_RET) or
  6302. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6303. )
  6304. ) then
  6305. { If condition is False, then the JMP/RET instructions matched conventionally }
  6306. begin
  6307. { See if one of the jumps can be instantly converted into a RET }
  6308. if (taicpu(hp3).opcode=A_JMP) then
  6309. begin
  6310. { Reuse hp5 }
  6311. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6312. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6313. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6314. Exit;
  6315. if MatchInstruction(hp5, A_RET, []) then
  6316. begin
  6317. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6318. ConvertJumpToRET(hp3, hp5);
  6319. Result := True;
  6320. end
  6321. else
  6322. Exit;
  6323. end;
  6324. if (taicpu(hp6).opcode=A_JMP) then
  6325. begin
  6326. { Reuse hp5 }
  6327. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6328. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6329. Exit;
  6330. if MatchInstruction(hp5, A_RET, []) then
  6331. begin
  6332. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6333. ConvertJumpToRET(hp6, hp5);
  6334. Result := True;
  6335. end
  6336. else
  6337. Exit;
  6338. end;
  6339. if not
  6340. (
  6341. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6342. (
  6343. (taicpu(hp6).opcode=A_RET) or
  6344. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6345. )
  6346. ) then
  6347. { Still doesn't match }
  6348. Exit;
  6349. end;
  6350. if (taicpu(hp2).oper[0]^.val = 1) then
  6351. begin
  6352. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6353. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6354. end
  6355. else
  6356. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6357. if taicpu(hp2).opsize=S_B then
  6358. begin
  6359. if taicpu(hp2).oper[1]^.typ = top_reg then
  6360. begin
  6361. SecondReg := taicpu(hp2).oper[1]^.reg;
  6362. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6363. end
  6364. else
  6365. begin
  6366. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6367. SecondReg := NR_NO;
  6368. end;
  6369. hp_pos := p;
  6370. hp_allocstart := hp4;
  6371. end
  6372. else
  6373. begin
  6374. { Will be a register because the size can't be S_B otherwise }
  6375. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6376. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6377. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6378. if (cs_opt_size in current_settings.optimizerswitches) then
  6379. begin
  6380. { Favour using MOVZX when optimising for size }
  6381. case taicpu(hp2).opsize of
  6382. S_W:
  6383. NewSize := S_BW;
  6384. S_L:
  6385. NewSize := S_BL;
  6386. {$ifdef x86_64}
  6387. S_Q:
  6388. begin
  6389. NewSize := S_BL;
  6390. { Will implicitly zero-extend to 64-bit }
  6391. setsubreg(SecondReg, R_SUBD);
  6392. end;
  6393. {$endif x86_64}
  6394. else
  6395. InternalError(2022101301);
  6396. end;
  6397. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6398. { Inserting it right before p will guarantee that the flags are also tracked }
  6399. Asml.InsertBefore(hp5, p);
  6400. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6401. hp_pos := hp5;
  6402. hp_allocstart := hp4;
  6403. end
  6404. else
  6405. begin
  6406. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6407. { Inserting it right before p will guarantee that the flags are also tracked }
  6408. Asml.InsertBefore(hp5, p);
  6409. hp_pos := p;
  6410. hp_allocstart := hp5;
  6411. end;
  6412. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6413. end;
  6414. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6415. taicpu(hp4).condition := taicpu(p).condition;
  6416. asml.InsertBefore(hp4, hp_pos);
  6417. if taicpu(hp3).is_jmp then
  6418. begin
  6419. JumpLoc.decrefs;
  6420. MakeUnconditional(taicpu(p));
  6421. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6422. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6423. end
  6424. else
  6425. ConvertJumpToRET(p, hp3);
  6426. if SecondReg <> NR_NO then
  6427. { Ensure the destination register is allocated over this region }
  6428. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6429. if (JumpLoc.getrefs = 0) then
  6430. RemoveDeadCodeAfterJump(hp3);
  6431. Result:=true;
  6432. exit;
  6433. end;
  6434. end;
  6435. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6436. var
  6437. hp1, hp2: tai;
  6438. ActiveReg: TRegister;
  6439. OldOffset: asizeint;
  6440. ThisConst: TCGInt;
  6441. function RegDeallocated: Boolean;
  6442. begin
  6443. TransferUsedRegs(TmpUsedRegs);
  6444. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6445. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6446. end;
  6447. begin
  6448. Result:=false;
  6449. hp1 := nil;
  6450. { replace
  6451. subX const,%reg1
  6452. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6453. dealloc %reg1
  6454. by
  6455. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6456. }
  6457. if MatchOpType(taicpu(p),top_const,top_reg) then
  6458. begin
  6459. ActiveReg := taicpu(p).oper[1]^.reg;
  6460. { Ensures the entire register was updated }
  6461. if (taicpu(p).opsize >= S_L) and
  6462. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6463. MatchInstruction(hp1,A_LEA,[]) and
  6464. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6465. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6466. (
  6467. { Cover the case where the register in the reference is also the destination register }
  6468. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6469. (
  6470. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6471. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6472. RegDeallocated
  6473. )
  6474. ) then
  6475. begin
  6476. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6477. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6478. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6479. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6480. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6481. {$ifdef x86_64}
  6482. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6483. begin
  6484. { Overflow; abort }
  6485. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6486. end
  6487. else
  6488. {$endif x86_64}
  6489. begin
  6490. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6491. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6492. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6493. RemoveCurrentP(p, hp1)
  6494. else
  6495. RemoveCurrentP(p);
  6496. result:=true;
  6497. Exit;
  6498. end;
  6499. end;
  6500. if (
  6501. { Save calling GetNextInstructionUsingReg again }
  6502. Assigned(hp1) or
  6503. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6504. ) and
  6505. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6506. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6507. begin
  6508. if taicpu(hp1).oper[0]^.typ = top_const then
  6509. begin
  6510. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6511. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6512. Result := True;
  6513. { Handle any overflows }
  6514. case taicpu(p).opsize of
  6515. S_B:
  6516. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6517. S_W:
  6518. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6519. S_L:
  6520. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6521. {$ifdef x86_64}
  6522. S_Q:
  6523. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6524. { Overflow; abort }
  6525. Result := False
  6526. else
  6527. taicpu(p).oper[0]^.val := ThisConst;
  6528. {$endif x86_64}
  6529. else
  6530. InternalError(2021102611);
  6531. end;
  6532. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6533. if Result then
  6534. begin
  6535. if (taicpu(p).oper[0]^.val < 0) and
  6536. (
  6537. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6538. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6539. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6540. ) then
  6541. begin
  6542. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6543. taicpu(p).opcode := A_SUB;
  6544. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6545. end
  6546. else
  6547. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6548. RemoveInstruction(hp1);
  6549. end;
  6550. end
  6551. else
  6552. begin
  6553. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6554. TransferUsedRegs(TmpUsedRegs);
  6555. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6556. hp2 := p;
  6557. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6558. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6559. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6560. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6561. begin
  6562. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6563. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6564. Asml.Remove(p);
  6565. Asml.InsertAfter(p, hp1);
  6566. p := hp1;
  6567. Result := True;
  6568. Exit;
  6569. end;
  6570. end;
  6571. end;
  6572. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6573. { * change "sub/add const1, reg" or "dec reg" followed by
  6574. "sub const2, reg" to one "sub ..., reg" }
  6575. {$ifdef i386}
  6576. if (taicpu(p).oper[0]^.val = 2) and
  6577. (ActiveReg = NR_ESP) and
  6578. { Don't do the sub/push optimization if the sub }
  6579. { comes from setting up the stack frame (JM) }
  6580. (not(GetLastInstruction(p,hp1)) or
  6581. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6582. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6583. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6584. begin
  6585. hp1 := tai(p.next);
  6586. while Assigned(hp1) and
  6587. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6588. not RegReadByInstruction(NR_ESP,hp1) and
  6589. not RegModifiedByInstruction(NR_ESP,hp1) do
  6590. hp1 := tai(hp1.next);
  6591. if Assigned(hp1) and
  6592. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6593. begin
  6594. taicpu(hp1).changeopsize(S_L);
  6595. if taicpu(hp1).oper[0]^.typ=top_reg then
  6596. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6597. hp1 := tai(p.next);
  6598. RemoveCurrentp(p, hp1);
  6599. Result:=true;
  6600. exit;
  6601. end;
  6602. end;
  6603. {$endif i386}
  6604. if DoArithCombineOpt(p) then
  6605. Result:=true;
  6606. end;
  6607. end;
  6608. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6609. var
  6610. TmpBool1,TmpBool2 : Boolean;
  6611. tmpref : treference;
  6612. hp1,hp2: tai;
  6613. mask, shiftval: tcgint;
  6614. begin
  6615. Result:=false;
  6616. { All these optimisations work on "shl/sal const,%reg" }
  6617. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6618. Exit;
  6619. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6620. (taicpu(p).oper[0]^.val <= 3) then
  6621. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6622. begin
  6623. { should we check the next instruction? }
  6624. TmpBool1 := True;
  6625. { have we found an add/sub which could be
  6626. integrated in the lea? }
  6627. TmpBool2 := False;
  6628. reference_reset(tmpref,2,[]);
  6629. TmpRef.index := taicpu(p).oper[1]^.reg;
  6630. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6631. while TmpBool1 and
  6632. GetNextInstruction(p, hp1) and
  6633. (tai(hp1).typ = ait_instruction) and
  6634. ((((taicpu(hp1).opcode = A_ADD) or
  6635. (taicpu(hp1).opcode = A_SUB)) and
  6636. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6637. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6638. (((taicpu(hp1).opcode = A_INC) or
  6639. (taicpu(hp1).opcode = A_DEC)) and
  6640. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6641. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6642. ((taicpu(hp1).opcode = A_LEA) and
  6643. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6644. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6645. (not GetNextInstruction(hp1,hp2) or
  6646. not instrReadsFlags(hp2)) Do
  6647. begin
  6648. TmpBool1 := False;
  6649. if taicpu(hp1).opcode=A_LEA then
  6650. begin
  6651. if (TmpRef.base = NR_NO) and
  6652. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6653. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6654. { Segment register isn't a concern here }
  6655. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6656. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6657. begin
  6658. TmpBool1 := True;
  6659. TmpBool2 := True;
  6660. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6661. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6662. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6663. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6664. RemoveInstruction(hp1);
  6665. end
  6666. end
  6667. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6668. begin
  6669. TmpBool1 := True;
  6670. TmpBool2 := True;
  6671. case taicpu(hp1).opcode of
  6672. A_ADD:
  6673. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6674. A_SUB:
  6675. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6676. else
  6677. internalerror(2019050536);
  6678. end;
  6679. RemoveInstruction(hp1);
  6680. end
  6681. else
  6682. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6683. (((taicpu(hp1).opcode = A_ADD) and
  6684. (TmpRef.base = NR_NO)) or
  6685. (taicpu(hp1).opcode = A_INC) or
  6686. (taicpu(hp1).opcode = A_DEC)) then
  6687. begin
  6688. TmpBool1 := True;
  6689. TmpBool2 := True;
  6690. case taicpu(hp1).opcode of
  6691. A_ADD:
  6692. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6693. A_INC:
  6694. inc(TmpRef.offset);
  6695. A_DEC:
  6696. dec(TmpRef.offset);
  6697. else
  6698. internalerror(2019050535);
  6699. end;
  6700. RemoveInstruction(hp1);
  6701. end;
  6702. end;
  6703. if TmpBool2
  6704. {$ifndef x86_64}
  6705. or
  6706. ((current_settings.optimizecputype < cpu_Pentium2) and
  6707. (taicpu(p).oper[0]^.val <= 3) and
  6708. not(cs_opt_size in current_settings.optimizerswitches))
  6709. {$endif x86_64}
  6710. then
  6711. begin
  6712. if not(TmpBool2) and
  6713. (taicpu(p).oper[0]^.val=1) then
  6714. begin
  6715. taicpu(p).opcode := A_ADD;
  6716. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6717. end
  6718. else
  6719. begin
  6720. taicpu(p).opcode := A_LEA;
  6721. taicpu(p).loadref(0, TmpRef);
  6722. end;
  6723. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6724. Result := True;
  6725. end;
  6726. end
  6727. {$ifndef x86_64}
  6728. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6729. begin
  6730. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6731. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6732. (unlike shl, which is only Tairable in the U pipe) }
  6733. if taicpu(p).oper[0]^.val=1 then
  6734. begin
  6735. taicpu(p).opcode := A_ADD;
  6736. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6737. Result := True;
  6738. end
  6739. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6740. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6741. else if (taicpu(p).opsize = S_L) and
  6742. (taicpu(p).oper[0]^.val<= 3) then
  6743. begin
  6744. reference_reset(tmpref,2,[]);
  6745. TmpRef.index := taicpu(p).oper[1]^.reg;
  6746. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6747. taicpu(p).opcode := A_LEA;
  6748. taicpu(p).loadref(0, TmpRef);
  6749. Result := True;
  6750. end;
  6751. end
  6752. {$endif x86_64}
  6753. else if
  6754. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6755. (
  6756. (
  6757. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6758. SetAndTest(hp1, hp2)
  6759. {$ifdef x86_64}
  6760. ) or
  6761. (
  6762. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6763. GetNextInstruction(hp1, hp2) and
  6764. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6765. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6766. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6767. {$endif x86_64}
  6768. )
  6769. ) and
  6770. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6771. begin
  6772. { Change:
  6773. shl x, %reg1
  6774. mov -(1<<x), %reg2
  6775. and %reg2, %reg1
  6776. Or:
  6777. shl x, %reg1
  6778. and -(1<<x), %reg1
  6779. To just:
  6780. shl x, %reg1
  6781. Since the and operation only zeroes bits that are already zero from the shl operation
  6782. }
  6783. case taicpu(p).oper[0]^.val of
  6784. 8:
  6785. mask:=$FFFFFFFFFFFFFF00;
  6786. 16:
  6787. mask:=$FFFFFFFFFFFF0000;
  6788. 32:
  6789. mask:=$FFFFFFFF00000000;
  6790. 63:
  6791. { Constant pre-calculated to prevent overflow errors with Int64 }
  6792. mask:=$8000000000000000;
  6793. else
  6794. begin
  6795. if taicpu(p).oper[0]^.val >= 64 then
  6796. { Shouldn't happen realistically, since the register
  6797. is guaranteed to be set to zero at this point }
  6798. mask := 0
  6799. else
  6800. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6801. end;
  6802. end;
  6803. if taicpu(hp1).oper[0]^.val = mask then
  6804. begin
  6805. { Everything checks out, perform the optimisation, as long as
  6806. the FLAGS register isn't being used}
  6807. TransferUsedRegs(TmpUsedRegs);
  6808. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6809. {$ifdef x86_64}
  6810. if (hp1 <> hp2) then
  6811. begin
  6812. { "shl/mov/and" version }
  6813. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6814. { Don't do the optimisation if the FLAGS register is in use }
  6815. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6816. begin
  6817. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6818. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6819. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6820. begin
  6821. RemoveInstruction(hp1);
  6822. Result := True;
  6823. end;
  6824. { Only set Result to True if the 'mov' instruction was removed }
  6825. RemoveInstruction(hp2);
  6826. end;
  6827. end
  6828. else
  6829. {$endif x86_64}
  6830. begin
  6831. { "shl/and" version }
  6832. { Don't do the optimisation if the FLAGS register is in use }
  6833. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6834. begin
  6835. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6836. RemoveInstruction(hp1);
  6837. Result := True;
  6838. end;
  6839. end;
  6840. Exit;
  6841. end
  6842. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6843. begin
  6844. { Even if the mask doesn't allow for its removal, we might be
  6845. able to optimise the mask for the "shl/and" version, which
  6846. may permit other peephole optimisations }
  6847. {$ifdef DEBUG_AOPTCPU}
  6848. mask := taicpu(hp1).oper[0]^.val and mask;
  6849. if taicpu(hp1).oper[0]^.val <> mask then
  6850. begin
  6851. DebugMsg(
  6852. SPeepholeOptimization +
  6853. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6854. ' to $' + debug_tostr(mask) +
  6855. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6856. taicpu(hp1).oper[0]^.val := mask;
  6857. end;
  6858. {$else DEBUG_AOPTCPU}
  6859. { If debugging is off, just set the operand even if it's the same }
  6860. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6861. {$endif DEBUG_AOPTCPU}
  6862. end;
  6863. end;
  6864. {
  6865. change
  6866. shl/sal const,reg
  6867. <op> ...(...,reg,1),...
  6868. into
  6869. <op> ...(...,reg,1 shl const),...
  6870. if const in 1..3
  6871. }
  6872. if MatchOpType(taicpu(p), top_const, top_reg) and
  6873. (taicpu(p).oper[0]^.val in [1..3]) and
  6874. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6875. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6876. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6877. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6878. MatchOpType(taicpu(hp1),top_ref))
  6879. ) and
  6880. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6881. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6882. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6883. begin
  6884. TransferUsedRegs(TmpUsedRegs);
  6885. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6886. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6887. begin
  6888. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6889. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6890. RemoveCurrentP(p);
  6891. Result:=true;
  6892. exit;
  6893. end;
  6894. end;
  6895. if MatchOpType(taicpu(p), top_const, top_reg) and
  6896. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6897. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6898. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6899. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6900. begin
  6901. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6902. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6903. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6904. {$ifdef x86_64}
  6905. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6906. {$endif x86_64}
  6907. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6908. begin
  6909. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6910. taicpu(hp1).opcode:=A_MOV;
  6911. taicpu(hp1).oper[0]^.val:=0;
  6912. end
  6913. else
  6914. begin
  6915. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6916. taicpu(hp1).oper[0]^.val:=shiftval;
  6917. end;
  6918. RemoveCurrentP(p);
  6919. Result:=true;
  6920. exit;
  6921. end;
  6922. end;
  6923. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6924. begin
  6925. case shr_size of
  6926. S_B:
  6927. { No valid combinations }
  6928. Result := False;
  6929. S_W:
  6930. Result := (Shift >= 8) and (movz_size = S_BW);
  6931. S_L:
  6932. Result :=
  6933. (Shift >= 24) { Any opsize is valid for this shift } or
  6934. ((Shift >= 16) and (movz_size = S_WL));
  6935. {$ifdef x86_64}
  6936. S_Q:
  6937. Result :=
  6938. (Shift >= 56) { Any opsize is valid for this shift } or
  6939. ((Shift >= 48) and (movz_size = S_WL));
  6940. {$endif x86_64}
  6941. else
  6942. InternalError(2022081510);
  6943. end;
  6944. end;
  6945. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6946. var
  6947. hp1, hp2: tai;
  6948. Shift: TCGInt;
  6949. LimitSize: Topsize;
  6950. DoNotMerge: Boolean;
  6951. begin
  6952. Result := False;
  6953. { All these optimisations work on "shr const,%reg" }
  6954. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6955. Exit;
  6956. DoNotMerge := False;
  6957. Shift := taicpu(p).oper[0]^.val;
  6958. LimitSize := taicpu(p).opsize;
  6959. hp1 := p;
  6960. repeat
  6961. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6962. Exit;
  6963. case taicpu(hp1).opcode of
  6964. A_TEST, A_CMP, A_Jcc:
  6965. { Skip over conditional jumps and relevant comparisons }
  6966. Continue;
  6967. A_MOVZX:
  6968. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6969. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6970. begin
  6971. { Since the original register is being read as is, subsequent
  6972. SHRs must not be merged at this point }
  6973. DoNotMerge := True;
  6974. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6975. begin
  6976. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6977. begin
  6978. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6979. taicpu(hp1).opcode := A_MOV;
  6980. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6981. case taicpu(hp1).opsize of
  6982. S_BW:
  6983. taicpu(hp1).opsize := S_W;
  6984. S_BL, S_WL:
  6985. taicpu(hp1).opsize := S_L;
  6986. else
  6987. InternalError(2022081503);
  6988. end;
  6989. { p itself hasn't changed, so no need to set Result to True }
  6990. Include(OptsToCheck, aoc_ForceNewIteration);
  6991. { See if there's anything afterwards that can be
  6992. optimised, since the input register hasn't changed }
  6993. Continue;
  6994. end;
  6995. { NOTE: If the MOVZX instruction reads and writes the same
  6996. register, defer this to the post-peephole optimisation stage }
  6997. Exit;
  6998. end;
  6999. end;
  7000. A_SHL, A_SAL, A_SHR:
  7001. if (taicpu(hp1).opsize <= LimitSize) and
  7002. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7003. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7004. begin
  7005. { Make sure the sizes don't exceed the register size limit
  7006. (measured by the shift value falling below the limit) }
  7007. if taicpu(hp1).opsize < LimitSize then
  7008. LimitSize := taicpu(hp1).opsize;
  7009. if taicpu(hp1).opcode = A_SHR then
  7010. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7011. else
  7012. begin
  7013. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7014. DoNotMerge := True;
  7015. end;
  7016. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7017. Exit;
  7018. { Since we've established that the combined shift is within
  7019. limits, we can actually combine the adjacent SHR
  7020. instructions even if they're different sizes }
  7021. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7022. begin
  7023. hp2 := tai(hp1.Previous);
  7024. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7025. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7026. RemoveInstruction(hp1);
  7027. hp1 := hp2;
  7028. { Though p has changed, only the constant has, and its
  7029. effects can still be detected on the next iteration of
  7030. the repeat..until loop }
  7031. Include(OptsToCheck, aoc_ForceNewIteration);
  7032. end;
  7033. { Move onto the next instruction }
  7034. Continue;
  7035. end;
  7036. else
  7037. ;
  7038. end;
  7039. Break;
  7040. until False;
  7041. end;
  7042. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7043. var
  7044. CurrentRef: TReference;
  7045. FullReg: TRegister;
  7046. hp1, hp2: tai;
  7047. begin
  7048. Result := False;
  7049. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7050. Exit;
  7051. { We assume you've checked if the operand is actually a reference by
  7052. this point. If it isn't, you'll most likely get an access violation }
  7053. CurrentRef := first_mov.oper[1]^.ref^;
  7054. { Memory must be aligned }
  7055. if (CurrentRef.offset mod 4) <> 0 then
  7056. Exit;
  7057. Inc(CurrentRef.offset);
  7058. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7059. if MatchOperand(second_mov.oper[0]^, 0) and
  7060. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7061. GetNextInstruction(second_mov, hp1) and
  7062. (hp1.typ = ait_instruction) and
  7063. (taicpu(hp1).opcode = A_MOV) and
  7064. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7065. (taicpu(hp1).oper[0]^.val = 0) then
  7066. begin
  7067. Inc(CurrentRef.offset);
  7068. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7069. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7070. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7071. begin
  7072. case taicpu(hp1).opsize of
  7073. S_B:
  7074. if GetNextInstruction(hp1, hp2) and
  7075. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7076. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7077. (taicpu(hp2).oper[0]^.val = 0) then
  7078. begin
  7079. Inc(CurrentRef.offset);
  7080. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7081. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7082. (taicpu(hp2).opsize = S_B) then
  7083. begin
  7084. RemoveInstruction(hp1);
  7085. RemoveInstruction(hp2);
  7086. first_mov.opsize := S_L;
  7087. if first_mov.oper[0]^.typ = top_reg then
  7088. begin
  7089. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7090. { Reuse second_mov as a MOVZX instruction }
  7091. second_mov.opcode := A_MOVZX;
  7092. second_mov.opsize := S_BL;
  7093. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7094. second_mov.loadreg(1, FullReg);
  7095. first_mov.oper[0]^.reg := FullReg;
  7096. asml.Remove(second_mov);
  7097. asml.InsertBefore(second_mov, first_mov);
  7098. end
  7099. else
  7100. { It's a value }
  7101. begin
  7102. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7103. RemoveInstruction(second_mov);
  7104. end;
  7105. Result := True;
  7106. Exit;
  7107. end;
  7108. end;
  7109. S_W:
  7110. begin
  7111. RemoveInstruction(hp1);
  7112. first_mov.opsize := S_L;
  7113. if first_mov.oper[0]^.typ = top_reg then
  7114. begin
  7115. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7116. { Reuse second_mov as a MOVZX instruction }
  7117. second_mov.opcode := A_MOVZX;
  7118. second_mov.opsize := S_BL;
  7119. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7120. second_mov.loadreg(1, FullReg);
  7121. first_mov.oper[0]^.reg := FullReg;
  7122. asml.Remove(second_mov);
  7123. asml.InsertBefore(second_mov, first_mov);
  7124. end
  7125. else
  7126. { It's a value }
  7127. begin
  7128. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7129. RemoveInstruction(second_mov);
  7130. end;
  7131. Result := True;
  7132. Exit;
  7133. end;
  7134. else
  7135. ;
  7136. end;
  7137. end;
  7138. end;
  7139. end;
  7140. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7141. { returns true if a "continue" should be done after this optimization }
  7142. var
  7143. hp1, hp2, hp3: tai;
  7144. begin
  7145. Result := false;
  7146. hp3 := nil;
  7147. if MatchOpType(taicpu(p),top_ref) and
  7148. GetNextInstruction(p, hp1) and
  7149. (hp1.typ = ait_instruction) and
  7150. (((taicpu(hp1).opcode = A_FLD) and
  7151. (taicpu(p).opcode = A_FSTP)) or
  7152. ((taicpu(p).opcode = A_FISTP) and
  7153. (taicpu(hp1).opcode = A_FILD))) and
  7154. MatchOpType(taicpu(hp1),top_ref) and
  7155. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7156. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7157. begin
  7158. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7159. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7160. GetNextInstruction(hp1, hp2) and
  7161. (((hp2.typ = ait_instruction) and
  7162. IsExitCode(hp2) and
  7163. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7164. not(assigned(current_procinfo.procdef.funcretsym) and
  7165. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7166. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7167. { fstp <temp>
  7168. fld <temp>
  7169. <dealloc> <temp>
  7170. }
  7171. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7172. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7173. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7174. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7175. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7176. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7177. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7178. )
  7179. )
  7180. ) then
  7181. begin
  7182. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7183. RemoveInstruction(hp1);
  7184. RemoveCurrentP(p, hp2);
  7185. { first case: exit code }
  7186. if hp2.typ = ait_instruction then
  7187. RemoveLastDeallocForFuncRes(p);
  7188. Result := true;
  7189. end
  7190. else
  7191. { we can do this only in fast math mode as fstp is rounding ...
  7192. ... still disabled as it breaks the compiler and/or rtl }
  7193. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7194. { ... or if another fstp equal to the first one follows }
  7195. GetNextInstruction(hp1,hp2) and
  7196. (hp2.typ = ait_instruction) and
  7197. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7198. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7199. begin
  7200. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7201. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7202. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7203. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7204. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7205. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7206. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7207. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7208. ) then
  7209. begin
  7210. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7211. RemoveCurrentP(p,hp2);
  7212. RemoveInstruction(hp1);
  7213. Result := true;
  7214. end
  7215. else if { fst can't store an extended/comp value }
  7216. (taicpu(p).opsize <> S_FX) and
  7217. (taicpu(p).opsize <> S_IQ) then
  7218. begin
  7219. if (taicpu(p).opcode = A_FSTP) then
  7220. taicpu(p).opcode := A_FST
  7221. else
  7222. taicpu(p).opcode := A_FIST;
  7223. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7224. RemoveInstruction(hp1);
  7225. Result := true;
  7226. end;
  7227. end;
  7228. end;
  7229. end;
  7230. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7231. var
  7232. hp1, hp2, hp3: tai;
  7233. begin
  7234. result:=false;
  7235. if MatchOpType(taicpu(p),top_reg) and
  7236. GetNextInstruction(p, hp1) and
  7237. (hp1.typ = Ait_Instruction) and
  7238. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7239. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7240. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7241. { change to
  7242. fld reg fxxx reg,st
  7243. fxxxp st, st1 (hp1)
  7244. Remark: non commutative operations must be reversed!
  7245. }
  7246. begin
  7247. case taicpu(hp1).opcode Of
  7248. A_FMULP,A_FADDP,
  7249. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7250. begin
  7251. case taicpu(hp1).opcode Of
  7252. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7253. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7254. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7255. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7256. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7257. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7258. else
  7259. internalerror(2019050534);
  7260. end;
  7261. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7262. taicpu(hp1).oper[1]^.reg := NR_ST;
  7263. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7264. RemoveCurrentP(p, hp1);
  7265. Result:=true;
  7266. exit;
  7267. end;
  7268. else
  7269. ;
  7270. end;
  7271. end
  7272. else
  7273. if MatchOpType(taicpu(p),top_ref) and
  7274. GetNextInstruction(p, hp2) and
  7275. (hp2.typ = Ait_Instruction) and
  7276. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7277. (taicpu(p).opsize in [S_FS, S_FL]) and
  7278. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7279. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7280. if GetLastInstruction(p, hp1) and
  7281. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7282. MatchOpType(taicpu(hp1),top_ref) and
  7283. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7284. if ((taicpu(hp2).opcode = A_FMULP) or
  7285. (taicpu(hp2).opcode = A_FADDP)) then
  7286. { change to
  7287. fld/fst mem1 (hp1) fld/fst mem1
  7288. fld mem1 (p) fadd/
  7289. faddp/ fmul st, st
  7290. fmulp st, st1 (hp2) }
  7291. begin
  7292. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7293. RemoveCurrentP(p, hp1);
  7294. if (taicpu(hp2).opcode = A_FADDP) then
  7295. taicpu(hp2).opcode := A_FADD
  7296. else
  7297. taicpu(hp2).opcode := A_FMUL;
  7298. taicpu(hp2).oper[1]^.reg := NR_ST;
  7299. end
  7300. else
  7301. { change to
  7302. fld/fst mem1 (hp1) fld/fst mem1
  7303. fld mem1 (p) fld st
  7304. }
  7305. begin
  7306. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7307. taicpu(p).changeopsize(S_FL);
  7308. taicpu(p).loadreg(0,NR_ST);
  7309. end
  7310. else
  7311. begin
  7312. case taicpu(hp2).opcode Of
  7313. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7314. { change to
  7315. fld/fst mem1 (hp1) fld/fst mem1
  7316. fld mem2 (p) fxxx mem2
  7317. fxxxp st, st1 (hp2) }
  7318. begin
  7319. case taicpu(hp2).opcode Of
  7320. A_FADDP: taicpu(p).opcode := A_FADD;
  7321. A_FMULP: taicpu(p).opcode := A_FMUL;
  7322. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7323. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7324. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7325. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7326. else
  7327. internalerror(2019050533);
  7328. end;
  7329. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7330. RemoveInstruction(hp2);
  7331. end
  7332. else
  7333. ;
  7334. end
  7335. end
  7336. end;
  7337. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7338. begin
  7339. Result := condition_in(cond1, cond2) or
  7340. { Not strictly subsets due to the actual flags checked, but because we're
  7341. comparing integers, E is a subset of AE and GE and their aliases }
  7342. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7343. end;
  7344. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7345. var
  7346. v: TCGInt;
  7347. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7348. FirstMatch, TempBool: Boolean;
  7349. NewReg: TRegister;
  7350. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7351. begin
  7352. Result:=false;
  7353. { All these optimisations need a next instruction }
  7354. if not GetNextInstruction(p, hp1) then
  7355. Exit;
  7356. true_hp1 := hp1;
  7357. { Search for:
  7358. cmp ###,###
  7359. j(c1) @lbl1
  7360. ...
  7361. @lbl:
  7362. cmp ###,### (same comparison as above)
  7363. j(c2) @lbl2
  7364. If c1 is a subset of c2, change to:
  7365. cmp ###,###
  7366. j(c1) @lbl2
  7367. (@lbl1 may become a dead label as a result)
  7368. }
  7369. { Also handle cases where there are multiple jumps in a row }
  7370. p_jump := hp1;
  7371. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7372. begin
  7373. Prefetch(p_jump.Next);
  7374. if IsJumpToLabel(taicpu(p_jump)) then
  7375. begin
  7376. { Do jump optimisations first in case the condition becomes
  7377. unnecessary }
  7378. TempBool := True;
  7379. if DoJumpOptimizations(p_jump, TempBool) or
  7380. not TempBool then
  7381. begin
  7382. if Assigned(p_jump) then
  7383. begin
  7384. { CollapseZeroDistJump will be set to the label or an align
  7385. before it after the jump if it optimises, whether or not
  7386. the label is live or dead }
  7387. if (p_jump.typ = ait_align) or
  7388. (
  7389. (p_jump.typ = ait_label) and
  7390. not (tai_label(p_jump).labsym.is_used)
  7391. ) then
  7392. GetNextInstruction(p_jump, p_jump);
  7393. end;
  7394. TransferUsedRegs(TmpUsedRegs);
  7395. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7396. if not Assigned(p_jump) or
  7397. (
  7398. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7399. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7400. ) then
  7401. begin
  7402. { No more conditional jumps; conditional statement is no longer required }
  7403. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7404. RemoveCurrentP(p);
  7405. Result := True;
  7406. Exit;
  7407. end;
  7408. hp1 := p_jump;
  7409. Include(OptsToCheck, aoc_ForceNewIteration);
  7410. Continue;
  7411. end;
  7412. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7413. if GetNextInstruction(p_jump, hp2) and
  7414. (
  7415. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7416. not TempBool
  7417. ) then
  7418. begin
  7419. hp1 := p_jump;
  7420. Include(OptsToCheck, aoc_ForceNewIteration);
  7421. Continue;
  7422. end;
  7423. p_label := nil;
  7424. if Assigned(JumpLabel) then
  7425. p_label := getlabelwithsym(JumpLabel);
  7426. if Assigned(p_label) and
  7427. GetNextInstruction(p_label, p_dist) and
  7428. MatchInstruction(p_dist, A_CMP, []) and
  7429. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7430. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7431. GetNextInstruction(p_dist, hp1_dist) and
  7432. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7433. begin
  7434. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7435. if JumpLabel = JumpLabel_dist then
  7436. { This is an infinite loop }
  7437. Exit;
  7438. { Best optimisation when the first condition is a subset (or equal) of the second }
  7439. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7440. begin
  7441. { Any registers used here will already be allocated }
  7442. if Assigned(JumpLabel) then
  7443. JumpLabel.DecRefs;
  7444. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7445. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7446. Include(OptsToCheck, aoc_ForceNewIteration);
  7447. { Don't exit yet. Since p and p_jump haven't actually been
  7448. removed, we can check for more on this iteration }
  7449. end
  7450. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7451. GetNextInstruction(hp1_dist, hp1_label) and
  7452. (hp1_label.typ = ait_label) then
  7453. begin
  7454. JumpLabel_far := tai_label(hp1_label).labsym;
  7455. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7456. { This is an infinite loop }
  7457. Exit;
  7458. if Assigned(JumpLabel_far) then
  7459. begin
  7460. { In this situation, if the first jump branches, the second one will never,
  7461. branch so change the destination label to after the second jump }
  7462. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7463. if Assigned(JumpLabel) then
  7464. JumpLabel.DecRefs;
  7465. JumpLabel_far.IncRefs;
  7466. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7467. Result := True;
  7468. { Don't exit yet. Since p and p_jump haven't actually been
  7469. removed, we can check for more on this iteration }
  7470. Continue;
  7471. end;
  7472. end;
  7473. end;
  7474. end;
  7475. { Search for:
  7476. cmp ###,###
  7477. j(c1) @lbl1
  7478. cmp ###,### (same as first)
  7479. Remove second cmp
  7480. }
  7481. if GetNextInstruction(p_jump, hp2) and
  7482. (
  7483. (
  7484. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7485. (
  7486. (
  7487. MatchOpType(taicpu(p), top_const, top_reg) and
  7488. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7489. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7490. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7491. ) or (
  7492. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7493. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7494. )
  7495. )
  7496. ) or (
  7497. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7498. MatchOperand(taicpu(p).oper[0]^, 0) and
  7499. (taicpu(p).oper[1]^.typ = top_reg) and
  7500. MatchInstruction(hp2, A_TEST, []) and
  7501. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7502. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7503. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7504. )
  7505. ) then
  7506. begin
  7507. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7508. TransferUsedRegs(TmpUsedRegs);
  7509. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7510. RemoveInstruction(hp2);
  7511. Result := True;
  7512. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7513. end
  7514. else
  7515. begin
  7516. { hp2 is the next instruction, so save time and just set p_jump
  7517. to it instead of calling GetNextInstruction below }
  7518. p_jump := hp2;
  7519. Continue;
  7520. end;
  7521. GetNextInstruction(p_jump, p_jump);
  7522. end;
  7523. if (
  7524. { Don't call GetNextInstruction again if we already have it }
  7525. (true_hp1 = p_jump) or
  7526. GetNextInstruction(p, hp1)
  7527. ) and
  7528. MatchInstruction(hp1, A_Jcc, []) and
  7529. IsJumpToLabel(taicpu(hp1)) and
  7530. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7531. GetNextInstruction(hp1, hp2) then
  7532. begin
  7533. {
  7534. cmp x, y (or "cmp y, x")
  7535. je @lbl
  7536. mov x, y
  7537. @lbl:
  7538. (x and y can be constants, registers or references)
  7539. Change to:
  7540. mov x, y (x and y will always be equal in the end)
  7541. @lbl: (may beceome a dead label)
  7542. Also:
  7543. cmp x, y (or "cmp y, x")
  7544. jne @lbl
  7545. mov x, y
  7546. @lbl:
  7547. (x and y can be constants, registers or references)
  7548. Change to:
  7549. Absolutely nothing! (Except @lbl if it's still live)
  7550. }
  7551. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7552. (
  7553. (
  7554. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7555. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7556. ) or (
  7557. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7558. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7559. )
  7560. ) and
  7561. GetNextInstruction(hp2, hp1_label) and
  7562. (hp1_label.typ = ait_label) and
  7563. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7564. begin
  7565. tai_label(hp1_label).labsym.DecRefs;
  7566. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7567. begin
  7568. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7569. RemoveInstruction(hp2);
  7570. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7571. end
  7572. else
  7573. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7574. RemoveInstruction(hp1);
  7575. RemoveCurrentp(p, hp2);
  7576. Result := True;
  7577. Exit;
  7578. end;
  7579. {
  7580. Try to optimise the following:
  7581. cmp $x,### ($x and $y can be registers or constants)
  7582. je @lbl1 (only reference)
  7583. cmp $y,### (### are identical)
  7584. @Lbl:
  7585. sete %reg1
  7586. Change to:
  7587. cmp $x,###
  7588. sete %reg2 (allocate new %reg2)
  7589. cmp $y,###
  7590. sete %reg1
  7591. orb %reg2,%reg1
  7592. (dealloc %reg2)
  7593. This adds an instruction (so don't perform under -Os), but it removes
  7594. a conditional branch.
  7595. }
  7596. if not (cs_opt_size in current_settings.optimizerswitches) and
  7597. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7598. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7599. { The first operand of CMP instructions can only be a register or
  7600. immediate anyway, so no need to check }
  7601. GetNextInstruction(hp2, p_label) and
  7602. (p_label.typ = ait_label) and
  7603. (tai_label(p_label).labsym.getrefs = 1) and
  7604. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7605. GetNextInstruction(p_label, p_dist) and
  7606. MatchInstruction(p_dist, A_SETcc, []) and
  7607. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7608. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7609. begin
  7610. TransferUsedRegs(TmpUsedRegs);
  7611. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7612. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7613. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7614. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7615. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7616. { Get the instruction after the SETcc instruction so we can
  7617. allocate a new register over the entire range }
  7618. GetNextInstruction(p_dist, hp1_dist) then
  7619. begin
  7620. { Register can appear in p if it's not used afterwards, so only
  7621. allocate between hp1 and hp1_dist }
  7622. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7623. if NewReg <> NR_NO then
  7624. begin
  7625. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7626. { Change the jump instruction into a SETcc instruction }
  7627. taicpu(hp1).opcode := A_SETcc;
  7628. taicpu(hp1).opsize := S_B;
  7629. taicpu(hp1).loadreg(0, NewReg);
  7630. { This is now a dead label }
  7631. tai_label(p_label).labsym.decrefs;
  7632. { Prefer adding before the next instruction so the FLAGS
  7633. register is deallicated first }
  7634. AsmL.InsertBefore(
  7635. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7636. hp1_dist
  7637. );
  7638. Result := True;
  7639. { Don't exit yet, as p wasn't changed and hp1, while
  7640. modified, is still intact and might be optimised by the
  7641. SETcc optimisation below }
  7642. end;
  7643. end;
  7644. end;
  7645. end;
  7646. if (taicpu(p).oper[0]^.typ = top_const) and
  7647. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7648. begin
  7649. if (taicpu(p).oper[0]^.val = 0) and
  7650. (taicpu(p).oper[1]^.typ = top_reg) then
  7651. begin
  7652. hp2 := p;
  7653. FirstMatch := True;
  7654. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7655. anything meaningful once it's converted to "test %reg,%reg";
  7656. additionally, some jumps will always (or never) branch, so
  7657. evaluate every jump immediately following the
  7658. comparison, optimising the conditions if possible.
  7659. Similarly with SETcc... those that are always set to 0 or 1
  7660. are changed to MOV instructions }
  7661. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7662. (
  7663. GetNextInstruction(hp2, hp1) and
  7664. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7665. ) do
  7666. begin
  7667. Prefetch(hp1.Next);
  7668. FirstMatch := False;
  7669. case taicpu(hp1).condition of
  7670. C_B, C_C, C_NAE, C_O:
  7671. { For B/NAE:
  7672. Will never branch since an unsigned integer can never be below zero
  7673. For C/O:
  7674. Result cannot overflow because 0 is being subtracted
  7675. }
  7676. begin
  7677. if taicpu(hp1).opcode = A_Jcc then
  7678. begin
  7679. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7680. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7681. RemoveInstruction(hp1);
  7682. { Since hp1 was deleted, hp2 must not be updated }
  7683. Continue;
  7684. end
  7685. else
  7686. begin
  7687. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7688. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7689. taicpu(hp1).opcode := A_MOV;
  7690. taicpu(hp1).ops := 2;
  7691. taicpu(hp1).condition := C_None;
  7692. taicpu(hp1).opsize := S_B;
  7693. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7694. taicpu(hp1).loadconst(0, 0);
  7695. end;
  7696. end;
  7697. C_BE, C_NA:
  7698. begin
  7699. { Will only branch if equal to zero }
  7700. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7701. taicpu(hp1).condition := C_E;
  7702. end;
  7703. C_A, C_NBE:
  7704. begin
  7705. { Will only branch if not equal to zero }
  7706. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7707. taicpu(hp1).condition := C_NE;
  7708. end;
  7709. C_AE, C_NB, C_NC, C_NO:
  7710. begin
  7711. { Will always branch }
  7712. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7713. if taicpu(hp1).opcode = A_Jcc then
  7714. begin
  7715. MakeUnconditional(taicpu(hp1));
  7716. { Any jumps/set that follow will now be dead code }
  7717. RemoveDeadCodeAfterJump(taicpu(hp1));
  7718. Break;
  7719. end
  7720. else
  7721. begin
  7722. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7723. taicpu(hp1).opcode := A_MOV;
  7724. taicpu(hp1).ops := 2;
  7725. taicpu(hp1).condition := C_None;
  7726. taicpu(hp1).opsize := S_B;
  7727. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7728. taicpu(hp1).loadconst(0, 1);
  7729. end;
  7730. end;
  7731. C_None:
  7732. InternalError(2020012201);
  7733. C_P, C_PE, C_NP, C_PO:
  7734. { We can't handle parity checks and they should never be generated
  7735. after a general-purpose CMP (it's used in some floating-point
  7736. comparisons that don't use CMP) }
  7737. InternalError(2020012202);
  7738. else
  7739. { Zero/Equality, Sign, their complements and all of the
  7740. signed comparisons do not need to be converted };
  7741. end;
  7742. hp2 := hp1;
  7743. end;
  7744. { Convert the instruction to a TEST }
  7745. taicpu(p).opcode := A_TEST;
  7746. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7747. Result := True;
  7748. Exit;
  7749. end
  7750. else
  7751. begin
  7752. TransferUsedRegs(TmpUsedRegs);
  7753. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7754. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7755. begin
  7756. if (taicpu(p).oper[0]^.val = 1) and
  7757. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7758. begin
  7759. { Convert; To:
  7760. cmp $1,r/m cmp $0,r/m
  7761. jl @lbl jle @lbl
  7762. (Also do inverted conditions)
  7763. }
  7764. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7765. taicpu(p).oper[0]^.val := 0;
  7766. if taicpu(hp1).condition in [C_L, C_NGE] then
  7767. taicpu(hp1).condition := C_LE
  7768. else
  7769. taicpu(hp1).condition := C_NLE;
  7770. { If the instruction is now "cmp $0,%reg", convert it to a
  7771. TEST (and effectively do the work of the "cmp $0,%reg" in
  7772. the block above)
  7773. }
  7774. if (taicpu(p).oper[1]^.typ = top_reg) then
  7775. begin
  7776. taicpu(p).opcode := A_TEST;
  7777. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7778. end;
  7779. Result := True;
  7780. Exit;
  7781. end
  7782. else if (taicpu(p).oper[1]^.typ = top_reg)
  7783. {$ifdef x86_64}
  7784. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7785. {$endif x86_64}
  7786. then
  7787. begin
  7788. { cmp register,$8000 neg register
  7789. je target --> jo target
  7790. .... only if register is deallocated before jump.}
  7791. case Taicpu(p).opsize of
  7792. S_B: v:=$80;
  7793. S_W: v:=$8000;
  7794. S_L: v:=qword($80000000);
  7795. else
  7796. internalerror(2013112905);
  7797. end;
  7798. if (taicpu(p).oper[0]^.val=v) and
  7799. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7800. begin
  7801. TransferUsedRegs(TmpUsedRegs);
  7802. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7803. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7804. begin
  7805. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7806. Taicpu(p).opcode:=A_NEG;
  7807. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7808. Taicpu(p).clearop(1);
  7809. Taicpu(p).ops:=1;
  7810. if Taicpu(hp1).condition=C_E then
  7811. Taicpu(hp1).condition:=C_O
  7812. else
  7813. Taicpu(hp1).condition:=C_NO;
  7814. Result:=true;
  7815. exit;
  7816. end;
  7817. end;
  7818. end;
  7819. end;
  7820. end;
  7821. end;
  7822. if TrySwapMovCmp(p, hp1) then
  7823. begin
  7824. Result := True;
  7825. Exit;
  7826. end;
  7827. end;
  7828. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7829. var
  7830. hp1: tai;
  7831. begin
  7832. {
  7833. remove the second (v)pxor from
  7834. pxor reg,reg
  7835. ...
  7836. pxor reg,reg
  7837. }
  7838. Result:=false;
  7839. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7840. MatchOpType(taicpu(p),top_reg,top_reg) and
  7841. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7842. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7843. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7844. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7845. begin
  7846. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7847. RemoveInstruction(hp1);
  7848. Result:=true;
  7849. Exit;
  7850. end
  7851. {
  7852. replace
  7853. pxor reg1,reg1
  7854. movapd/s reg1,reg2
  7855. dealloc reg1
  7856. by
  7857. pxor reg2,reg2
  7858. }
  7859. else if GetNextInstruction(p,hp1) and
  7860. { we mix single and double opperations here because we assume that the compiler
  7861. generates vmovapd only after double operations and vmovaps only after single operations }
  7862. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7863. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7864. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7865. (taicpu(p).oper[0]^.typ=top_reg) then
  7866. begin
  7867. TransferUsedRegs(TmpUsedRegs);
  7868. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7869. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7870. begin
  7871. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7872. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7873. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7874. RemoveInstruction(hp1);
  7875. result:=true;
  7876. end;
  7877. end;
  7878. end;
  7879. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7880. var
  7881. hp1: tai;
  7882. begin
  7883. {
  7884. remove the second (v)pxor from
  7885. (v)pxor reg,reg
  7886. ...
  7887. (v)pxor reg,reg
  7888. }
  7889. Result:=false;
  7890. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7891. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7892. begin
  7893. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7894. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7895. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7896. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7897. begin
  7898. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7899. RemoveInstruction(hp1);
  7900. Result:=true;
  7901. Exit;
  7902. end;
  7903. {$ifdef x86_64}
  7904. {
  7905. replace
  7906. vpxor reg1,reg1,reg1
  7907. vmov reg,mem
  7908. by
  7909. movq $0,mem
  7910. }
  7911. if GetNextInstruction(p,hp1) and
  7912. MatchInstruction(hp1,A_VMOVSD,[]) and
  7913. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7914. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7915. begin
  7916. TransferUsedRegs(TmpUsedRegs);
  7917. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7918. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7919. begin
  7920. taicpu(hp1).loadconst(0,0);
  7921. taicpu(hp1).opcode:=A_MOV;
  7922. taicpu(hp1).opsize:=S_Q;
  7923. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7924. RemoveCurrentP(p);
  7925. result:=true;
  7926. Exit;
  7927. end;
  7928. end;
  7929. {$endif x86_64}
  7930. end
  7931. {
  7932. replace
  7933. vpxor reg1,reg1,reg2
  7934. by
  7935. vpxor reg2,reg2,reg2
  7936. to avoid unncessary data dependencies
  7937. }
  7938. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7939. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7940. begin
  7941. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7942. { avoid unncessary data dependency }
  7943. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7944. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7945. result:=true;
  7946. exit;
  7947. end;
  7948. Result:=OptPass1VOP(p);
  7949. end;
  7950. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7951. var
  7952. hp1 : tai;
  7953. begin
  7954. result:=false;
  7955. { replace
  7956. IMul const,%mreg1,%mreg2
  7957. Mov %reg2,%mreg3
  7958. dealloc %mreg3
  7959. by
  7960. Imul const,%mreg1,%mreg23
  7961. }
  7962. if (taicpu(p).ops=3) and
  7963. GetNextInstruction(p,hp1) and
  7964. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7965. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7966. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7967. begin
  7968. TransferUsedRegs(TmpUsedRegs);
  7969. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7970. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7971. begin
  7972. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7973. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7974. RemoveInstruction(hp1);
  7975. result:=true;
  7976. end;
  7977. end;
  7978. end;
  7979. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7980. var
  7981. hp1 : tai;
  7982. begin
  7983. result:=false;
  7984. { replace
  7985. IMul %reg0,%reg1,%reg2
  7986. Mov %reg2,%reg3
  7987. dealloc %reg2
  7988. by
  7989. Imul %reg0,%reg1,%reg3
  7990. }
  7991. if GetNextInstruction(p,hp1) and
  7992. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7993. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7994. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7995. begin
  7996. TransferUsedRegs(TmpUsedRegs);
  7997. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7998. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7999. begin
  8000. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8001. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8002. RemoveInstruction(hp1);
  8003. result:=true;
  8004. end;
  8005. end;
  8006. end;
  8007. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8008. var
  8009. hp1: tai;
  8010. begin
  8011. Result:=false;
  8012. { get rid of
  8013. (v)cvtss2sd reg0,<reg1,>reg2
  8014. (v)cvtss2sd reg2,<reg2,>reg0
  8015. }
  8016. if GetNextInstruction(p,hp1) and
  8017. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8018. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8019. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8020. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8021. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8022. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8023. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8024. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8025. )
  8026. ) then
  8027. begin
  8028. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8029. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8030. begin
  8031. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8032. RemoveCurrentP(p);
  8033. RemoveInstruction(hp1);
  8034. end
  8035. else
  8036. begin
  8037. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8038. if taicpu(hp1).opcode=A_CVTSD2SS then
  8039. begin
  8040. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8041. taicpu(p).opcode:=A_MOVAPS;
  8042. end
  8043. else
  8044. begin
  8045. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8046. taicpu(p).opcode:=A_VMOVAPS;
  8047. end;
  8048. taicpu(p).ops:=2;
  8049. RemoveInstruction(hp1);
  8050. end;
  8051. Result:=true;
  8052. Exit;
  8053. end;
  8054. end;
  8055. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8056. var
  8057. hp1, hp2, hp3, hp4, hp5: tai;
  8058. ThisReg: TRegister;
  8059. begin
  8060. Result := False;
  8061. if not GetNextInstruction(p,hp1) then
  8062. Exit;
  8063. {
  8064. convert
  8065. j<c> .L1
  8066. mov 1,reg
  8067. jmp .L2
  8068. .L1
  8069. mov 0,reg
  8070. .L2
  8071. into
  8072. mov 0,reg
  8073. set<not(c)> reg
  8074. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8075. would destroy the flag contents
  8076. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8077. executed at the same time as a previous comparison.
  8078. set<not(c)> reg
  8079. movzx reg, reg
  8080. }
  8081. if MatchInstruction(hp1,A_MOV,[]) and
  8082. (taicpu(hp1).oper[0]^.typ = top_const) and
  8083. (
  8084. (
  8085. (taicpu(hp1).oper[1]^.typ = top_reg)
  8086. {$ifdef i386}
  8087. { Under i386, ESI, EDI, EBP and ESP
  8088. don't have an 8-bit representation }
  8089. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8090. {$endif i386}
  8091. ) or (
  8092. {$ifdef i386}
  8093. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8094. {$endif i386}
  8095. (taicpu(hp1).opsize = S_B)
  8096. )
  8097. ) and
  8098. GetNextInstruction(hp1,hp2) and
  8099. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8100. GetNextInstruction(hp2,hp3) and
  8101. (hp3.typ=ait_label) and
  8102. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8103. GetNextInstruction(hp3,hp4) and
  8104. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8105. (taicpu(hp4).oper[0]^.typ = top_const) and
  8106. (
  8107. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8108. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8109. ) and
  8110. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8111. GetNextInstruction(hp4,hp5) and
  8112. (hp5.typ=ait_label) and
  8113. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  8114. begin
  8115. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8116. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8117. tai_label(hp3).labsym.DecRefs;
  8118. { If this isn't the only reference to the middle label, we can
  8119. still make a saving - only that the first jump and everything
  8120. that follows will remain. }
  8121. if (tai_label(hp3).labsym.getrefs = 0) then
  8122. begin
  8123. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8124. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8125. else
  8126. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8127. { remove jump, first label and second MOV (also catching any aligns) }
  8128. repeat
  8129. if not GetNextInstruction(hp2, hp3) then
  8130. InternalError(2021040810);
  8131. RemoveInstruction(hp2);
  8132. hp2 := hp3;
  8133. until hp2 = hp5;
  8134. { Don't decrement reference count before the removal loop
  8135. above, otherwise GetNextInstruction won't stop on the
  8136. the label }
  8137. tai_label(hp5).labsym.DecRefs;
  8138. end
  8139. else
  8140. begin
  8141. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8142. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8143. else
  8144. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8145. end;
  8146. taicpu(p).opcode:=A_SETcc;
  8147. taicpu(p).opsize:=S_B;
  8148. taicpu(p).is_jmp:=False;
  8149. if taicpu(hp1).opsize=S_B then
  8150. begin
  8151. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8152. if taicpu(hp1).oper[1]^.typ = top_reg then
  8153. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8154. RemoveInstruction(hp1);
  8155. end
  8156. else
  8157. begin
  8158. { Will be a register because the size can't be S_B otherwise }
  8159. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8160. taicpu(p).loadreg(0, ThisReg);
  8161. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8162. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8163. begin
  8164. case taicpu(hp1).opsize of
  8165. S_W:
  8166. taicpu(hp1).opsize := S_BW;
  8167. S_L:
  8168. taicpu(hp1).opsize := S_BL;
  8169. {$ifdef x86_64}
  8170. S_Q:
  8171. begin
  8172. taicpu(hp1).opsize := S_BL;
  8173. { Change the destination register to 32-bit }
  8174. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8175. end;
  8176. {$endif x86_64}
  8177. else
  8178. InternalError(2021040820);
  8179. end;
  8180. taicpu(hp1).opcode := A_MOVZX;
  8181. taicpu(hp1).loadreg(0, ThisReg);
  8182. end
  8183. else
  8184. begin
  8185. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8186. { hp1 is already a MOV instruction with the correct register }
  8187. taicpu(hp1).loadconst(0, 0);
  8188. { Inserting it right before p will guarantee that the flags are also tracked }
  8189. asml.Remove(hp1);
  8190. asml.InsertBefore(hp1, p);
  8191. end;
  8192. end;
  8193. Result:=true;
  8194. exit;
  8195. end
  8196. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8197. Result := TryJccStcClcOpt(p, hp1)
  8198. else if (hp1.typ = ait_label) then
  8199. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8200. end;
  8201. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8202. var
  8203. hp1, hp2, hp3: tai;
  8204. SourceRef, TargetRef: TReference;
  8205. CurrentReg: TRegister;
  8206. begin
  8207. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8208. if not UseAVX then
  8209. InternalError(2021100501);
  8210. Result := False;
  8211. { Look for the following to simplify:
  8212. vmovdqa/u x(mem1), %xmmreg
  8213. vmovdqa/u %xmmreg, y(mem2)
  8214. vmovdqa/u x+16(mem1), %xmmreg
  8215. vmovdqa/u %xmmreg, y+16(mem2)
  8216. Change to:
  8217. vmovdqa/u x(mem1), %ymmreg
  8218. vmovdqa/u %ymmreg, y(mem2)
  8219. vpxor %ymmreg, %ymmreg, %ymmreg
  8220. ( The VPXOR instruction is to zero the upper half, thus removing the
  8221. need to call the potentially expensive VZEROUPPER instruction. Other
  8222. peephole optimisations can remove VPXOR if it's unnecessary )
  8223. }
  8224. TransferUsedRegs(TmpUsedRegs);
  8225. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8226. { NOTE: In the optimisations below, if the references dictate that an
  8227. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8228. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8229. if (taicpu(p).opsize = S_XMM) and
  8230. MatchOpType(taicpu(p), top_ref, top_reg) and
  8231. GetNextInstruction(p, hp1) and
  8232. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8233. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8234. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8235. begin
  8236. SourceRef := taicpu(p).oper[0]^.ref^;
  8237. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8238. if GetNextInstruction(hp1, hp2) and
  8239. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8240. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8241. begin
  8242. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8243. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8244. Inc(SourceRef.offset, 16);
  8245. { Reuse the register in the first block move }
  8246. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8247. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8248. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8249. begin
  8250. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8251. Inc(TargetRef.offset, 16);
  8252. if GetNextInstruction(hp2, hp3) and
  8253. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8254. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8255. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8256. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8257. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8258. begin
  8259. { Update the register tracking to the new size }
  8260. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8261. { Remember that the offsets are 16 ahead }
  8262. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8263. if not (
  8264. ((SourceRef.offset mod 32) = 16) and
  8265. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8266. ) then
  8267. taicpu(p).opcode := A_VMOVDQU;
  8268. taicpu(p).opsize := S_YMM;
  8269. taicpu(p).oper[1]^.reg := CurrentReg;
  8270. if not (
  8271. ((TargetRef.offset mod 32) = 16) and
  8272. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8273. ) then
  8274. taicpu(hp1).opcode := A_VMOVDQU;
  8275. taicpu(hp1).opsize := S_YMM;
  8276. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8277. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8278. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8279. if (pi_uses_ymm in current_procinfo.flags) then
  8280. RemoveInstruction(hp2)
  8281. else
  8282. begin
  8283. taicpu(hp2).opcode := A_VPXOR;
  8284. taicpu(hp2).opsize := S_YMM;
  8285. taicpu(hp2).loadreg(0, CurrentReg);
  8286. taicpu(hp2).loadreg(1, CurrentReg);
  8287. taicpu(hp2).loadreg(2, CurrentReg);
  8288. taicpu(hp2).ops := 3;
  8289. end;
  8290. RemoveInstruction(hp3);
  8291. Result := True;
  8292. Exit;
  8293. end;
  8294. end
  8295. else
  8296. begin
  8297. { See if the next references are 16 less rather than 16 greater }
  8298. Dec(SourceRef.offset, 32); { -16 the other way }
  8299. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8300. begin
  8301. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8302. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8303. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8304. GetNextInstruction(hp2, hp3) and
  8305. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8306. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8307. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8308. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8309. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8310. begin
  8311. { Update the register tracking to the new size }
  8312. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8313. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8314. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8315. if not(
  8316. ((SourceRef.offset mod 32) = 0) and
  8317. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8318. ) then
  8319. taicpu(hp2).opcode := A_VMOVDQU;
  8320. taicpu(hp2).opsize := S_YMM;
  8321. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8322. if not (
  8323. ((TargetRef.offset mod 32) = 0) and
  8324. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8325. ) then
  8326. taicpu(hp3).opcode := A_VMOVDQU;
  8327. taicpu(hp3).opsize := S_YMM;
  8328. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8329. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8330. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8331. if (pi_uses_ymm in current_procinfo.flags) then
  8332. RemoveInstruction(hp1)
  8333. else
  8334. begin
  8335. taicpu(hp1).opcode := A_VPXOR;
  8336. taicpu(hp1).opsize := S_YMM;
  8337. taicpu(hp1).loadreg(0, CurrentReg);
  8338. taicpu(hp1).loadreg(1, CurrentReg);
  8339. taicpu(hp1).loadreg(2, CurrentReg);
  8340. taicpu(hp1).ops := 3;
  8341. Asml.Remove(hp1);
  8342. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8343. end;
  8344. RemoveCurrentP(p, hp2);
  8345. Result := True;
  8346. Exit;
  8347. end;
  8348. end;
  8349. end;
  8350. end;
  8351. end;
  8352. end;
  8353. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8354. var
  8355. hp2, hp3, first_assignment: tai;
  8356. IncCount, OperIdx: Integer;
  8357. OrigLabel: TAsmLabel;
  8358. begin
  8359. Count := 0;
  8360. Result := False;
  8361. first_assignment := nil;
  8362. if (LoopCount >= 20) then
  8363. begin
  8364. { Guard against infinite loops }
  8365. Exit;
  8366. end;
  8367. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8368. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8369. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8370. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8371. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8372. Exit;
  8373. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8374. {
  8375. change
  8376. jmp .L1
  8377. ...
  8378. .L1:
  8379. mov ##, ## ( multiple movs possible )
  8380. jmp/ret
  8381. into
  8382. mov ##, ##
  8383. jmp/ret
  8384. }
  8385. if not Assigned(hp1) then
  8386. begin
  8387. hp1 := GetLabelWithSym(OrigLabel);
  8388. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8389. Exit;
  8390. end;
  8391. hp2 := hp1;
  8392. while Assigned(hp2) do
  8393. begin
  8394. if Assigned(hp2) and (hp2.typ = ait_label) then
  8395. SkipLabels(hp2,hp2);
  8396. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8397. Break;
  8398. case taicpu(hp2).opcode of
  8399. A_MOVSD:
  8400. begin
  8401. if taicpu(hp2).ops = 0 then
  8402. { Wrong MOVSD }
  8403. Break;
  8404. Inc(Count);
  8405. if Count >= 5 then
  8406. { Too many to be worthwhile }
  8407. Break;
  8408. GetNextInstruction(hp2, hp2);
  8409. Continue;
  8410. end;
  8411. A_MOV,
  8412. A_MOVD,
  8413. A_MOVQ,
  8414. A_MOVSX,
  8415. {$ifdef x86_64}
  8416. A_MOVSXD,
  8417. {$endif x86_64}
  8418. A_MOVZX,
  8419. A_MOVAPS,
  8420. A_MOVUPS,
  8421. A_MOVSS,
  8422. A_MOVAPD,
  8423. A_MOVUPD,
  8424. A_MOVDQA,
  8425. A_MOVDQU,
  8426. A_VMOVSS,
  8427. A_VMOVAPS,
  8428. A_VMOVUPS,
  8429. A_VMOVSD,
  8430. A_VMOVAPD,
  8431. A_VMOVUPD,
  8432. A_VMOVDQA,
  8433. A_VMOVDQU:
  8434. begin
  8435. Inc(Count);
  8436. if Count >= 5 then
  8437. { Too many to be worthwhile }
  8438. Break;
  8439. GetNextInstruction(hp2, hp2);
  8440. Continue;
  8441. end;
  8442. A_JMP:
  8443. begin
  8444. { Guard against infinite loops }
  8445. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8446. Exit;
  8447. { Analyse this jump first in case it also duplicates assignments }
  8448. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8449. begin
  8450. { Something did change! }
  8451. Result := True;
  8452. Inc(Count, IncCount);
  8453. if Count >= 5 then
  8454. begin
  8455. { Too many to be worthwhile }
  8456. Exit;
  8457. end;
  8458. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8459. Break;
  8460. end;
  8461. Result := True;
  8462. Break;
  8463. end;
  8464. A_RET:
  8465. begin
  8466. Result := True;
  8467. Break;
  8468. end;
  8469. else
  8470. Break;
  8471. end;
  8472. end;
  8473. if Result then
  8474. begin
  8475. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8476. if Count = 0 then
  8477. begin
  8478. Result := False;
  8479. Exit;
  8480. end;
  8481. TransferUsedRegs(TmpUsedRegs);
  8482. hp3 := p;
  8483. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8484. while True do
  8485. begin
  8486. if Assigned(hp1) and (hp1.typ = ait_label) then
  8487. SkipLabels(hp1,hp1);
  8488. case hp1.typ of
  8489. ait_regalloc:
  8490. if tai_regalloc(hp1).ratype = ra_dealloc then
  8491. begin
  8492. { Duplicate the register deallocation... }
  8493. hp3:=tai(hp1.getcopy);
  8494. if first_assignment = nil then
  8495. first_assignment := hp3;
  8496. asml.InsertBefore(hp3, p);
  8497. { ... but also reallocate it after the jump }
  8498. hp3:=tai(hp1.getcopy);
  8499. tai_regalloc(hp3).ratype := ra_alloc;
  8500. asml.InsertAfter(hp3, p);
  8501. end;
  8502. ait_instruction:
  8503. case taicpu(hp1).opcode of
  8504. A_JMP:
  8505. begin
  8506. { Change the original jump to the new destination }
  8507. OrigLabel.decrefs;
  8508. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8509. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8510. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8511. if not Assigned(first_assignment) then
  8512. InternalError(2021040810)
  8513. else
  8514. p := first_assignment;
  8515. Exit;
  8516. end;
  8517. A_RET:
  8518. begin
  8519. { Now change the jump into a RET instruction }
  8520. ConvertJumpToRET(p, hp1);
  8521. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8522. if not Assigned(first_assignment) then
  8523. InternalError(2021040811)
  8524. else
  8525. p := first_assignment;
  8526. Exit;
  8527. end;
  8528. else
  8529. begin
  8530. { Duplicate the MOV instruction }
  8531. hp3:=tai(hp1.getcopy);
  8532. if first_assignment = nil then
  8533. first_assignment := hp3;
  8534. asml.InsertBefore(hp3, p);
  8535. { Make sure the compiler knows about any final registers written here }
  8536. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8537. with taicpu(hp3).oper[OperIdx]^ do
  8538. begin
  8539. case typ of
  8540. top_ref:
  8541. begin
  8542. if (ref^.base <> NR_NO) and
  8543. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8544. (
  8545. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8546. (
  8547. { Allow the frame pointer if it's not being used by the procedure as such }
  8548. Assigned(current_procinfo) and
  8549. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8550. )
  8551. )
  8552. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8553. then
  8554. begin
  8555. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8556. if not Assigned(first_assignment) then
  8557. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8558. end;
  8559. if (ref^.index <> NR_NO) and
  8560. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8561. (
  8562. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8563. (
  8564. { Allow the frame pointer if it's not being used by the procedure as such }
  8565. Assigned(current_procinfo) and
  8566. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8567. )
  8568. )
  8569. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8570. (ref^.index <> ref^.base) then
  8571. begin
  8572. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8573. if not Assigned(first_assignment) then
  8574. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8575. end;
  8576. end;
  8577. top_reg:
  8578. begin
  8579. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8580. if not Assigned(first_assignment) then
  8581. IncludeRegInUsedRegs(reg, UsedRegs);
  8582. end;
  8583. else
  8584. ;
  8585. end;
  8586. end;
  8587. end;
  8588. end;
  8589. else
  8590. InternalError(2021040720);
  8591. end;
  8592. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8593. { Should have dropped out earlier }
  8594. InternalError(2021040710);
  8595. end;
  8596. end;
  8597. end;
  8598. const
  8599. WriteOp: array[0..3] of set of TInsChange = (
  8600. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8601. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8602. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8603. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8604. RegWriteFlags: array[0..7] of set of TInsChange = (
  8605. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8606. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8607. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8608. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8609. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8610. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8611. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8612. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8613. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8614. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8615. var
  8616. hp2: tai;
  8617. X: Integer;
  8618. begin
  8619. { If we have something like:
  8620. op ###,###
  8621. mov ###,###
  8622. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8623. interfere in regards to what they write to.
  8624. NOTE: p must be a 2-operand instruction
  8625. }
  8626. Result := False;
  8627. if (hp1.typ <> ait_instruction) or
  8628. taicpu(hp1).is_jmp or
  8629. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8630. Exit;
  8631. { NOP is a pipeline fence, likely marking the beginning of the function
  8632. epilogue, so drop out. Similarly, drop out if POP or RET are
  8633. encountered }
  8634. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8635. Exit;
  8636. if (taicpu(hp1).opcode = A_MOVSD) and
  8637. (taicpu(hp1).ops = 0) then
  8638. { Wrong MOVSD }
  8639. Exit;
  8640. { Check for writes to specific registers first }
  8641. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8642. for X := 0 to 7 do
  8643. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8644. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8645. Exit;
  8646. for X := 0 to taicpu(hp1).ops - 1 do
  8647. begin
  8648. { Check to see if this operand writes to something }
  8649. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8650. { And matches something in the CMP/TEST instruction }
  8651. (
  8652. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8653. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8654. (
  8655. { If it's a register, make sure the register written to doesn't
  8656. appear in the cmp instruction as part of a reference }
  8657. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8658. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8659. )
  8660. ) then
  8661. Exit;
  8662. end;
  8663. { Check p to make sure it doesn't write to something that affects hp1 }
  8664. { Check for writes to specific registers first }
  8665. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8666. for X := 0 to 7 do
  8667. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8668. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8669. Exit;
  8670. for X := 0 to taicpu(p).ops - 1 do
  8671. begin
  8672. { Check to see if this operand writes to something }
  8673. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8674. { And matches something in hp1 }
  8675. (taicpu(p).oper[X]^.typ = top_reg) and
  8676. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8677. Exit;
  8678. end;
  8679. { The instruction can be safely moved }
  8680. asml.Remove(hp1);
  8681. { Try to insert after the last instructions where the FLAGS register is not
  8682. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8683. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8684. asml.InsertBefore(hp1, hp2)
  8685. { Failing that, try to insert after the last instructions where the
  8686. FLAGS register is not yet in use }
  8687. else if GetLastInstruction(p, hp2) and
  8688. (
  8689. (hp2.typ <> ait_instruction) or
  8690. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8691. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8692. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8693. ) then
  8694. asml.InsertAfter(hp1, hp2)
  8695. else
  8696. { Note, if p.Previous is nil (even if it should logically never be the
  8697. case), FindRegAllocBackward immediately exits with False and so we
  8698. safely land here (we can't just pass p because FindRegAllocBackward
  8699. immediately exits on an instruction). [Kit] }
  8700. asml.InsertBefore(hp1, p);
  8701. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8702. { We can't trust UsedRegs because we're looking backwards, although we
  8703. know the registers are allocated after p at the very least, so manually
  8704. create tai_regalloc objects if needed }
  8705. for X := 0 to taicpu(hp1).ops - 1 do
  8706. case taicpu(hp1).oper[X]^.typ of
  8707. top_reg:
  8708. begin
  8709. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8710. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8711. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8712. end;
  8713. top_ref:
  8714. begin
  8715. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8716. begin
  8717. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8718. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8719. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8720. end;
  8721. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8722. begin
  8723. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8724. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8725. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8726. end;
  8727. end;
  8728. else
  8729. ;
  8730. end;
  8731. Result := True;
  8732. end;
  8733. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8734. var
  8735. hp2: tai;
  8736. X: Integer;
  8737. begin
  8738. { If we have something like:
  8739. cmp ###,%reg1
  8740. mov 0,%reg2
  8741. And no modified registers are shared, move the instruction to before
  8742. the comparison as this means it can be optimised without worrying
  8743. about the FLAGS register. (CMP/MOV is generated by
  8744. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8745. As long as the second instruction doesn't use the flags or one of the
  8746. registers used by CMP or TEST (also check any references that use the
  8747. registers), then it can be moved prior to the comparison.
  8748. }
  8749. Result := False;
  8750. if not TrySwapMovOp(p, hp1) then
  8751. Exit;
  8752. if taicpu(hp1).opcode = A_LEA then
  8753. { The flags will be overwritten by the CMP/TEST instruction }
  8754. ConvertLEA(taicpu(hp1));
  8755. Result := True;
  8756. { Can we move it one further back? }
  8757. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8758. { Check to see if CMP/TEST is a comparison against zero }
  8759. (
  8760. (
  8761. (taicpu(p).opcode = A_CMP) and
  8762. MatchOperand(taicpu(p).oper[0]^, 0)
  8763. ) or
  8764. (
  8765. (taicpu(p).opcode = A_TEST) and
  8766. (
  8767. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8768. MatchOperand(taicpu(p).oper[0]^, -1)
  8769. )
  8770. )
  8771. ) and
  8772. { These instructions set the zero flag if the result is zero }
  8773. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8774. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8775. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8776. TrySwapMovOp(hp2, hp1);
  8777. end;
  8778. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8779. var
  8780. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8781. JumpLabel: TAsmLabel;
  8782. TmpBool: Boolean;
  8783. begin
  8784. Result := False;
  8785. { Look for:
  8786. stc/clc
  8787. j(c) .L1
  8788. ...
  8789. .L1:
  8790. set(n)cb %reg
  8791. (flags deallocated)
  8792. j(c) .L2
  8793. Change to:
  8794. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8795. j(c) .L2
  8796. }
  8797. p_last := p;
  8798. while GetNextInstruction(p_last, hp1) and
  8799. (hp1.typ = ait_instruction) and
  8800. IsJumpToLabel(taicpu(hp1)) do
  8801. begin
  8802. if DoJumpOptimizations(hp1, TmpBool) then
  8803. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8804. Continue;
  8805. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8806. if not Assigned(JumpLabel) then
  8807. InternalError(2024012801);
  8808. { Optimise the J(c); stc/clc optimisation first since this will
  8809. get missed if the main optimisation takes place }
  8810. if (taicpu(hp1).opcode = A_JCC) then
  8811. begin
  8812. if GetNextInstruction(hp1, hp2) and
  8813. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8814. TryJccStcClcOpt(hp1, hp2) then
  8815. begin
  8816. Result := True;
  8817. Exit;
  8818. end;
  8819. hp2 := nil; { Suppress compiler warning }
  8820. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8821. { Make sure the flags aren't used again }
  8822. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8823. begin
  8824. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8825. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8826. begin
  8827. if (taicpu(p).opcode = A_STC) then
  8828. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8829. else
  8830. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8831. MakeUnconditional(taicpu(hp1));
  8832. { Move the jump to after the flag deallocations }
  8833. Asml.Remove(hp1);
  8834. Asml.InsertAfter(hp1, hp2);
  8835. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8836. Result := True;
  8837. Exit;
  8838. end
  8839. else
  8840. begin
  8841. if (taicpu(p).opcode = A_STC) then
  8842. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8843. else
  8844. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8845. { In this case, the jump is deterministic in that it will never be taken }
  8846. JumpLabel.DecRefs;
  8847. RemoveInstruction(hp1);
  8848. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8849. Result := True;
  8850. Exit;
  8851. end;
  8852. end;
  8853. end;
  8854. hp2 := nil; { Suppress compiler warning }
  8855. if
  8856. { Make sure the carry flag doesn't appear in the jump conditions }
  8857. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8858. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8859. GetNextInstruction(hp2, p_dist) and
  8860. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8861. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8862. begin
  8863. case taicpu(p_dist).opcode of
  8864. A_Jcc:
  8865. begin
  8866. if DoJumpOptimizations(p_dist, TmpBool) then
  8867. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8868. Continue;
  8869. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8870. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8871. begin
  8872. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8873. JumpLabel.decrefs;
  8874. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8875. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8876. Result := True;
  8877. Exit;
  8878. end
  8879. else if GetNextInstruction(p_dist, hp1_dist) and
  8880. (hp1_dist.typ = ait_label) then
  8881. begin
  8882. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8883. JumpLabel.decrefs;
  8884. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8885. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8886. Result := True;
  8887. Exit;
  8888. end;
  8889. end;
  8890. A_SETcc:
  8891. if { Make sure the flags aren't used again }
  8892. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8893. GetNextInstruction(hp2, hp1_dist) and
  8894. (hp1_dist.typ = ait_instruction) and
  8895. IsJumpToLabel(taicpu(hp1_dist)) and
  8896. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8897. { This works if hp1_dist or both are regular JMP instructions }
  8898. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8899. (
  8900. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8901. { Make sure the register isn't still in use, otherwise it
  8902. may get corrupted (fixes #40659) }
  8903. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8904. ) then
  8905. begin
  8906. taicpu(p).allocate_oper(2);
  8907. taicpu(p).ops := 2;
  8908. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8909. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8910. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8911. taicpu(p).opcode := A_MOV;
  8912. taicpu(p).opsize := S_B;
  8913. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8914. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8915. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8916. JumpLabel.decrefs;
  8917. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8918. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8919. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8920. (tai_regalloc(hp2).ratype = ra_alloc) then
  8921. begin
  8922. Asml.Remove(hp2);
  8923. Asml.InsertAfter(hp2, p);
  8924. end;
  8925. Result := True;
  8926. Exit;
  8927. end;
  8928. else
  8929. ;
  8930. end;
  8931. end;
  8932. p_last := hp1;
  8933. end;
  8934. end;
  8935. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8936. var
  8937. hp2, hp3: tai;
  8938. TempBool: Boolean;
  8939. begin
  8940. Result := False;
  8941. {
  8942. j(c) .L1
  8943. stc/clc
  8944. .L1:
  8945. jc/jnc .L2
  8946. (Flags deallocated)
  8947. Change to:
  8948. j)c) .L1
  8949. jmp .L2
  8950. .L1:
  8951. jc/jnc .L2
  8952. Then call DoJumpOptimizations to convert to:
  8953. j(nc) .L2
  8954. .L1: (may become a dead label)
  8955. jc/jnc .L2
  8956. }
  8957. if GetNextInstruction(hp1, hp2) and
  8958. (hp2.typ = ait_label) and
  8959. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8960. GetNextInstruction(hp2, hp3) and
  8961. MatchInstruction(hp3, A_Jcc, []) and
  8962. (
  8963. (
  8964. (taicpu(hp3).condition = C_C) and
  8965. (taicpu(hp1).opcode = A_STC)
  8966. ) or (
  8967. (taicpu(hp3).condition = C_NC) and
  8968. (taicpu(hp1).opcode = A_CLC)
  8969. )
  8970. ) and
  8971. { Make sure the flags aren't used again }
  8972. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8973. begin
  8974. taicpu(hp1).allocate_oper(1);
  8975. taicpu(hp1).ops := 1;
  8976. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8977. taicpu(hp1).opcode := A_JMP;
  8978. taicpu(hp1).is_jmp := True;
  8979. TempBool := True; { Prevent compiler warnings }
  8980. if DoJumpOptimizations(p, TempBool) then
  8981. Result := True
  8982. else
  8983. Include(OptsToCheck, aoc_ForceNewIteration);
  8984. end;
  8985. end;
  8986. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8987. begin
  8988. { This generally only executes under -O3 and above }
  8989. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8990. end;
  8991. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8992. var
  8993. hp1, hp2: tai;
  8994. FoundComparison: Boolean;
  8995. begin
  8996. { Run the pass 1 optimisations as well, since they may have some effect
  8997. after the CMOV blocks are created in OptPass2Jcc }
  8998. Result := False;
  8999. { Result := OptPass1CMOVcc(p);
  9000. if Result then
  9001. Exit;}
  9002. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9003. and make a slightly inefficent result on branching-type blocks, notably
  9004. when setting a function result then jumping to the function epilogue.
  9005. In this case, change:
  9006. cmov(c) %reg1,%reg2
  9007. j(c) @lbl
  9008. (%reg2 deallocated)
  9009. To:
  9010. mov %reg11,%reg2
  9011. j(c) @lbl
  9012. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9013. jump because if it's not present, we may end up with a jump that's
  9014. completely unrelated.
  9015. }
  9016. hp1 := p;
  9017. while GetNextInstruction(hp1, hp1) and
  9018. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9019. if (hp1.typ = ait_instruction) and
  9020. (taicpu(hp1).opcode = A_Jcc) and
  9021. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9022. begin
  9023. TransferUsedRegs(TmpUsedRegs);
  9024. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9025. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9026. (
  9027. { See if we can find a more distant instruction that overwrites
  9028. the destination register }
  9029. (cs_opt_level3 in current_settings.optimizerswitches) and
  9030. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9031. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9032. ) then
  9033. begin
  9034. if (taicpu(p).oper[0]^.typ = top_reg) then
  9035. begin
  9036. { Search backwards to see if the source register is set to a
  9037. constant }
  9038. FoundComparison := False;
  9039. hp1 := p;
  9040. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9041. begin
  9042. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9043. begin
  9044. FoundComparison := True;
  9045. Continue;
  9046. end;
  9047. { Once we find the CMP, TEST or similar instruction, we
  9048. have to stop if we find anything other than a MOV }
  9049. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9050. Break;
  9051. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9052. { Destination register was modified }
  9053. Break;
  9054. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9055. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9056. begin
  9057. { Found a constant! }
  9058. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9059. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9060. { The source register is no longer in use }
  9061. RemoveInstruction(hp1);
  9062. Break;
  9063. end;
  9064. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9065. { Some other instruction has modified the source register }
  9066. Break;
  9067. end;
  9068. end;
  9069. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9070. taicpu(p).opcode := A_MOV;
  9071. taicpu(p).condition := C_None;
  9072. { Rely on the post peephole stage to put the MOV before the
  9073. CMP/TEST instruction that appears prior }
  9074. Result := True;
  9075. Exit;
  9076. end;
  9077. end;
  9078. end;
  9079. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9080. function IsXCHGAcceptable: Boolean; inline;
  9081. begin
  9082. { Always accept if optimising for size }
  9083. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9084. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9085. than 3, so it becomes a saving compared to three MOVs with two of
  9086. them able to execute simultaneously. [Kit] }
  9087. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9088. end;
  9089. var
  9090. NewRef: TReference;
  9091. hp1, hp2, hp3, hp4: Tai;
  9092. {$ifndef x86_64}
  9093. OperIdx: Integer;
  9094. {$endif x86_64}
  9095. NewInstr : Taicpu;
  9096. NewAligh : Tai_align;
  9097. DestLabel: TAsmLabel;
  9098. TempTracking: TAllUsedRegs;
  9099. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9100. var
  9101. NextInstr: tai;
  9102. begin
  9103. Result := False;
  9104. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9105. if not GetNextInstruction(InputInstr, NextInstr) or
  9106. (
  9107. { The FLAGS register isn't always tracked properly, so do not
  9108. perform this optimisation if a conditional statement follows }
  9109. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9110. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9111. ) then
  9112. begin
  9113. reference_reset(NewRef, 1, []);
  9114. NewRef.base := taicpu(p).oper[0]^.reg;
  9115. NewRef.scalefactor := 1;
  9116. if taicpu(InputInstr).opcode = A_ADD then
  9117. begin
  9118. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9119. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9120. end
  9121. else
  9122. begin
  9123. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9124. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9125. end;
  9126. taicpu(p).opcode := A_LEA;
  9127. taicpu(p).loadref(0, NewRef);
  9128. { For the sake of debugging, have the line info match the
  9129. arithmetic instruction rather than the MOV instruction }
  9130. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9131. RemoveInstruction(InputInstr);
  9132. Result := True;
  9133. end;
  9134. end;
  9135. begin
  9136. Result:=false;
  9137. { This optimisation adds an instruction, so only do it for speed }
  9138. if not (cs_opt_size in current_settings.optimizerswitches) and
  9139. MatchOpType(taicpu(p), top_const, top_reg) and
  9140. (taicpu(p).oper[0]^.val = 0) then
  9141. begin
  9142. { To avoid compiler warning }
  9143. DestLabel := nil;
  9144. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9145. InternalError(2021040750);
  9146. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9147. Exit;
  9148. case hp1.typ of
  9149. ait_label:
  9150. begin
  9151. { Change:
  9152. mov $0,%reg mov $0,%reg
  9153. @Lbl1: @Lbl1:
  9154. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9155. je @Lbl2 jne @Lbl2
  9156. To: To:
  9157. mov $0,%reg mov $0,%reg
  9158. jmp @Lbl2 jmp @Lbl3
  9159. (align) (align)
  9160. @Lbl1: @Lbl1:
  9161. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9162. je @Lbl2 je @Lbl2
  9163. @Lbl3: <-- Only if label exists
  9164. (Not if it's optimised for size)
  9165. }
  9166. if not GetNextInstruction(hp1, hp2) then
  9167. Exit;
  9168. if (hp2.typ = ait_instruction) and
  9169. (
  9170. { Register sizes must exactly match }
  9171. (
  9172. (taicpu(hp2).opcode = A_CMP) and
  9173. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9174. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9175. ) or (
  9176. (taicpu(hp2).opcode = A_TEST) and
  9177. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9178. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9179. )
  9180. ) and GetNextInstruction(hp2, hp3) and
  9181. (hp3.typ = ait_instruction) and
  9182. (taicpu(hp3).opcode = A_JCC) and
  9183. (taicpu(hp3).oper[0]^.typ=top_ref) and (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and (taicpu(hp3).oper[0]^.ref^.base=NR_NO) and
  9184. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9185. begin
  9186. { Check condition of jump }
  9187. { Always true? }
  9188. if condition_in(C_E, taicpu(hp3).condition) then
  9189. begin
  9190. { Copy label symbol and obtain matching label entry for the
  9191. conditional jump, as this will be our destination}
  9192. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9193. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9194. Result := True;
  9195. end
  9196. { Always false? }
  9197. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9198. begin
  9199. { This is only worth it if there's a jump to take }
  9200. case hp2.typ of
  9201. ait_instruction:
  9202. begin
  9203. if taicpu(hp2).opcode = A_JMP then
  9204. begin
  9205. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9206. { An unconditional jump follows the conditional jump which will always be false,
  9207. so use this jump's destination for the new jump }
  9208. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9209. Result := True;
  9210. end
  9211. else if taicpu(hp2).opcode = A_JCC then
  9212. begin
  9213. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9214. if condition_in(C_E, taicpu(hp2).condition) then
  9215. begin
  9216. { A second conditional jump follows the conditional jump which will always be false,
  9217. while the second jump is always True, so use this jump's destination for the new jump }
  9218. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9219. Result := True;
  9220. end;
  9221. { Don't risk it if the jump isn't always true (Result remains False) }
  9222. end;
  9223. end;
  9224. else
  9225. { If anything else don't optimise };
  9226. end;
  9227. end;
  9228. if Result then
  9229. begin
  9230. { Just so we have something to insert as a paremeter}
  9231. reference_reset(NewRef, 1, []);
  9232. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9233. { Now actually load the correct parameter (this also
  9234. increases the reference count) }
  9235. NewInstr.loadsymbol(0, DestLabel, 0);
  9236. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9237. begin
  9238. { Get instruction before original label (may not be p under -O3) }
  9239. if not GetLastInstruction(hp1, hp2) then
  9240. { Shouldn't fail here }
  9241. InternalError(2021040701);
  9242. end
  9243. else
  9244. hp2 := p;
  9245. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9246. AsmL.InsertAfter(NewInstr, hp2);
  9247. { Add new alignment field }
  9248. (* AsmL.InsertAfter(
  9249. cai_align.create_max(
  9250. current_settings.alignment.jumpalign,
  9251. current_settings.alignment.jumpalignskipmax
  9252. ),
  9253. NewInstr
  9254. ); *)
  9255. end;
  9256. Exit;
  9257. end;
  9258. end;
  9259. else
  9260. ;
  9261. end;
  9262. end;
  9263. if not GetNextInstruction(p, hp1) then
  9264. Exit;
  9265. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9266. begin
  9267. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9268. begin
  9269. Result := True;
  9270. Exit;
  9271. end;
  9272. { This optimisation is only effective on a second run of Pass 2,
  9273. hence -O3 or above.
  9274. Change:
  9275. mov %reg1,%reg2
  9276. cmp/test (contains %reg1)
  9277. mov x, %reg1
  9278. (another mov or a j(c))
  9279. To:
  9280. mov %reg1,%reg2
  9281. mov x, %reg1
  9282. cmp (%reg1 replaced with %reg2)
  9283. (another mov or a j(c))
  9284. The requirement of an additional MOV or a jump ensures there
  9285. isn't performance loss, since a j(c) will permit macro-fusion
  9286. with the cmp instruction, while another MOV likely means it's
  9287. not all being executed in a single cycle due to parallelisation.
  9288. }
  9289. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9290. MatchOpType(taicpu(p), top_reg, top_reg) and
  9291. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9292. GetNextInstruction(hp1, hp2) and
  9293. MatchInstruction(hp2, A_MOV, []) and
  9294. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9295. { Registers don't have to be the same size in this case }
  9296. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9297. GetNextInstruction(hp2, hp3) and
  9298. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9299. { Make sure the operands in the camparison can be safely replaced }
  9300. (
  9301. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9302. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9303. ) and
  9304. (
  9305. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9306. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9307. ) then
  9308. begin
  9309. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9310. AsmL.Remove(hp2);
  9311. AsmL.InsertAfter(hp2, p);
  9312. Result := True;
  9313. Exit;
  9314. end;
  9315. end;
  9316. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9317. begin
  9318. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9319. further, but we can't just put this jump optimisation in pass 1
  9320. because it tends to perform worse when conditional jumps are
  9321. nearby (e.g. when converting CMOV instructions). [Kit] }
  9322. CopyUsedRegs(TempTracking);
  9323. UpdateUsedRegs(tai(p.Next));
  9324. if OptPass2JMP(hp1) then
  9325. begin
  9326. { Restore register state }
  9327. RestoreUsedRegs(TempTracking);
  9328. ReleaseUsedRegs(TempTracking);
  9329. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9330. OptPass1MOV(p);
  9331. Result := True;
  9332. Exit;
  9333. end;
  9334. { If OptPass2JMP returned False, no optimisations were done to
  9335. the jump and there are no further optimisations that can be done
  9336. to the MOV instruction on this pass other than FuncMov2Func }
  9337. { Restore register state }
  9338. RestoreUsedRegs(TempTracking);
  9339. ReleaseUsedRegs(TempTracking);
  9340. Result := FuncMov2Func(p, hp1);
  9341. Exit;
  9342. end;
  9343. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9344. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9345. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9346. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9347. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9348. begin
  9349. { Change:
  9350. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9351. addl/q $x,%reg2 subl/q $x,%reg2
  9352. To:
  9353. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9354. }
  9355. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9356. { be lazy, checking separately for sub would be slightly better }
  9357. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9358. begin
  9359. TransferUsedRegs(TmpUsedRegs);
  9360. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9361. if TryMovArith2Lea(hp1) then
  9362. begin
  9363. Result := True;
  9364. Exit;
  9365. end
  9366. end
  9367. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9368. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9369. { Same as above, but also adds or subtracts to %reg2 in between.
  9370. It's still valid as long as the flags aren't in use }
  9371. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9372. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9373. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9374. { be lazy, checking separately for sub would be slightly better }
  9375. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9376. begin
  9377. TransferUsedRegs(TmpUsedRegs);
  9378. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9379. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9380. if TryMovArith2Lea(hp2) then
  9381. begin
  9382. Result := True;
  9383. Exit;
  9384. end;
  9385. end;
  9386. end;
  9387. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9388. {$ifdef x86_64}
  9389. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9390. {$else x86_64}
  9391. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9392. {$endif x86_64}
  9393. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9394. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9395. { mov reg1, reg2 mov reg1, reg2
  9396. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9397. begin
  9398. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9399. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9400. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9401. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9402. TransferUsedRegs(TmpUsedRegs);
  9403. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9404. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9405. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9406. then
  9407. begin
  9408. RemoveCurrentP(p, hp1);
  9409. Result:=true;
  9410. end;
  9411. Exit;
  9412. end;
  9413. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9414. IsXCHGAcceptable and
  9415. { XCHG doesn't support 8-bit registers }
  9416. (taicpu(p).opsize <> S_B) and
  9417. MatchInstruction(hp1, A_MOV, []) and
  9418. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9419. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9420. GetNextInstruction(hp1, hp2) and
  9421. MatchInstruction(hp2, A_MOV, []) and
  9422. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9423. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9424. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9425. begin
  9426. { mov %reg1,%reg2
  9427. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9428. mov %reg2,%reg3
  9429. (%reg2 not used afterwards)
  9430. Note that xchg takes 3 cycles to execute, and generally mov's take
  9431. only one cycle apiece, but the first two mov's can be executed in
  9432. parallel, only taking 2 cycles overall. Older processors should
  9433. therefore only optimise for size. [Kit]
  9434. }
  9435. TransferUsedRegs(TmpUsedRegs);
  9436. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9437. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9438. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9439. begin
  9440. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9441. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9442. taicpu(hp1).opcode := A_XCHG;
  9443. RemoveCurrentP(p, hp1);
  9444. RemoveInstruction(hp2);
  9445. Result := True;
  9446. Exit;
  9447. end;
  9448. end;
  9449. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9450. MatchInstruction(hp1, A_SAR, []) then
  9451. begin
  9452. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9453. begin
  9454. { the use of %edx also covers the opsize being S_L }
  9455. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9456. begin
  9457. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9458. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9459. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9460. begin
  9461. { Change:
  9462. movl %eax,%edx
  9463. sarl $31,%edx
  9464. To:
  9465. cltd
  9466. }
  9467. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9468. RemoveInstruction(hp1);
  9469. taicpu(p).opcode := A_CDQ;
  9470. taicpu(p).opsize := S_NO;
  9471. taicpu(p).clearop(1);
  9472. taicpu(p).clearop(0);
  9473. taicpu(p).ops:=0;
  9474. Result := True;
  9475. Exit;
  9476. end
  9477. else if (cs_opt_size in current_settings.optimizerswitches) and
  9478. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9479. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9480. begin
  9481. { Change:
  9482. movl %edx,%eax
  9483. sarl $31,%edx
  9484. To:
  9485. movl %edx,%eax
  9486. cltd
  9487. Note that this creates a dependency between the two instructions,
  9488. so only perform if optimising for size.
  9489. }
  9490. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9491. taicpu(hp1).opcode := A_CDQ;
  9492. taicpu(hp1).opsize := S_NO;
  9493. taicpu(hp1).clearop(1);
  9494. taicpu(hp1).clearop(0);
  9495. taicpu(hp1).ops:=0;
  9496. Include(OptsToCheck, aoc_ForceNewIteration);
  9497. Exit;
  9498. end;
  9499. {$ifndef x86_64}
  9500. end
  9501. { Don't bother if CMOV is supported, because a more optimal
  9502. sequence would have been generated for the Abs() intrinsic }
  9503. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9504. { the use of %eax also covers the opsize being S_L }
  9505. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9506. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9507. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9508. GetNextInstruction(hp1, hp2) and
  9509. MatchInstruction(hp2, A_XOR, [S_L]) and
  9510. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9511. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9512. GetNextInstruction(hp2, hp3) and
  9513. MatchInstruction(hp3, A_SUB, [S_L]) and
  9514. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9515. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9516. begin
  9517. { Change:
  9518. movl %eax,%edx
  9519. sarl $31,%eax
  9520. xorl %eax,%edx
  9521. subl %eax,%edx
  9522. (Instruction that uses %edx)
  9523. (%eax deallocated)
  9524. (%edx deallocated)
  9525. To:
  9526. cltd
  9527. xorl %edx,%eax <-- Note the registers have swapped
  9528. subl %edx,%eax
  9529. (Instruction that uses %eax) <-- %eax rather than %edx
  9530. }
  9531. TransferUsedRegs(TmpUsedRegs);
  9532. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9533. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9534. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9535. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9536. begin
  9537. if GetNextInstruction(hp3, hp4) and
  9538. not RegModifiedByInstruction(NR_EDX, hp4) and
  9539. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9540. begin
  9541. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9542. taicpu(p).opcode := A_CDQ;
  9543. taicpu(p).clearop(1);
  9544. taicpu(p).clearop(0);
  9545. taicpu(p).ops:=0;
  9546. RemoveInstruction(hp1);
  9547. taicpu(hp2).loadreg(0, NR_EDX);
  9548. taicpu(hp2).loadreg(1, NR_EAX);
  9549. taicpu(hp3).loadreg(0, NR_EDX);
  9550. taicpu(hp3).loadreg(1, NR_EAX);
  9551. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9552. { Convert references in the following instruction (hp4) from %edx to %eax }
  9553. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9554. with taicpu(hp4).oper[OperIdx]^ do
  9555. case typ of
  9556. top_reg:
  9557. if getsupreg(reg) = RS_EDX then
  9558. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9559. top_ref:
  9560. begin
  9561. if getsupreg(reg) = RS_EDX then
  9562. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9563. if getsupreg(reg) = RS_EDX then
  9564. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9565. end;
  9566. else
  9567. ;
  9568. end;
  9569. Result := True;
  9570. Exit;
  9571. end;
  9572. end;
  9573. {$else x86_64}
  9574. end;
  9575. end
  9576. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9577. { the use of %rdx also covers the opsize being S_Q }
  9578. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9579. begin
  9580. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9581. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9582. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9583. begin
  9584. { Change:
  9585. movq %rax,%rdx
  9586. sarq $63,%rdx
  9587. To:
  9588. cqto
  9589. }
  9590. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9591. RemoveInstruction(hp1);
  9592. taicpu(p).opcode := A_CQO;
  9593. taicpu(p).opsize := S_NO;
  9594. taicpu(p).clearop(1);
  9595. taicpu(p).clearop(0);
  9596. taicpu(p).ops:=0;
  9597. Result := True;
  9598. Exit;
  9599. end
  9600. else if (cs_opt_size in current_settings.optimizerswitches) and
  9601. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9602. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9603. begin
  9604. { Change:
  9605. movq %rdx,%rax
  9606. sarq $63,%rdx
  9607. To:
  9608. movq %rdx,%rax
  9609. cqto
  9610. Note that this creates a dependency between the two instructions,
  9611. so only perform if optimising for size.
  9612. }
  9613. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9614. taicpu(hp1).opcode := A_CQO;
  9615. taicpu(hp1).opsize := S_NO;
  9616. taicpu(hp1).clearop(1);
  9617. taicpu(hp1).clearop(0);
  9618. taicpu(hp1).ops:=0;
  9619. Include(OptsToCheck, aoc_ForceNewIteration);
  9620. Exit;
  9621. {$endif x86_64}
  9622. end;
  9623. end;
  9624. end;
  9625. if MatchInstruction(hp1, A_MOV, []) and
  9626. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9627. { Though "GetNextInstruction" could be factored out, along with
  9628. the instructions that depend on hp2, it is an expensive call that
  9629. should be delayed for as long as possible, hence we do cheaper
  9630. checks first that are likely to be False. [Kit] }
  9631. begin
  9632. if (
  9633. (
  9634. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9635. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9636. (
  9637. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9638. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9639. )
  9640. ) or
  9641. (
  9642. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9643. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9644. (
  9645. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9646. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9647. )
  9648. )
  9649. ) and
  9650. GetNextInstruction(hp1, hp2) and
  9651. MatchInstruction(hp2, A_SAR, []) and
  9652. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9653. begin
  9654. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9655. begin
  9656. { Change:
  9657. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9658. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9659. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9660. To:
  9661. movl r/m,%eax <- Note the change in register
  9662. cltd
  9663. }
  9664. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9665. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9666. taicpu(p).loadreg(1, NR_EAX);
  9667. taicpu(hp1).opcode := A_CDQ;
  9668. taicpu(hp1).clearop(1);
  9669. taicpu(hp1).clearop(0);
  9670. taicpu(hp1).ops:=0;
  9671. RemoveInstruction(hp2);
  9672. Include(OptsToCheck, aoc_ForceNewIteration);
  9673. (*
  9674. {$ifdef x86_64}
  9675. end
  9676. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9677. { This code sequence does not get generated - however it might become useful
  9678. if and when 128-bit signed integer types make an appearance, so the code
  9679. is kept here for when it is eventually needed. [Kit] }
  9680. (
  9681. (
  9682. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9683. (
  9684. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9685. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9686. )
  9687. ) or
  9688. (
  9689. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9690. (
  9691. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9692. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9693. )
  9694. )
  9695. ) and
  9696. GetNextInstruction(hp1, hp2) and
  9697. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9698. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9699. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9700. begin
  9701. { Change:
  9702. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9703. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9704. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9705. To:
  9706. movq r/m,%rax <- Note the change in register
  9707. cqto
  9708. }
  9709. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9710. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9711. taicpu(p).loadreg(1, NR_RAX);
  9712. taicpu(hp1).opcode := A_CQO;
  9713. taicpu(hp1).clearop(1);
  9714. taicpu(hp1).clearop(0);
  9715. taicpu(hp1).ops:=0;
  9716. RemoveInstruction(hp2);
  9717. Include(OptsToCheck, aoc_ForceNewIteration);
  9718. {$endif x86_64}
  9719. *)
  9720. end;
  9721. end;
  9722. {$ifdef x86_64}
  9723. end;
  9724. if (taicpu(p).opsize = S_L) and
  9725. (taicpu(p).oper[1]^.typ = top_reg) and
  9726. (
  9727. MatchInstruction(hp1, A_MOV,[]) and
  9728. (taicpu(hp1).opsize = S_L) and
  9729. (taicpu(hp1).oper[1]^.typ = top_reg)
  9730. ) and (
  9731. GetNextInstruction(hp1, hp2) and
  9732. (tai(hp2).typ=ait_instruction) and
  9733. (taicpu(hp2).opsize = S_Q) and
  9734. (
  9735. (
  9736. MatchInstruction(hp2, A_ADD,[]) and
  9737. (taicpu(hp2).opsize = S_Q) and
  9738. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9739. (
  9740. (
  9741. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9742. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9743. ) or (
  9744. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9745. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9746. )
  9747. )
  9748. ) or (
  9749. MatchInstruction(hp2, A_LEA,[]) and
  9750. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9751. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9752. (
  9753. (
  9754. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9755. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9756. ) or (
  9757. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9758. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9759. )
  9760. ) and (
  9761. (
  9762. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9763. ) or (
  9764. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9765. )
  9766. )
  9767. )
  9768. )
  9769. ) and (
  9770. GetNextInstruction(hp2, hp3) and
  9771. MatchInstruction(hp3, A_SHR,[]) and
  9772. (taicpu(hp3).opsize = S_Q) and
  9773. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9774. (taicpu(hp3).oper[0]^.val = 1) and
  9775. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9776. ) then
  9777. begin
  9778. { Change movl x, reg1d movl x, reg1d
  9779. movl y, reg2d movl y, reg2d
  9780. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9781. shrq $1, reg1q shrq $1, reg1q
  9782. ( reg1d and reg2d can be switched around in the first two instructions )
  9783. To movl x, reg1d
  9784. addl y, reg1d
  9785. rcrl $1, reg1d
  9786. This corresponds to the common expression (x + y) shr 1, where
  9787. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9788. smaller code, but won't account for x + y causing an overflow). [Kit]
  9789. }
  9790. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9791. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9792. begin
  9793. { Change first MOV command to have the same register as the final output }
  9794. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9795. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9796. Result := True;
  9797. end
  9798. else
  9799. begin
  9800. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9801. Include(OptsToCheck, aoc_ForceNewIteration);
  9802. end;
  9803. { Change second MOV command to an ADD command. This is easier than
  9804. converting the existing command because it means we don't have to
  9805. touch 'y', which might be a complicated reference, and also the
  9806. fact that the third command might either be ADD or LEA. [Kit] }
  9807. taicpu(hp1).opcode := A_ADD;
  9808. { Delete old ADD/LEA instruction }
  9809. RemoveInstruction(hp2);
  9810. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9811. taicpu(hp3).opcode := A_RCR;
  9812. taicpu(hp3).changeopsize(S_L);
  9813. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9814. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9815. called, so FuncMov2Func below is safe to call }
  9816. {$endif x86_64}
  9817. end;
  9818. if FuncMov2Func(p, hp1) then
  9819. begin
  9820. Result := True;
  9821. Exit;
  9822. end;
  9823. end;
  9824. {$push}
  9825. {$q-}{$r-}
  9826. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9827. var
  9828. ThisReg: TRegister;
  9829. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9830. TargetSubReg: TSubRegister;
  9831. hp1, hp2: tai;
  9832. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9833. { Store list of found instructions so we don't have to call
  9834. GetNextInstructionUsingReg multiple times }
  9835. InstrList: array of taicpu;
  9836. InstrMax, Index: Integer;
  9837. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9838. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9839. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9840. WorkingValue: TCgInt;
  9841. PreMessage: string;
  9842. { Data flow analysis }
  9843. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9844. BitwiseOnly, OrXorUsed,
  9845. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9846. function CheckOverflowConditions: Boolean;
  9847. begin
  9848. Result := True;
  9849. if (TestValSignedMax > SignedUpperLimit) then
  9850. UpperSignedOverflow := True;
  9851. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9852. LowerSignedOverflow := True;
  9853. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9854. LowerUnsignedOverflow := True;
  9855. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9856. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9857. begin
  9858. { Absolute overflow }
  9859. Result := False;
  9860. Exit;
  9861. end;
  9862. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9863. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9864. ShiftDownOverflow := True;
  9865. if (TestValMin < 0) or (TestValMax < 0) then
  9866. begin
  9867. LowerUnsignedOverflow := True;
  9868. UpperUnsignedOverflow := True;
  9869. end;
  9870. end;
  9871. function AdjustInitialLoadAndSize: Boolean;
  9872. begin
  9873. Result := False;
  9874. if not p_removed then
  9875. begin
  9876. if TargetSize = MinSize then
  9877. begin
  9878. { Convert the input MOVZX to a MOV }
  9879. if (taicpu(p).oper[0]^.typ = top_reg) and
  9880. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9881. begin
  9882. { Or remove it completely! }
  9883. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9884. RemoveCurrentP(p);
  9885. p_removed := True;
  9886. end
  9887. else
  9888. begin
  9889. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9890. taicpu(p).opcode := A_MOV;
  9891. taicpu(p).oper[1]^.reg := ThisReg;
  9892. taicpu(p).opsize := TargetSize;
  9893. end;
  9894. Result := True;
  9895. end
  9896. else if TargetSize <> MaxSize then
  9897. begin
  9898. case MaxSize of
  9899. S_L:
  9900. if TargetSize = S_W then
  9901. begin
  9902. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9903. taicpu(p).opsize := S_BW;
  9904. taicpu(p).oper[1]^.reg := ThisReg;
  9905. Result := True;
  9906. end
  9907. else
  9908. InternalError(2020112341);
  9909. S_W:
  9910. if TargetSize = S_L then
  9911. begin
  9912. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9913. taicpu(p).opsize := S_BL;
  9914. taicpu(p).oper[1]^.reg := ThisReg;
  9915. Result := True;
  9916. end
  9917. else
  9918. InternalError(2020112342);
  9919. else
  9920. ;
  9921. end;
  9922. end
  9923. else if not hp1_removed and not RegInUse then
  9924. begin
  9925. { If we have something like:
  9926. movzbl (oper),%regd
  9927. add x, %regd
  9928. movzbl %regb, %regd
  9929. We can reduce the register size to the input of the final
  9930. movzbl instruction. Overflows won't have any effect.
  9931. }
  9932. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9933. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9934. begin
  9935. TargetSize := S_B;
  9936. setsubreg(ThisReg, R_SUBL);
  9937. Result := True;
  9938. end
  9939. else if (taicpu(p).opsize = S_WL) and
  9940. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9941. begin
  9942. TargetSize := S_W;
  9943. setsubreg(ThisReg, R_SUBW);
  9944. Result := True;
  9945. end;
  9946. if Result then
  9947. begin
  9948. { Convert the input MOVZX to a MOV }
  9949. if (taicpu(p).oper[0]^.typ = top_reg) and
  9950. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9951. begin
  9952. { Or remove it completely! }
  9953. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9954. RemoveCurrentP(p);
  9955. p_removed := True;
  9956. end
  9957. else
  9958. begin
  9959. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9960. taicpu(p).opcode := A_MOV;
  9961. taicpu(p).oper[1]^.reg := ThisReg;
  9962. taicpu(p).opsize := TargetSize;
  9963. end;
  9964. end;
  9965. end;
  9966. end;
  9967. end;
  9968. procedure AdjustFinalLoad;
  9969. begin
  9970. if not LowerUnsignedOverflow then
  9971. begin
  9972. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9973. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9974. begin
  9975. { Convert the output MOVZX to a MOV }
  9976. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9977. begin
  9978. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9979. if (MinSize = S_B) or
  9980. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9981. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9982. begin
  9983. { Remove it completely! }
  9984. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9985. { Be careful; if p = hp1 and p was also removed, p
  9986. will become a dangling pointer }
  9987. if p = hp1 then
  9988. begin
  9989. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9990. p_removed := True;
  9991. end
  9992. else
  9993. RemoveInstruction(hp1);
  9994. hp1_removed := True;
  9995. end;
  9996. end
  9997. else
  9998. begin
  9999. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10000. taicpu(hp1).opcode := A_MOV;
  10001. taicpu(hp1).oper[0]^.reg := ThisReg;
  10002. taicpu(hp1).opsize := TargetSize;
  10003. end;
  10004. end
  10005. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10006. begin
  10007. { Need to change the size of the output }
  10008. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10009. taicpu(hp1).oper[0]^.reg := ThisReg;
  10010. taicpu(hp1).opsize := S_BL;
  10011. end;
  10012. end;
  10013. end;
  10014. function CompressInstructions: Boolean;
  10015. var
  10016. LocalIndex: Integer;
  10017. begin
  10018. Result := False;
  10019. { The objective here is to try to find a combination that
  10020. removes one of the MOV/Z instructions. }
  10021. if (
  10022. (taicpu(p).oper[0]^.typ <> top_reg) or
  10023. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10024. ) and
  10025. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10026. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10027. begin
  10028. { Make a preference to remove the second MOVZX instruction }
  10029. case taicpu(hp1).opsize of
  10030. S_BL, S_WL:
  10031. begin
  10032. TargetSize := S_L;
  10033. TargetSubReg := R_SUBD;
  10034. end;
  10035. S_BW:
  10036. begin
  10037. TargetSize := S_W;
  10038. TargetSubReg := R_SUBW;
  10039. end;
  10040. else
  10041. InternalError(2020112302);
  10042. end;
  10043. end
  10044. else
  10045. begin
  10046. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10047. begin
  10048. { Exceeded lower bound but not upper bound }
  10049. TargetSize := MaxSize;
  10050. end
  10051. else if not LowerUnsignedOverflow then
  10052. begin
  10053. { Size didn't exceed lower bound }
  10054. TargetSize := MinSize;
  10055. end
  10056. else
  10057. Exit;
  10058. end;
  10059. case TargetSize of
  10060. S_B:
  10061. TargetSubReg := R_SUBL;
  10062. S_W:
  10063. TargetSubReg := R_SUBW;
  10064. S_L:
  10065. TargetSubReg := R_SUBD;
  10066. else
  10067. InternalError(2020112350);
  10068. end;
  10069. { Update the register to its new size }
  10070. setsubreg(ThisReg, TargetSubReg);
  10071. RegInUse := False;
  10072. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10073. begin
  10074. { Check to see if the active register is used afterwards;
  10075. if not, we can change it and make a saving. }
  10076. TransferUsedRegs(TmpUsedRegs);
  10077. { The target register may be marked as in use to cross
  10078. a jump to a distant label, so exclude it }
  10079. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10080. hp2 := p;
  10081. repeat
  10082. { Explicitly check for the excluded register (don't include the first
  10083. instruction as it may be reading from here }
  10084. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10085. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10086. begin
  10087. RegInUse := True;
  10088. Break;
  10089. end;
  10090. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10091. if not GetNextInstruction(hp2, hp2) then
  10092. InternalError(2020112340);
  10093. until (hp2 = hp1);
  10094. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10095. { We might still be able to get away with this }
  10096. RegInUse := not
  10097. (
  10098. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10099. (hp2.typ = ait_instruction) and
  10100. (
  10101. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10102. instruction that doesn't actually contain ThisReg }
  10103. (cs_opt_level3 in current_settings.optimizerswitches) or
  10104. RegInInstruction(ThisReg, hp2)
  10105. ) and
  10106. RegLoadedWithNewValue(ThisReg, hp2)
  10107. );
  10108. if not RegInUse then
  10109. begin
  10110. { Force the register size to the same as this instruction so it can be removed}
  10111. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10112. begin
  10113. TargetSize := S_L;
  10114. TargetSubReg := R_SUBD;
  10115. end
  10116. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10117. begin
  10118. TargetSize := S_W;
  10119. TargetSubReg := R_SUBW;
  10120. end;
  10121. ThisReg := taicpu(hp1).oper[1]^.reg;
  10122. setsubreg(ThisReg, TargetSubReg);
  10123. RegChanged := True;
  10124. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10125. TransferUsedRegs(TmpUsedRegs);
  10126. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10127. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10128. if p = hp1 then
  10129. begin
  10130. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10131. p_removed := True;
  10132. end
  10133. else
  10134. RemoveInstruction(hp1);
  10135. hp1_removed := True;
  10136. { Instruction will become "mov %reg,%reg" }
  10137. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10138. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10139. begin
  10140. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10141. RemoveCurrentP(p);
  10142. p_removed := True;
  10143. end
  10144. else
  10145. taicpu(p).oper[1]^.reg := ThisReg;
  10146. Result := True;
  10147. end
  10148. else
  10149. begin
  10150. if TargetSize <> MaxSize then
  10151. begin
  10152. { Since the register is in use, we have to force it to
  10153. MaxSize otherwise part of it may become undefined later on }
  10154. TargetSize := MaxSize;
  10155. case TargetSize of
  10156. S_B:
  10157. TargetSubReg := R_SUBL;
  10158. S_W:
  10159. TargetSubReg := R_SUBW;
  10160. S_L:
  10161. TargetSubReg := R_SUBD;
  10162. else
  10163. InternalError(2020112351);
  10164. end;
  10165. setsubreg(ThisReg, TargetSubReg);
  10166. end;
  10167. AdjustFinalLoad;
  10168. end;
  10169. end
  10170. else
  10171. AdjustFinalLoad;
  10172. Result := AdjustInitialLoadAndSize or Result;
  10173. { Now go through every instruction we found and change the
  10174. size. If TargetSize = MaxSize, then almost no changes are
  10175. needed and Result can remain False if it hasn't been set
  10176. yet.
  10177. If RegChanged is True, then the register requires changing
  10178. and so the point about TargetSize = MaxSize doesn't apply. }
  10179. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10180. begin
  10181. for LocalIndex := 0 to InstrMax do
  10182. begin
  10183. { If p_removed is true, then the original MOV/Z was removed
  10184. and removing the AND instruction may not be safe if it
  10185. appears first }
  10186. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10187. InternalError(2020112310);
  10188. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10189. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10190. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10191. InstrList[LocalIndex].opsize := TargetSize;
  10192. end;
  10193. Result := True;
  10194. end;
  10195. end;
  10196. begin
  10197. Result := False;
  10198. p_removed := False;
  10199. hp1_removed := False;
  10200. ThisReg := taicpu(p).oper[1]^.reg;
  10201. { Check for:
  10202. movs/z ###,%ecx (or %cx or %rcx)
  10203. ...
  10204. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10205. (dealloc %ecx)
  10206. Change to:
  10207. mov ###,%cl (if ### = %cl, then remove completely)
  10208. ...
  10209. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10210. }
  10211. if (getsupreg(ThisReg) = RS_ECX) and
  10212. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10213. (hp1.typ = ait_instruction) and
  10214. (
  10215. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10216. instruction that doesn't actually contain ECX }
  10217. (cs_opt_level3 in current_settings.optimizerswitches) or
  10218. RegInInstruction(NR_ECX, hp1) or
  10219. (
  10220. { It's common for the shift/rotate's read/write register to be
  10221. initialised in between, so under -O2 and under, search ahead
  10222. one more instruction
  10223. }
  10224. GetNextInstruction(hp1, hp1) and
  10225. (hp1.typ = ait_instruction) and
  10226. RegInInstruction(NR_ECX, hp1)
  10227. )
  10228. ) and
  10229. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10230. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10231. begin
  10232. TransferUsedRegs(TmpUsedRegs);
  10233. hp2 := p;
  10234. repeat
  10235. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10236. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10237. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10238. begin
  10239. case taicpu(p).opsize of
  10240. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10241. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10242. begin
  10243. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10244. RemoveCurrentP(p);
  10245. end
  10246. else
  10247. begin
  10248. taicpu(p).opcode := A_MOV;
  10249. taicpu(p).opsize := S_B;
  10250. taicpu(p).oper[1]^.reg := NR_CL;
  10251. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10252. end;
  10253. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10254. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10255. begin
  10256. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10257. RemoveCurrentP(p);
  10258. end
  10259. else
  10260. begin
  10261. taicpu(p).opcode := A_MOV;
  10262. taicpu(p).opsize := S_W;
  10263. taicpu(p).oper[1]^.reg := NR_CX;
  10264. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10265. end;
  10266. {$ifdef x86_64}
  10267. S_LQ:
  10268. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10269. begin
  10270. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10271. RemoveCurrentP(p);
  10272. end
  10273. else
  10274. begin
  10275. taicpu(p).opcode := A_MOV;
  10276. taicpu(p).opsize := S_L;
  10277. taicpu(p).oper[1]^.reg := NR_ECX;
  10278. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10279. end;
  10280. {$endif x86_64}
  10281. else
  10282. InternalError(2021120401);
  10283. end;
  10284. Result := True;
  10285. Exit;
  10286. end;
  10287. end;
  10288. { This is anything but quick! }
  10289. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10290. Exit;
  10291. SetLength(InstrList, 0);
  10292. InstrMax := -1;
  10293. case taicpu(p).opsize of
  10294. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10295. begin
  10296. {$if defined(i386) or defined(i8086)}
  10297. { If the target size is 8-bit, make sure we can actually encode it }
  10298. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10299. Exit;
  10300. {$endif i386 or i8086}
  10301. LowerLimit := $FF;
  10302. SignedLowerLimit := $7F;
  10303. SignedLowerLimitBottom := -128;
  10304. MinSize := S_B;
  10305. if taicpu(p).opsize = S_BW then
  10306. begin
  10307. MaxSize := S_W;
  10308. UpperLimit := $FFFF;
  10309. SignedUpperLimit := $7FFF;
  10310. SignedUpperLimitBottom := -32768;
  10311. end
  10312. else
  10313. begin
  10314. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10315. MaxSize := S_L;
  10316. UpperLimit := $FFFFFFFF;
  10317. SignedUpperLimit := $7FFFFFFF;
  10318. SignedUpperLimitBottom := -2147483648;
  10319. end;
  10320. end;
  10321. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10322. begin
  10323. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10324. LowerLimit := $FFFF;
  10325. SignedLowerLimit := $7FFF;
  10326. SignedLowerLimitBottom := -32768;
  10327. UpperLimit := $FFFFFFFF;
  10328. SignedUpperLimit := $7FFFFFFF;
  10329. SignedUpperLimitBottom := -2147483648;
  10330. MinSize := S_W;
  10331. MaxSize := S_L;
  10332. end;
  10333. {$ifdef x86_64}
  10334. S_LQ:
  10335. begin
  10336. { Both the lower and upper limits are set to 32-bit. If a limit
  10337. is breached, then optimisation is impossible }
  10338. LowerLimit := $FFFFFFFF;
  10339. SignedLowerLimit := $7FFFFFFF;
  10340. SignedLowerLimitBottom := -2147483648;
  10341. UpperLimit := $FFFFFFFF;
  10342. SignedUpperLimit := $7FFFFFFF;
  10343. SignedUpperLimitBottom := -2147483648;
  10344. MinSize := S_L;
  10345. MaxSize := S_L;
  10346. end;
  10347. {$endif x86_64}
  10348. else
  10349. InternalError(2020112301);
  10350. end;
  10351. TestValMin := 0;
  10352. TestValMax := LowerLimit;
  10353. TestValSignedMax := SignedLowerLimit;
  10354. TryShiftDownLimit := LowerLimit;
  10355. TryShiftDown := S_NO;
  10356. ShiftDownOverflow := False;
  10357. RegChanged := False;
  10358. BitwiseOnly := True;
  10359. OrXorUsed := False;
  10360. UpperSignedOverflow := False;
  10361. LowerSignedOverflow := False;
  10362. UpperUnsignedOverflow := False;
  10363. LowerUnsignedOverflow := False;
  10364. hp1 := p;
  10365. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10366. (hp1.typ = ait_instruction) and
  10367. (
  10368. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10369. instruction that doesn't actually contain ThisReg }
  10370. (cs_opt_level3 in current_settings.optimizerswitches) or
  10371. { This allows this Movx optimisation to work through the SETcc instructions
  10372. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10373. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10374. skip over these SETcc instructions). }
  10375. (taicpu(hp1).opcode = A_SETcc) or
  10376. RegInInstruction(ThisReg, hp1)
  10377. ) do
  10378. begin
  10379. case taicpu(hp1).opcode of
  10380. A_INC,A_DEC:
  10381. begin
  10382. { Has to be an exact match on the register }
  10383. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10384. Break;
  10385. if taicpu(hp1).opcode = A_INC then
  10386. begin
  10387. Inc(TestValMin);
  10388. Inc(TestValMax);
  10389. Inc(TestValSignedMax);
  10390. end
  10391. else
  10392. begin
  10393. Dec(TestValMin);
  10394. Dec(TestValMax);
  10395. Dec(TestValSignedMax);
  10396. end;
  10397. end;
  10398. A_TEST, A_CMP:
  10399. begin
  10400. if (
  10401. { Too high a risk of non-linear behaviour that breaks DFA
  10402. here, unless it's cmp $0,%reg, which is equivalent to
  10403. test %reg,%reg }
  10404. OrXorUsed and
  10405. (taicpu(hp1).opcode = A_CMP) and
  10406. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10407. ) or
  10408. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10409. { Has to be an exact match on the register }
  10410. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10411. (
  10412. { Permit "test %reg,%reg" }
  10413. (taicpu(hp1).opcode = A_TEST) and
  10414. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10415. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10416. ) or
  10417. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10418. { Make sure the comparison value is not smaller than the
  10419. smallest allowed signed value for the minimum size (e.g.
  10420. -128 for 8-bit) }
  10421. not (
  10422. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10423. { Is it in the negative range? }
  10424. (
  10425. (taicpu(hp1).oper[0]^.val < 0) and
  10426. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10427. )
  10428. ) then
  10429. Break;
  10430. { Check to see if the active register is used afterwards }
  10431. TransferUsedRegs(TmpUsedRegs);
  10432. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10433. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10434. begin
  10435. { Make sure the comparison or any previous instructions
  10436. hasn't pushed the test values outside of the range of
  10437. MinSize }
  10438. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10439. begin
  10440. { Exceeded lower bound but not upper bound }
  10441. Exit;
  10442. end
  10443. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10444. begin
  10445. { Size didn't exceed lower bound }
  10446. TargetSize := MinSize;
  10447. end
  10448. else
  10449. Break;
  10450. case TargetSize of
  10451. S_B:
  10452. TargetSubReg := R_SUBL;
  10453. S_W:
  10454. TargetSubReg := R_SUBW;
  10455. S_L:
  10456. TargetSubReg := R_SUBD;
  10457. else
  10458. InternalError(2021051002);
  10459. end;
  10460. if TargetSize <> MaxSize then
  10461. begin
  10462. { Update the register to its new size }
  10463. setsubreg(ThisReg, TargetSubReg);
  10464. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10465. taicpu(hp1).oper[1]^.reg := ThisReg;
  10466. taicpu(hp1).opsize := TargetSize;
  10467. { Convert the input MOVZX to a MOV if necessary }
  10468. AdjustInitialLoadAndSize;
  10469. if (InstrMax >= 0) then
  10470. begin
  10471. for Index := 0 to InstrMax do
  10472. begin
  10473. { If p_removed is true, then the original MOV/Z was removed
  10474. and removing the AND instruction may not be safe if it
  10475. appears first }
  10476. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10477. InternalError(2020112311);
  10478. if InstrList[Index].oper[0]^.typ = top_reg then
  10479. InstrList[Index].oper[0]^.reg := ThisReg;
  10480. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10481. InstrList[Index].opsize := MinSize;
  10482. end;
  10483. end;
  10484. Result := True;
  10485. end;
  10486. Exit;
  10487. end;
  10488. end;
  10489. A_SETcc:
  10490. begin
  10491. { This allows this Movx optimisation to work through the SETcc instructions
  10492. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10493. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10494. skip over these SETcc instructions). }
  10495. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10496. { Of course, break out if the current register is used }
  10497. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10498. Break
  10499. else
  10500. { We must use Continue so the instruction doesn't get added
  10501. to InstrList }
  10502. Continue;
  10503. end;
  10504. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10505. begin
  10506. if
  10507. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10508. { Has to be an exact match on the register }
  10509. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10510. (
  10511. (
  10512. (taicpu(hp1).oper[0]^.typ = top_const) and
  10513. (
  10514. (
  10515. (taicpu(hp1).opcode = A_SHL) and
  10516. (
  10517. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10518. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10519. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10520. )
  10521. ) or (
  10522. (taicpu(hp1).opcode <> A_SHL) and
  10523. (
  10524. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10525. { Is it in the negative range? }
  10526. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10527. )
  10528. )
  10529. )
  10530. ) or (
  10531. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10532. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10533. )
  10534. ) then
  10535. Break;
  10536. { Only process OR and XOR if there are only bitwise operations,
  10537. since otherwise they can too easily fool the data flow
  10538. analysis (they can cause non-linear behaviour) }
  10539. case taicpu(hp1).opcode of
  10540. A_ADD:
  10541. begin
  10542. if OrXorUsed then
  10543. { Too high a risk of non-linear behaviour that breaks DFA here }
  10544. Break
  10545. else
  10546. BitwiseOnly := False;
  10547. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10548. begin
  10549. TestValMin := TestValMin * 2;
  10550. TestValMax := TestValMax * 2;
  10551. TestValSignedMax := TestValSignedMax * 2;
  10552. end
  10553. else
  10554. begin
  10555. WorkingValue := taicpu(hp1).oper[0]^.val;
  10556. TestValMin := TestValMin + WorkingValue;
  10557. TestValMax := TestValMax + WorkingValue;
  10558. TestValSignedMax := TestValSignedMax + WorkingValue;
  10559. end;
  10560. end;
  10561. A_SUB:
  10562. begin
  10563. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10564. begin
  10565. TestValMin := 0;
  10566. TestValMax := 0;
  10567. TestValSignedMax := 0;
  10568. end
  10569. else
  10570. begin
  10571. if OrXorUsed then
  10572. { Too high a risk of non-linear behaviour that breaks DFA here }
  10573. Break
  10574. else
  10575. BitwiseOnly := False;
  10576. WorkingValue := taicpu(hp1).oper[0]^.val;
  10577. TestValMin := TestValMin - WorkingValue;
  10578. TestValMax := TestValMax - WorkingValue;
  10579. TestValSignedMax := TestValSignedMax - WorkingValue;
  10580. end;
  10581. end;
  10582. A_AND:
  10583. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10584. begin
  10585. { we might be able to go smaller if AND appears first }
  10586. if InstrMax = -1 then
  10587. case MinSize of
  10588. S_B:
  10589. ;
  10590. S_W:
  10591. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10592. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10593. begin
  10594. TryShiftDown := S_B;
  10595. TryShiftDownLimit := $FF;
  10596. end;
  10597. S_L:
  10598. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10599. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10600. begin
  10601. TryShiftDown := S_B;
  10602. TryShiftDownLimit := $FF;
  10603. end
  10604. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10605. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10606. begin
  10607. TryShiftDown := S_W;
  10608. TryShiftDownLimit := $FFFF;
  10609. end;
  10610. else
  10611. InternalError(2020112320);
  10612. end;
  10613. WorkingValue := taicpu(hp1).oper[0]^.val;
  10614. TestValMin := TestValMin and WorkingValue;
  10615. TestValMax := TestValMax and WorkingValue;
  10616. TestValSignedMax := TestValSignedMax and WorkingValue;
  10617. end;
  10618. A_OR:
  10619. begin
  10620. if not BitwiseOnly then
  10621. Break;
  10622. OrXorUsed := True;
  10623. WorkingValue := taicpu(hp1).oper[0]^.val;
  10624. TestValMin := TestValMin or WorkingValue;
  10625. TestValMax := TestValMax or WorkingValue;
  10626. TestValSignedMax := TestValSignedMax or WorkingValue;
  10627. end;
  10628. A_XOR:
  10629. begin
  10630. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10631. begin
  10632. TestValMin := 0;
  10633. TestValMax := 0;
  10634. TestValSignedMax := 0;
  10635. end
  10636. else
  10637. begin
  10638. if not BitwiseOnly then
  10639. Break;
  10640. OrXorUsed := True;
  10641. WorkingValue := taicpu(hp1).oper[0]^.val;
  10642. TestValMin := TestValMin xor WorkingValue;
  10643. TestValMax := TestValMax xor WorkingValue;
  10644. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10645. end;
  10646. end;
  10647. A_SHL:
  10648. begin
  10649. BitwiseOnly := False;
  10650. WorkingValue := taicpu(hp1).oper[0]^.val;
  10651. TestValMin := TestValMin shl WorkingValue;
  10652. TestValMax := TestValMax shl WorkingValue;
  10653. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10654. end;
  10655. A_SHR,
  10656. { The first instruction was MOVZX, so the value won't be negative }
  10657. A_SAR:
  10658. begin
  10659. if InstrMax <> -1 then
  10660. BitwiseOnly := False
  10661. else
  10662. { we might be able to go smaller if SHR appears first }
  10663. case MinSize of
  10664. S_B:
  10665. ;
  10666. S_W:
  10667. if (taicpu(hp1).oper[0]^.val >= 8) then
  10668. begin
  10669. TryShiftDown := S_B;
  10670. TryShiftDownLimit := $FF;
  10671. TryShiftDownSignedLimit := $7F;
  10672. TryShiftDownSignedLimitLower := -128;
  10673. end;
  10674. S_L:
  10675. if (taicpu(hp1).oper[0]^.val >= 24) then
  10676. begin
  10677. TryShiftDown := S_B;
  10678. TryShiftDownLimit := $FF;
  10679. TryShiftDownSignedLimit := $7F;
  10680. TryShiftDownSignedLimitLower := -128;
  10681. end
  10682. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10683. begin
  10684. TryShiftDown := S_W;
  10685. TryShiftDownLimit := $FFFF;
  10686. TryShiftDownSignedLimit := $7FFF;
  10687. TryShiftDownSignedLimitLower := -32768;
  10688. end;
  10689. else
  10690. InternalError(2020112321);
  10691. end;
  10692. WorkingValue := taicpu(hp1).oper[0]^.val;
  10693. if taicpu(hp1).opcode = A_SAR then
  10694. begin
  10695. TestValMin := SarInt64(TestValMin, WorkingValue);
  10696. TestValMax := SarInt64(TestValMax, WorkingValue);
  10697. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10698. end
  10699. else
  10700. begin
  10701. TestValMin := TestValMin shr WorkingValue;
  10702. TestValMax := TestValMax shr WorkingValue;
  10703. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10704. end;
  10705. end;
  10706. else
  10707. InternalError(2020112303);
  10708. end;
  10709. end;
  10710. (*
  10711. A_IMUL:
  10712. case taicpu(hp1).ops of
  10713. 2:
  10714. begin
  10715. if not MatchOpType(hp1, top_reg, top_reg) or
  10716. { Has to be an exact match on the register }
  10717. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10718. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10719. Break;
  10720. TestValMin := TestValMin * TestValMin;
  10721. TestValMax := TestValMax * TestValMax;
  10722. TestValSignedMax := TestValSignedMax * TestValMax;
  10723. end;
  10724. 3:
  10725. begin
  10726. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10727. { Has to be an exact match on the register }
  10728. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10729. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10730. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10731. { Is it in the negative range? }
  10732. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10733. Break;
  10734. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10735. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10736. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10737. end;
  10738. else
  10739. Break;
  10740. end;
  10741. A_IDIV:
  10742. case taicpu(hp1).ops of
  10743. 3:
  10744. begin
  10745. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10746. { Has to be an exact match on the register }
  10747. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10748. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10749. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10750. { Is it in the negative range? }
  10751. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10752. Break;
  10753. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10754. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10755. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10756. end;
  10757. else
  10758. Break;
  10759. end;
  10760. *)
  10761. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10762. begin
  10763. { If there are no instructions in between, then we might be able to make a saving }
  10764. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10765. Break;
  10766. { We have something like:
  10767. movzbw %dl,%dx
  10768. ...
  10769. movswl %dx,%edx
  10770. Change the latter to a zero-extension then enter the
  10771. A_MOVZX case branch.
  10772. }
  10773. {$ifdef x86_64}
  10774. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10775. begin
  10776. { this becomes a zero extension from 32-bit to 64-bit, but
  10777. the upper 32 bits are already zero, so just delete the
  10778. instruction }
  10779. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10780. RemoveInstruction(hp1);
  10781. Result := True;
  10782. Exit;
  10783. end
  10784. else
  10785. {$endif x86_64}
  10786. begin
  10787. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10788. taicpu(hp1).opcode := A_MOVZX;
  10789. {$ifdef x86_64}
  10790. case taicpu(hp1).opsize of
  10791. S_BQ:
  10792. begin
  10793. taicpu(hp1).opsize := S_BL;
  10794. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10795. end;
  10796. S_WQ:
  10797. begin
  10798. taicpu(hp1).opsize := S_WL;
  10799. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10800. end;
  10801. S_LQ:
  10802. begin
  10803. taicpu(hp1).opcode := A_MOV;
  10804. taicpu(hp1).opsize := S_L;
  10805. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10806. { In this instance, we need to break out because the
  10807. instruction is no longer MOVZX or MOVSXD }
  10808. Result := True;
  10809. Exit;
  10810. end;
  10811. else
  10812. ;
  10813. end;
  10814. {$endif x86_64}
  10815. Result := CompressInstructions;
  10816. Exit;
  10817. end;
  10818. end;
  10819. A_MOVZX:
  10820. begin
  10821. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10822. Break;
  10823. if (InstrMax = -1) then
  10824. begin
  10825. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10826. begin
  10827. { Optimise around i40003 }
  10828. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10829. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10830. {$ifndef x86_64}
  10831. and (
  10832. (taicpu(p).oper[0]^.typ <> top_reg) or
  10833. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10834. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10835. )
  10836. {$endif not x86_64}
  10837. then
  10838. begin
  10839. if (taicpu(p).oper[0]^.typ = top_reg) then
  10840. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10841. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10842. taicpu(p).opsize := S_BL;
  10843. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10844. RemoveInstruction(hp1);
  10845. Result := True;
  10846. Exit;
  10847. end;
  10848. end
  10849. else
  10850. begin
  10851. { Will return false if the second parameter isn't ThisReg
  10852. (can happen on -O2 and under) }
  10853. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10854. begin
  10855. { The two MOVZX instructions are adjacent, so remove the first one }
  10856. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10857. RemoveCurrentP(p);
  10858. Result := True;
  10859. Exit;
  10860. end;
  10861. Break;
  10862. end;
  10863. end;
  10864. Result := CompressInstructions;
  10865. Exit;
  10866. end;
  10867. else
  10868. { This includes ADC, SBB and IDIV }
  10869. Break;
  10870. end;
  10871. if not CheckOverflowConditions then
  10872. Break;
  10873. { Contains highest index (so instruction count - 1) }
  10874. Inc(InstrMax);
  10875. if InstrMax > High(InstrList) then
  10876. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10877. InstrList[InstrMax] := taicpu(hp1);
  10878. end;
  10879. end;
  10880. {$pop}
  10881. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10882. var
  10883. hp1 : tai;
  10884. begin
  10885. Result:=false;
  10886. if (taicpu(p).ops >= 2) and
  10887. ((taicpu(p).oper[0]^.typ = top_const) or
  10888. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10889. (taicpu(p).oper[1]^.typ = top_reg) and
  10890. ((taicpu(p).ops = 2) or
  10891. ((taicpu(p).oper[2]^.typ = top_reg) and
  10892. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10893. GetLastInstruction(p,hp1) and
  10894. MatchInstruction(hp1,A_MOV,[]) and
  10895. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10896. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10897. begin
  10898. TransferUsedRegs(TmpUsedRegs);
  10899. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10900. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10901. { change
  10902. mov reg1,reg2
  10903. imul y,reg2 to imul y,reg1,reg2 }
  10904. begin
  10905. taicpu(p).ops := 3;
  10906. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10907. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10908. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10909. RemoveInstruction(hp1);
  10910. result:=true;
  10911. end;
  10912. end;
  10913. end;
  10914. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10915. var
  10916. ThisLabel: TAsmLabel;
  10917. begin
  10918. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10919. ThisLabel.decrefs;
  10920. taicpu(p).condition := C_None;
  10921. taicpu(p).opcode := A_RET;
  10922. taicpu(p).is_jmp := false;
  10923. taicpu(p).ops := taicpu(ret_p).ops;
  10924. case taicpu(ret_p).ops of
  10925. 0:
  10926. taicpu(p).clearop(0);
  10927. 1:
  10928. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10929. else
  10930. internalerror(2016041301);
  10931. end;
  10932. { If the original label is now dead, it might turn out that the label
  10933. immediately follows p. As a result, everything beyond it, which will
  10934. be just some final register configuration and a RET instruction, is
  10935. now dead code. [Kit] }
  10936. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10937. running RemoveDeadCodeAfterJump for each RET instruction, because
  10938. this optimisation rarely happens and most RETs appear at the end of
  10939. routines where there is nothing that can be stripped. [Kit] }
  10940. if not ThisLabel.is_used then
  10941. RemoveDeadCodeAfterJump(p);
  10942. end;
  10943. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10944. var
  10945. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10946. Unconditional, PotentialModified: Boolean;
  10947. OperPtr: POper;
  10948. NewRef: TReference;
  10949. InstrList: array of taicpu;
  10950. InstrMax, Index: Integer;
  10951. const
  10952. {$ifdef DEBUG_AOPTCPU}
  10953. SNoFlags: shortstring = ' so the flags aren''t modified';
  10954. {$else DEBUG_AOPTCPU}
  10955. SNoFlags = '';
  10956. {$endif DEBUG_AOPTCPU}
  10957. begin
  10958. Result:=false;
  10959. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10960. begin
  10961. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10962. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10963. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10964. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10965. GetNextInstruction(hp1, hp2) and
  10966. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10967. { Change from: To:
  10968. set(C) %reg j(~C) label
  10969. test %reg,%reg/cmp $0,%reg
  10970. je label
  10971. set(C) %reg j(C) label
  10972. test %reg,%reg/cmp $0,%reg
  10973. jne label
  10974. (Also do something similar with sete/setne instead of je/jne)
  10975. }
  10976. begin
  10977. { Before we do anything else, we need to check the instructions
  10978. in between SETcc and TEST to make sure they don't modify the
  10979. FLAGS register - if -O2 or under, there won't be any
  10980. instructions between SET and TEST }
  10981. TransferUsedRegs(TmpUsedRegs);
  10982. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10983. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10984. begin
  10985. next := p;
  10986. SetLength(InstrList, 0);
  10987. InstrMax := -1;
  10988. PotentialModified := False;
  10989. { Make a note of every instruction that modifies the FLAGS
  10990. register }
  10991. while GetNextInstruction(next, next) and (next <> hp1) do
  10992. begin
  10993. if next.typ <> ait_instruction then
  10994. { GetNextInstructionUsingReg should have returned False }
  10995. InternalError(2021051701);
  10996. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10997. begin
  10998. case taicpu(next).opcode of
  10999. A_SETcc,
  11000. A_CMOVcc,
  11001. A_Jcc:
  11002. begin
  11003. if PotentialModified then
  11004. { Not safe because the flags were modified earlier }
  11005. Exit
  11006. else
  11007. { Condition is the same as the initial SETcc, so this is safe
  11008. (don't add to instruction list though) }
  11009. Continue;
  11010. end;
  11011. A_ADD:
  11012. begin
  11013. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11014. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11015. (taicpu(next).oper[1]^.typ <> top_reg) or
  11016. { Must write to a register }
  11017. (taicpu(next).oper[0]^.typ = top_ref) then
  11018. { Require a constant or a register }
  11019. Exit;
  11020. PotentialModified := True;
  11021. end;
  11022. A_SUB:
  11023. begin
  11024. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11025. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11026. (taicpu(next).oper[1]^.typ <> top_reg) or
  11027. { Must write to a register }
  11028. (taicpu(next).oper[0]^.typ <> top_const) or
  11029. (taicpu(next).oper[0]^.val = $80000000) then
  11030. { Can't subtract a register with LEA - also
  11031. check that the value isn't -2^31, as this
  11032. can't be negated }
  11033. Exit;
  11034. PotentialModified := True;
  11035. end;
  11036. A_SAL,
  11037. A_SHL:
  11038. begin
  11039. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11040. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11041. (taicpu(next).oper[1]^.typ <> top_reg) or
  11042. { Must write to a register }
  11043. (taicpu(next).oper[0]^.typ <> top_const) or
  11044. (taicpu(next).oper[0]^.val < 0) or
  11045. (taicpu(next).oper[0]^.val > 3) then
  11046. Exit;
  11047. PotentialModified := True;
  11048. end;
  11049. A_IMUL:
  11050. begin
  11051. if (taicpu(next).ops <> 3) or
  11052. (taicpu(next).oper[1]^.typ <> top_reg) or
  11053. { Must write to a register }
  11054. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11055. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11056. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11057. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11058. Exit
  11059. else
  11060. PotentialModified := True;
  11061. end;
  11062. else
  11063. { Don't know how to change this, so abort }
  11064. Exit;
  11065. end;
  11066. { Contains highest index (so instruction count - 1) }
  11067. Inc(InstrMax);
  11068. if InstrMax > High(InstrList) then
  11069. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11070. InstrList[InstrMax] := taicpu(next);
  11071. end;
  11072. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11073. end;
  11074. if not Assigned(next) or (next <> hp1) then
  11075. { It should be equal to hp1 }
  11076. InternalError(2021051702);
  11077. { Cycle through each instruction and check to see if we can
  11078. change them to versions that don't modify the flags }
  11079. if (InstrMax >= 0) then
  11080. begin
  11081. for Index := 0 to InstrMax do
  11082. case InstrList[Index].opcode of
  11083. A_ADD:
  11084. begin
  11085. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11086. InstrList[Index].opcode := A_LEA;
  11087. reference_reset(NewRef, 1, []);
  11088. NewRef.base := InstrList[Index].oper[1]^.reg;
  11089. if InstrList[Index].oper[0]^.typ = top_reg then
  11090. begin
  11091. NewRef.index := InstrList[Index].oper[0]^.reg;
  11092. NewRef.scalefactor := 1;
  11093. end
  11094. else
  11095. NewRef.offset := InstrList[Index].oper[0]^.val;
  11096. InstrList[Index].loadref(0, NewRef);
  11097. end;
  11098. A_SUB:
  11099. begin
  11100. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11101. InstrList[Index].opcode := A_LEA;
  11102. reference_reset(NewRef, 1, []);
  11103. NewRef.base := InstrList[Index].oper[1]^.reg;
  11104. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11105. InstrList[Index].loadref(0, NewRef);
  11106. end;
  11107. A_SHL,
  11108. A_SAL:
  11109. begin
  11110. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11111. InstrList[Index].opcode := A_LEA;
  11112. reference_reset(NewRef, 1, []);
  11113. NewRef.index := InstrList[Index].oper[1]^.reg;
  11114. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11115. InstrList[Index].loadref(0, NewRef);
  11116. end;
  11117. A_IMUL:
  11118. begin
  11119. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11120. InstrList[Index].opcode := A_LEA;
  11121. reference_reset(NewRef, 1, []);
  11122. NewRef.index := InstrList[Index].oper[1]^.reg;
  11123. case InstrList[Index].oper[0]^.val of
  11124. 2, 4, 8:
  11125. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11126. else {3, 5 and 9}
  11127. begin
  11128. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11129. NewRef.base := InstrList[Index].oper[1]^.reg;
  11130. end;
  11131. end;
  11132. InstrList[Index].loadref(0, NewRef);
  11133. end;
  11134. else
  11135. InternalError(2021051710);
  11136. end;
  11137. end;
  11138. { Mark the FLAGS register as used across this whole block }
  11139. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11140. end;
  11141. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11142. JumpC := taicpu(hp2).condition;
  11143. Unconditional := False;
  11144. if conditions_equal(JumpC, C_E) then
  11145. SetC := inverse_cond(taicpu(p).condition)
  11146. else if conditions_equal(JumpC, C_NE) then
  11147. SetC := taicpu(p).condition
  11148. else
  11149. { We've got something weird here (and inefficent) }
  11150. begin
  11151. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11152. SetC := C_NONE;
  11153. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11154. if condition_in(C_AE, JumpC) then
  11155. Unconditional := True
  11156. else
  11157. { Not sure what to do with this jump - drop out }
  11158. Exit;
  11159. end;
  11160. RemoveInstruction(hp1);
  11161. if Unconditional then
  11162. MakeUnconditional(taicpu(hp2))
  11163. else
  11164. begin
  11165. if SetC = C_NONE then
  11166. InternalError(2018061402);
  11167. taicpu(hp2).SetCondition(SetC);
  11168. end;
  11169. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11170. TmpUsedRegs }
  11171. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11172. begin
  11173. RemoveCurrentp(p, hp2);
  11174. if taicpu(hp2).opcode = A_SETcc then
  11175. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11176. else
  11177. begin
  11178. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11179. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11180. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11181. end;
  11182. end
  11183. else
  11184. if taicpu(hp2).opcode = A_SETcc then
  11185. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11186. else
  11187. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11188. Result := True;
  11189. end
  11190. else if
  11191. { Make sure the instructions are adjacent }
  11192. (
  11193. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11194. GetNextInstruction(p, hp1)
  11195. ) and
  11196. MatchInstruction(hp1, A_MOV, [S_B]) and
  11197. { Writing to memory is allowed }
  11198. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11199. begin
  11200. {
  11201. Watch out for sequences such as:
  11202. set(c)b %regb
  11203. movb %regb,(ref)
  11204. movb $0,1(ref)
  11205. movb $0,2(ref)
  11206. movb $0,3(ref)
  11207. Much more efficient to turn it into:
  11208. movl $0,%regl
  11209. set(c)b %regb
  11210. movl %regl,(ref)
  11211. Or:
  11212. set(c)b %regb
  11213. movzbl %regb,%regl
  11214. movl %regl,(ref)
  11215. }
  11216. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11217. GetNextInstruction(hp1, hp2) and
  11218. MatchInstruction(hp2, A_MOV, [S_B]) and
  11219. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11220. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11221. begin
  11222. { Don't do anything else except set Result to True }
  11223. end
  11224. else
  11225. begin
  11226. if taicpu(p).oper[0]^.typ = top_reg then
  11227. begin
  11228. TransferUsedRegs(TmpUsedRegs);
  11229. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11230. end;
  11231. { If it's not a register, it's a memory address }
  11232. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11233. begin
  11234. { Even if the register is still in use, we can minimise the
  11235. pipeline stall by changing the MOV into another SETcc. }
  11236. taicpu(hp1).opcode := A_SETcc;
  11237. taicpu(hp1).condition := taicpu(p).condition;
  11238. if taicpu(hp1).oper[1]^.typ = top_ref then
  11239. begin
  11240. { Swapping the operand pointers like this is probably a
  11241. bit naughty, but it is far faster than using loadoper
  11242. to transfer the reference from oper[1] to oper[0] if
  11243. you take into account the extra procedure calls and
  11244. the memory allocation and deallocation required }
  11245. OperPtr := taicpu(hp1).oper[1];
  11246. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11247. taicpu(hp1).oper[0] := OperPtr;
  11248. end
  11249. else
  11250. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11251. taicpu(hp1).clearop(1);
  11252. taicpu(hp1).ops := 1;
  11253. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11254. end
  11255. else
  11256. begin
  11257. if taicpu(hp1).oper[1]^.typ = top_reg then
  11258. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11259. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11260. RemoveInstruction(hp1);
  11261. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11262. end
  11263. end;
  11264. Result := True;
  11265. end;
  11266. end;
  11267. end;
  11268. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11269. var
  11270. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11271. TargetReg: TRegister;
  11272. condition, inverted_condition: TAsmCond;
  11273. FoundMOV: Boolean;
  11274. begin
  11275. Result := False;
  11276. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11277. create the most optimial instructions possible due to limited
  11278. register availability, and there are situations where two
  11279. complementary "simple" CMOV blocks are created which, after the fact
  11280. can be merged into a "double" block. For example:
  11281. movw $257,%ax
  11282. movw $2,%r8w
  11283. xorl r9d,%r9d
  11284. testw $16,18(%rcx)
  11285. cmovew %ax,%dx
  11286. cmovew %r8w,%bx
  11287. cmovel %r9d,%r14d
  11288. movw $1283,%ax
  11289. movw $4,%r8w
  11290. movl $9,%r9d
  11291. cmovnew %ax,%dx
  11292. cmovnew %r8w,%bx
  11293. cmovnel %r9d,%r14d
  11294. The CMOVNE instructions at the end can be removed, and the
  11295. destination registers copied into the MOV instructions directly
  11296. above them, before finally being moved to before the first CMOVE
  11297. instructions, to produce:
  11298. movw $257,%ax
  11299. movw $2,%r8w
  11300. xorl r9d,%r9d
  11301. testw $16,18(%rcx)
  11302. movw $1283,%dx
  11303. movw $4,%bx
  11304. movl $9,%r14d
  11305. cmovew %ax,%dx
  11306. cmovew %r8w,%bx
  11307. cmovel %r9d,%r14d
  11308. Which can then be later optimised to:
  11309. movw $257,%ax
  11310. movw $2,%r8w
  11311. xorl r9d,%r9d
  11312. movw $1283,%dx
  11313. movw $4,%bx
  11314. movl $9,%r14d
  11315. testw $16,18(%rcx)
  11316. cmovew %ax,%dx
  11317. cmovew %r8w,%bx
  11318. cmovel %r9d,%r14d
  11319. }
  11320. TargetReg := taicpu(hp1).oper[1]^.reg;
  11321. condition := taicpu(hp1).condition;
  11322. inverted_condition := inverse_cond(condition);
  11323. pFirstMov := nil;
  11324. pLastMov := nil;
  11325. pCMOV := nil;
  11326. if (p.typ = ait_instruction) then
  11327. pCond := p
  11328. else if not GetNextInstruction(p, pCond) then
  11329. InternalError(2024012501);
  11330. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11331. { We should get the CMP or TEST instructeion }
  11332. InternalError(2024012502);
  11333. if (
  11334. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11335. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11336. ) then
  11337. begin
  11338. { We have to tread carefully here, hence why we're not using
  11339. GetNextInstructionUsingReg... we can only accept MOV and other
  11340. CMOV instructions. Anything else and we must drop out}
  11341. hp2 := hp1;
  11342. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11343. begin
  11344. if (hp2.typ <> ait_instruction) then
  11345. Exit;
  11346. case taicpu(hp2).opcode of
  11347. A_MOV:
  11348. begin
  11349. if not Assigned(pFirstMov) then
  11350. pFirstMov := hp2;
  11351. pLastMOV := hp2;
  11352. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11353. { Something different - drop out }
  11354. Exit;
  11355. { Otherwise, leave it for now }
  11356. end;
  11357. A_CMOVcc:
  11358. begin
  11359. if taicpu(hp2).condition = inverted_condition then
  11360. begin
  11361. { We found what we're looking for }
  11362. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11363. begin
  11364. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11365. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11366. begin
  11367. pCMOV := hp2;
  11368. Break;
  11369. end
  11370. else
  11371. { Unsafe reference - drop out }
  11372. Exit;
  11373. end;
  11374. end
  11375. else if taicpu(hp2).condition <> condition then
  11376. { Something weird - drop out }
  11377. Exit;
  11378. end;
  11379. else
  11380. { Invalid }
  11381. Exit;
  11382. end;
  11383. end;
  11384. if not Assigned(pCMOV) then
  11385. { No complementary CMOV found }
  11386. Exit;
  11387. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11388. begin
  11389. { Don't need to do anything special or search for a matching MOV }
  11390. Asml.Remove(pCMOV);
  11391. if RegInInstruction(TargetReg, pCond) then
  11392. { Make sure we don't overwrite the register if it's being used in the condition }
  11393. Asml.InsertAfter(pCMOV, pCond)
  11394. else
  11395. Asml.InsertBefore(pCMOV, pCond);
  11396. taicpu(pCMOV).opcode := A_MOV;
  11397. taicpu(pCMOV).condition := C_None;
  11398. { Don't need to worry about allocating new registers in these cases }
  11399. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11400. Result := True;
  11401. Exit;
  11402. end
  11403. else
  11404. begin
  11405. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11406. FoundMOV := False;
  11407. { Search for the MOV that sets the target register }
  11408. hp2 := pFirstMov;
  11409. repeat
  11410. if (taicpu(hp2).opcode = A_MOV) and
  11411. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11412. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11413. begin
  11414. { Change the destination }
  11415. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11416. if not FoundMOV then
  11417. begin
  11418. FoundMOV := True;
  11419. { Make sure the register is allocated }
  11420. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11421. end;
  11422. hp1 := tai(hp2.Previous);
  11423. Asml.Remove(hp2);
  11424. if RegInInstruction(TargetReg, pCond) then
  11425. { Make sure we don't overwrite the register if it's being used in the condition }
  11426. Asml.InsertAfter(hp2, pCond)
  11427. else
  11428. Asml.InsertBefore(hp2, pCond);
  11429. if (hp2 = pLastMov) then
  11430. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11431. Break;
  11432. hp2 := hp1;
  11433. end;
  11434. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11435. if FoundMOV then
  11436. { Delete the CMOV }
  11437. RemoveInstruction(pCMOV)
  11438. else
  11439. begin
  11440. { If no MOV was found, we have to actually move and transmute the CMOV }
  11441. Asml.Remove(pCMOV);
  11442. if RegInInstruction(TargetReg, pCond) then
  11443. { Make sure we don't overwrite the register if it's being used in the condition }
  11444. Asml.InsertAfter(pCMOV, pCond)
  11445. else
  11446. Asml.InsertBefore(pCMOV, pCond);
  11447. taicpu(pCMOV).opcode := A_MOV;
  11448. taicpu(pCMOV).condition := C_None;
  11449. end;
  11450. Result := True;
  11451. Exit;
  11452. end;
  11453. end;
  11454. end;
  11455. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11456. var
  11457. hp1, hp2, pCond: tai;
  11458. begin
  11459. Result := False;
  11460. { Search ahead for CMOV instructions }
  11461. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11462. begin
  11463. hp1 := p;
  11464. hp2 := p;
  11465. pCond := nil; { To prevent compiler warnings }
  11466. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11467. DEFAULTFLAGS }
  11468. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11469. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11470. pCond := p;
  11471. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11472. begin
  11473. if (hp1.typ <> ait_instruction) then
  11474. { Break out on markers and labels etc. }
  11475. Break;
  11476. case taicpu(hp1).opcode of
  11477. A_MOV:
  11478. { Ignore regular MOVs unless they are obviously not related
  11479. to a CMOV block }
  11480. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11481. Break;
  11482. A_CMOVcc:
  11483. if TryCmpCMovOpts(pCond, hp1) then
  11484. begin
  11485. hp1 := hp2;
  11486. { p itself isn't changed, and we're still inside a
  11487. while loop to catch subsequent CMOVs, so just flag
  11488. a new iteration }
  11489. Include(OptsToCheck, aoc_ForceNewIteration);
  11490. Continue;
  11491. end;
  11492. else
  11493. { Drop out if we find anything else }
  11494. Break;
  11495. end;
  11496. hp2 := hp1;
  11497. end;
  11498. end;
  11499. end;
  11500. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11501. var
  11502. hp1, hp2, pCond: tai;
  11503. SourceReg, TargetReg: TRegister;
  11504. begin
  11505. Result := False;
  11506. { In some situations, we end up with an inefficient arrangement of
  11507. instructions in the form of:
  11508. or %reg1,%reg2
  11509. (%reg1 deallocated)
  11510. test %reg2,%reg2
  11511. mov x,%reg2
  11512. we may be able to swap and rearrange the registers to produce:
  11513. or %reg2,%reg1
  11514. mov x,%reg2
  11515. test %reg1,%reg1
  11516. (%reg1 deallocated)
  11517. }
  11518. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11519. (taicpu(p).oper[1]^.typ = top_reg) and
  11520. (
  11521. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11522. MatchOperand(taicpu(p).oper[0]^, -1)
  11523. ) and
  11524. GetNextInstruction(p, hp1) and
  11525. MatchInstruction(hp1, A_MOV, []) and
  11526. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11527. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11528. begin
  11529. TargetReg := taicpu(p).oper[1]^.reg;
  11530. { Now look backwards to find a simple commutative operation: ADD,
  11531. IMUL (2-register version), OR, AND or XOR - whose destination
  11532. register is the same as TEST }
  11533. hp2 := p;
  11534. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11535. if RegInInstruction(TargetReg, hp2) then
  11536. begin
  11537. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11538. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11539. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11540. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11541. begin
  11542. SourceReg := taicpu(hp2).oper[0]^.reg;
  11543. if
  11544. { Make sure the MOV doesn't use the other register }
  11545. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11546. { And make sure the source register is not used afterwards }
  11547. not RegInUsedRegs(SourceReg, UsedRegs) then
  11548. begin
  11549. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11550. taicpu(hp2).oper[0]^.reg := TargetReg;
  11551. taicpu(hp2).oper[1]^.reg := SourceReg;
  11552. if taicpu(p).oper[0]^.typ = top_reg then
  11553. taicpu(p).oper[0]^.reg := SourceReg;
  11554. taicpu(p).oper[1]^.reg := SourceReg;
  11555. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11556. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11557. Include(OptsToCheck, aoc_ForceNewIteration);
  11558. { We can still check the following optimisations since
  11559. the instruction is still a TEST }
  11560. end;
  11561. end;
  11562. Break;
  11563. end;
  11564. end;
  11565. { Search ahead3 for CMOV instructions }
  11566. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11567. begin
  11568. hp1 := p;
  11569. hp2 := p;
  11570. pCond := nil; { To prevent compiler warnings }
  11571. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11572. DEFAULTFLAGS }
  11573. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11574. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11575. pCond := p;
  11576. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11577. begin
  11578. if (hp1.typ <> ait_instruction) then
  11579. { Break out on markers and labels etc. }
  11580. Break;
  11581. case taicpu(hp1).opcode of
  11582. A_MOV:
  11583. { Ignore regular MOVs unless they are obviously not related
  11584. to a CMOV block }
  11585. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11586. Break;
  11587. A_CMOVcc:
  11588. if TryCmpCMovOpts(pCond, hp1) then
  11589. begin
  11590. hp1 := hp2;
  11591. { p itself isn't changed, and we're still inside a
  11592. while loop to catch subsequent CMOVs, so just flag
  11593. a new iteration }
  11594. Include(OptsToCheck, aoc_ForceNewIteration);
  11595. Continue;
  11596. end;
  11597. else
  11598. { Drop out if we find anything else }
  11599. Break;
  11600. end;
  11601. hp2 := hp1;
  11602. end;
  11603. end;
  11604. end;
  11605. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11606. var
  11607. hp1: tai;
  11608. Count: Integer;
  11609. OrigLabel: TAsmLabel;
  11610. begin
  11611. result := False;
  11612. { Sometimes, the optimisations below can permit this }
  11613. RemoveDeadCodeAfterJump(p);
  11614. if (taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full) and (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  11615. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11616. begin
  11617. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11618. { Also a side-effect of optimisations }
  11619. if CollapseZeroDistJump(p, OrigLabel) then
  11620. begin
  11621. Result := True;
  11622. Exit;
  11623. end;
  11624. hp1 := GetLabelWithSym(OrigLabel);
  11625. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11626. begin
  11627. if taicpu(hp1).opcode = A_RET then
  11628. begin
  11629. {
  11630. change
  11631. jmp .L1
  11632. ...
  11633. .L1:
  11634. ret
  11635. into
  11636. ret
  11637. }
  11638. begin
  11639. ConvertJumpToRET(p, hp1);
  11640. result:=true;
  11641. end;
  11642. end
  11643. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11644. not (cs_opt_size in current_settings.optimizerswitches) and
  11645. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11646. begin
  11647. Result := True;
  11648. Exit;
  11649. end;
  11650. end;
  11651. end;
  11652. end;
  11653. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11654. begin
  11655. Result := assigned(p) and
  11656. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11657. (taicpu(p).oper[1]^.typ = top_reg) and
  11658. (
  11659. (taicpu(p).oper[0]^.typ = top_reg) or
  11660. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11661. it is not expected that this can cause a seg. violation }
  11662. (
  11663. (taicpu(p).oper[0]^.typ = top_ref) and
  11664. { TODO: Can we detect which references become constants at this
  11665. stage so we don't have to do a blanket ban? }
  11666. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11667. (
  11668. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11669. (
  11670. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11671. not RefModified and
  11672. { If the reference also appears in the condition, then we know it's safe, otherwise
  11673. any kind of access violation would have occurred already }
  11674. Assigned(cond_p) and
  11675. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11676. (cond_p.typ = ait_instruction) and
  11677. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11678. { Just consider 2-operand comparison instructions for now to be safe }
  11679. (taicpu(cond_p).ops = 2) and
  11680. (
  11681. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11682. (
  11683. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11684. { Don't risk identical registers but different offsets, as we may have constructs
  11685. such as buffer streams with things like length fields that indicate whether
  11686. any more data follows. And there are probably some contrived examples where
  11687. writing to offsets behind the one being read also lead to access violations }
  11688. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11689. (
  11690. { Check that we're not modifying a register that appears in the reference }
  11691. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11692. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11693. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11694. )
  11695. )
  11696. )
  11697. )
  11698. )
  11699. )
  11700. );
  11701. end;
  11702. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11703. begin
  11704. { Update integer registers, ignoring deallocations }
  11705. repeat
  11706. while assigned(p) and
  11707. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11708. (p.typ = ait_label) or
  11709. ((p.typ = ait_marker) and
  11710. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11711. p := tai(p.next);
  11712. while assigned(p) and
  11713. (p.typ=ait_RegAlloc) Do
  11714. begin
  11715. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11716. begin
  11717. case tai_regalloc(p).ratype of
  11718. ra_alloc :
  11719. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11720. else
  11721. ;
  11722. end;
  11723. end;
  11724. p := tai(p.next);
  11725. end;
  11726. until not(assigned(p)) or
  11727. (not(p.typ in SkipInstr) and
  11728. not((p.typ = ait_label) and
  11729. labelCanBeSkipped(tai_label(p))));
  11730. end;
  11731. {$ifndef 8086}
  11732. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11733. begin
  11734. Result := False;
  11735. EndJump := nil;
  11736. BlockStop := nil;
  11737. while (BlockStart <> fOptimizer.BlockEnd) and
  11738. { stop on labels }
  11739. (BlockStart.typ <> ait_label) do
  11740. begin
  11741. { Keep track of all integer registers that are used }
  11742. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11743. if BlockStart.typ = ait_instruction then
  11744. begin
  11745. if (taicpu(BlockStart).opcode = A_JMP) then
  11746. begin
  11747. if not IsJumpToLabel(taicpu(BlockStart)) or
  11748. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11749. Exit;
  11750. EndJump := BlockStart;
  11751. Break;
  11752. end
  11753. { Check to see if we have a valid MOV instruction instead }
  11754. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11755. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11756. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11757. begin
  11758. Exit;
  11759. end
  11760. else
  11761. { This will be a valid MOV }
  11762. fAllocationRange := BlockStart;
  11763. end;
  11764. OneBeforeBlock := BlockStart;
  11765. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11766. end;
  11767. if (BlockStart = fOptimizer.BlockEnd) then
  11768. Exit;
  11769. BlockStop := BlockStart;
  11770. Result := True;
  11771. end;
  11772. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11773. var
  11774. hp1: tai;
  11775. RefModified: Boolean;
  11776. begin
  11777. Result := 0;
  11778. hp1 := BlockStart;
  11779. RefModified := False; { As long as the condition is inverted, this can be reset }
  11780. while assigned(hp1) and
  11781. (hp1 <> BlockStop) do
  11782. begin
  11783. case hp1.typ of
  11784. ait_instruction:
  11785. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11786. begin
  11787. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11788. begin
  11789. Inc(Result);
  11790. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11791. Assigned(fCondition) and
  11792. { Will have 2 operands }
  11793. (
  11794. (
  11795. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11796. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11797. ) or
  11798. (
  11799. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11800. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11801. )
  11802. ) then
  11803. { It is no longer safe to use the reference in the condition.
  11804. this prevents problems such as:
  11805. mov (%reg),%reg
  11806. mov (%reg),...
  11807. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11808. (fixes #40165)
  11809. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11810. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11811. }
  11812. RefModified := True;
  11813. end
  11814. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11815. { CMOV with constants grows the code size }
  11816. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11817. begin
  11818. { Register was reserved by TryCMOVConst and
  11819. stored on ConstRegs }
  11820. end
  11821. else
  11822. begin
  11823. Result := -1;
  11824. Exit;
  11825. end;
  11826. end
  11827. else
  11828. begin
  11829. Result := -1;
  11830. Exit;
  11831. end;
  11832. else
  11833. { Most likely an align };
  11834. end;
  11835. fOptimizer.GetNextInstruction(hp1, hp1);
  11836. end;
  11837. end;
  11838. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11839. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11840. (this is done as a separate stage because the double types are extensions of the branching type,
  11841. but we can't discount the conditional jump until the last step) }
  11842. procedure EvaluateBranchingType;
  11843. begin
  11844. Inc(CMOVScore);
  11845. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11846. { Too many instructions to be worthwhile }
  11847. fState := tsInvalid;
  11848. end;
  11849. var
  11850. hp1: tai;
  11851. Count: Integer;
  11852. begin
  11853. { Table of valid CMOV block types
  11854. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11855. ---------- --------- --------- --------- --------- ---------
  11856. tsSimple X Yes X X X
  11857. tsDetour = 1st X X X X
  11858. tsBranching <> Mid Yes X X X
  11859. tsDouble End-label Yes * Yes X Yes
  11860. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11861. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11862. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11863. * Only one reference allowed
  11864. }
  11865. hp1 := nil; { To prevent compiler warnings }
  11866. Optimizer.CopyUsedRegs(RegisterTracking);
  11867. fOptimizer := Optimizer;
  11868. fLabel := AFirstLabel;
  11869. CMOVScore := 0;
  11870. ConstCount := 0;
  11871. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11872. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11873. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11874. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11875. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11876. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11877. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11878. fInsertionPoint := p_initialjump;
  11879. fCondition := nil;
  11880. fInitialJump := p_initialjump;
  11881. fFirstMovBlock := p_initialmov;
  11882. fFirstMovBlockStop := nil;
  11883. fSecondJump := nil;
  11884. fSecondMovBlock := nil;
  11885. fSecondMovBlockStop := nil;
  11886. fMidLabel := nil;
  11887. fSecondJump := nil;
  11888. fSecondMovBlock := nil;
  11889. fEndLabel := nil;
  11890. fAllocationRange := nil;
  11891. { Assume it all goes horribly wrong! }
  11892. fState := tsInvalid;
  11893. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11894. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11895. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11896. begin
  11897. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11898. for Count := 0 to 1 do
  11899. with taicpu(fCondition).oper[Count]^ do
  11900. case typ of
  11901. top_reg:
  11902. if getregtype(reg) = R_INTREGISTER then
  11903. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11904. top_ref:
  11905. begin
  11906. if
  11907. {$ifdef x86_64}
  11908. (ref^.base <> NR_RIP) and
  11909. {$endif x86_64}
  11910. (ref^.base <> NR_NO) then
  11911. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11912. if (ref^.index <> NR_NO) then
  11913. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11914. end
  11915. else
  11916. ;
  11917. end;
  11918. { When inserting instructions before hp_prev, try to insert them
  11919. before the allocation of the FLAGS register }
  11920. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11921. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11922. { If not found, set it equal to the condition so it's something sensible }
  11923. fInsertionPoint := fCondition;
  11924. { When dealing with a comparison against zero, take note of the
  11925. instruction before it to see if we can move instructions further
  11926. back in order to benefit PostPeepholeOptTestOr.
  11927. }
  11928. if (
  11929. (
  11930. (taicpu(fCondition).opcode = A_CMP) and
  11931. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11932. ) or
  11933. (
  11934. (taicpu(fCondition).opcode = A_TEST) and
  11935. (
  11936. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11937. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11938. )
  11939. )
  11940. ) and
  11941. Optimizer.GetLastInstruction(fCondition, hp1) then
  11942. begin
  11943. { These instructions set the zero flag if the result is zero }
  11944. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11945. begin
  11946. fInsertionPoint := hp1;
  11947. { Also mark all the registers in this previous instruction
  11948. as 'in use', even if they've just been deallocated }
  11949. for Count := 0 to 1 do
  11950. with taicpu(hp1).oper[Count]^ do
  11951. case typ of
  11952. top_reg:
  11953. if getregtype(reg) = R_INTREGISTER then
  11954. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11955. top_ref:
  11956. begin
  11957. if
  11958. {$ifdef x86_64}
  11959. (ref^.base <> NR_RIP) and
  11960. {$endif x86_64}
  11961. (ref^.base <> NR_NO) then
  11962. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11963. if (ref^.index <> NR_NO) then
  11964. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11965. end
  11966. else
  11967. ;
  11968. end;
  11969. end;
  11970. end;
  11971. end
  11972. else
  11973. fCondition := nil;
  11974. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11975. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11976. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11977. { If not found, set it equal to p so it's something sensible }
  11978. fInsertionPoint := hp1;
  11979. hp1 := p_initialmov;
  11980. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11981. Exit;
  11982. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11983. if (hp1.typ <> ait_label) then { should be on a jump }
  11984. begin
  11985. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11986. { Need a label afterwards }
  11987. Exit;
  11988. end
  11989. else
  11990. fMidLabel := hp1;
  11991. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11992. { Not the correct label }
  11993. fMidLabel := nil;
  11994. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11995. { If there's neither a 2nd jump nor correct label, then it's invalid
  11996. (see above table) }
  11997. Exit;
  11998. { Analyse the first block of MOVs more closely }
  11999. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12000. if Assigned(fSecondJump) then
  12001. begin
  12002. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12003. begin
  12004. fState := tsDetour
  12005. end
  12006. else
  12007. begin
  12008. { Need the correct mid-label for this one }
  12009. if not Assigned(fMidLabel) then
  12010. Exit;
  12011. fState := tsBranching;
  12012. end;
  12013. end
  12014. else
  12015. { No jump. but mid-label is present }
  12016. fState := tsSimple;
  12017. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12018. begin
  12019. { Invalid or too many instructions to be worthwhile }
  12020. fState := tsInvalid;
  12021. Exit;
  12022. end;
  12023. { check further for
  12024. jCC xxx
  12025. <several movs 1>
  12026. jmp yyy
  12027. xxx:
  12028. <several movs 2>
  12029. yyy:
  12030. etc.
  12031. }
  12032. if (fState = tsBranching) and
  12033. { Estimate for required savings for extra jump }
  12034. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12035. { Only one reference is allowed for double blocks }
  12036. (AFirstLabel.getrefs = 1) then
  12037. begin
  12038. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12039. fSecondMovBlock := hp1;
  12040. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12041. begin
  12042. EvaluateBranchingType;
  12043. Exit;
  12044. end;
  12045. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12046. if (hp1.typ <> ait_label) then { should be on a jump }
  12047. begin
  12048. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12049. begin
  12050. { Need a label afterwards }
  12051. EvaluateBranchingType;
  12052. Exit;
  12053. end;
  12054. end
  12055. else
  12056. fEndLabel := hp1;
  12057. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12058. { Second jump doesn't go to the end }
  12059. fEndLabel := nil;
  12060. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12061. begin
  12062. { If there's neither a 3rd jump nor correct end label, then it's
  12063. not a invalid double block, but is a valid single branching
  12064. block (see above table) }
  12065. EvaluateBranchingType;
  12066. Exit;
  12067. end;
  12068. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12069. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12070. { Invalid or too many instructions to be worthwhile }
  12071. Exit;
  12072. Inc(CMOVScore, Count);
  12073. if Assigned(fThirdJump) then
  12074. begin
  12075. if not Assigned(fSecondJump) then
  12076. fState := tsDoubleSecondBranching
  12077. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12078. fState := tsDoubleBranchSame
  12079. else
  12080. fState := tsDoubleBranchDifferent;
  12081. end
  12082. else
  12083. fState := tsDouble;
  12084. end;
  12085. if fState = tsBranching then
  12086. EvaluateBranchingType;
  12087. end;
  12088. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12089. new register to store the constant }
  12090. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12091. var
  12092. RegSize: TSubRegister;
  12093. CurrentVal: TCGInt;
  12094. ANewReg: TRegister;
  12095. X: ShortInt;
  12096. begin
  12097. Result := False;
  12098. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12099. Exit;
  12100. if ConstCount >= MAX_CMOV_REGISTERS then
  12101. { Arrays are full }
  12102. Exit;
  12103. { Remember that CMOV can't encode 8-bit registers }
  12104. case taicpu(p).opsize of
  12105. S_W:
  12106. RegSize := R_SUBW;
  12107. S_L:
  12108. RegSize := R_SUBD;
  12109. {$ifdef x86_64}
  12110. S_Q:
  12111. RegSize := R_SUBQ;
  12112. {$endif x86_64}
  12113. else
  12114. InternalError(2021100401);
  12115. end;
  12116. { See if the value has already been reserved for another CMOV instruction }
  12117. CurrentVal := taicpu(p).oper[0]^.val;
  12118. for X := 0 to ConstCount - 1 do
  12119. if ConstVals[X] = CurrentVal then
  12120. begin
  12121. ConstRegs[ConstCount] := ConstRegs[X];
  12122. ConstSizes[ConstCount] := RegSize;
  12123. ConstVals[ConstCount] := CurrentVal;
  12124. Inc(ConstCount);
  12125. Inc(Count);
  12126. Result := True;
  12127. Exit;
  12128. end;
  12129. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12130. if ANewReg = NR_NO then
  12131. { No free registers }
  12132. Exit;
  12133. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12134. up vying for the same register }
  12135. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12136. ConstRegs[ConstCount] := ANewReg;
  12137. ConstSizes[ConstCount] := RegSize;
  12138. ConstVals[ConstCount] := CurrentVal;
  12139. Inc(ConstCount);
  12140. Inc(Count);
  12141. Result := True;
  12142. end;
  12143. destructor TCMOVTracking.Done;
  12144. begin
  12145. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12146. end;
  12147. procedure TCMOVTracking.Process(out new_p: tai);
  12148. var
  12149. Count, Writes: LongInt;
  12150. RegMatch: Boolean;
  12151. hp1, hp_new: tai;
  12152. inverted_condition, condition: TAsmCond;
  12153. begin
  12154. if (fState in [tsInvalid, tsProcessed]) then
  12155. InternalError(2023110701);
  12156. { Repurpose RegisterTracking to mark registers that we've defined }
  12157. RegisterTracking[R_INTREGISTER].Clear;
  12158. Count := 0;
  12159. Writes := 0;
  12160. condition := taicpu(fInitialJump).condition;
  12161. inverted_condition := inverse_cond(condition);
  12162. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12163. doesn't get CMOVs in this case }
  12164. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12165. begin
  12166. { Include the jump in the flag tracking }
  12167. if Assigned(fThirdJump) then
  12168. begin
  12169. if (fState = tsDoubleBranchSame) then
  12170. begin
  12171. { Will be an unconditional jump, so track to the instruction before it }
  12172. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12173. InternalError(2023110710);
  12174. end
  12175. else
  12176. hp1 := fThirdJump;
  12177. end
  12178. else
  12179. hp1 := fSecondMovBlockStop;
  12180. end
  12181. else
  12182. begin
  12183. { Include a conditional jump in the flag tracking }
  12184. if Assigned(fSecondJump) then
  12185. begin
  12186. if (fState = tsDetour) then
  12187. begin
  12188. { Will be an unconditional jump, so track to the instruction before it }
  12189. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12190. InternalError(2023110711);
  12191. end
  12192. else
  12193. hp1 := fSecondJump;
  12194. end
  12195. else
  12196. hp1 := fFirstMovBlockStop;
  12197. end;
  12198. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12199. { Process the second set of MOVs first, because if a destination
  12200. register is shared between the first and second MOV sets, it is more
  12201. efficient to turn the first one into a MOV instruction and place it
  12202. before the CMP if possible, but we won't know which registers are
  12203. shared until we've processed at least one list, so we might as well
  12204. make it the second one since that won't be modified again. }
  12205. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12206. begin
  12207. hp1 := fSecondMovBlock;
  12208. repeat
  12209. if not Assigned(hp1) then
  12210. InternalError(2018062902);
  12211. if (hp1.typ = ait_instruction) then
  12212. begin
  12213. { Extra safeguard }
  12214. if (taicpu(hp1).opcode <> A_MOV) then
  12215. InternalError(2018062903);
  12216. { Note: tsDoubleBranchDifferent is essentially identical to
  12217. tsBranching and the 2nd block is best left largely
  12218. untouched, but we need to evaluate which registers the MOVs
  12219. write to in order to track what would be complementary CMOV
  12220. pairs that can be further optimised. [Kit] }
  12221. if fState <> tsDoubleBranchDifferent then
  12222. begin
  12223. if taicpu(hp1).oper[0]^.typ = top_const then
  12224. begin
  12225. RegMatch := False;
  12226. for Count := 0 to ConstCount - 1 do
  12227. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12228. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12229. begin
  12230. RegMatch := True;
  12231. { If it's in RegisterTracking, then this register
  12232. is being used more than once and hence has
  12233. already had its value defined (it gets added to
  12234. UsedRegs through AllocRegBetween below) }
  12235. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12236. begin
  12237. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12238. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12239. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12240. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12241. ConstMovs[Count] := hp_new;
  12242. end
  12243. else
  12244. { We just need an instruction between hp_prev and hp1
  12245. where we know the register is marked as in use }
  12246. hp_new := fSecondMovBlock;
  12247. { Keep track of largest write for this register so it can be optimised later }
  12248. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12249. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12250. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12251. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12252. Break;
  12253. end;
  12254. if not RegMatch then
  12255. InternalError(2021100411);
  12256. end;
  12257. taicpu(hp1).opcode := A_CMOVcc;
  12258. taicpu(hp1).condition := condition;
  12259. end;
  12260. { Store these writes to search for duplicates later on }
  12261. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12262. Inc(Writes);
  12263. end;
  12264. fOptimizer.GetNextInstruction(hp1, hp1);
  12265. until (hp1 = fSecondMovBlockStop);
  12266. end;
  12267. { Now do the first set of MOVs }
  12268. hp1 := fFirstMovBlock;
  12269. repeat
  12270. if not Assigned(hp1) then
  12271. InternalError(2018062904);
  12272. if (hp1.typ = ait_instruction) then
  12273. begin
  12274. RegMatch := False;
  12275. { Extra safeguard }
  12276. if (taicpu(hp1).opcode <> A_MOV) then
  12277. InternalError(2018062905);
  12278. { Search through the RegWrites list to see if there are any
  12279. opposing CMOV pairs that write to the same register }
  12280. for Count := 0 to Writes - 1 do
  12281. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12282. begin
  12283. { We have a match. Keep this as a MOV }
  12284. { Move ahead in preparation }
  12285. fOptimizer.GetNextInstruction(hp1, hp1);
  12286. RegMatch := True;
  12287. Break;
  12288. end;
  12289. if RegMatch then
  12290. Continue;
  12291. if taicpu(hp1).oper[0]^.typ = top_const then
  12292. begin
  12293. for Count := 0 to ConstCount - 1 do
  12294. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12295. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12296. begin
  12297. RegMatch := True;
  12298. { If it's in RegisterTracking, then this register is
  12299. being used more than once and hence has already had
  12300. its value defined (it gets added to UsedRegs through
  12301. AllocRegBetween below) }
  12302. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12303. begin
  12304. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12305. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12306. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12307. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12308. ConstMovs[Count] := hp_new;
  12309. end
  12310. else
  12311. { We just need an instruction between hp_prev and hp1
  12312. where we know the register is marked as in use }
  12313. hp_new := fFirstMovBlock;
  12314. { Keep track of largest write for this register so it can be optimised later }
  12315. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12316. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12317. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12318. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12319. Break;
  12320. end;
  12321. if not RegMatch then
  12322. InternalError(2021100412);
  12323. end;
  12324. taicpu(hp1).opcode := A_CMOVcc;
  12325. taicpu(hp1).condition := inverted_condition;
  12326. if (fState = tsDoubleBranchDifferent) then
  12327. begin
  12328. { Store these writes to search for duplicates later on }
  12329. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12330. Inc(Writes);
  12331. end;
  12332. end;
  12333. fOptimizer.GetNextInstruction(hp1, hp1);
  12334. until (hp1 = fFirstMovBlockStop);
  12335. { Update initialisation MOVs to the smallest possible size }
  12336. for Count := 0 to ConstCount - 1 do
  12337. if Assigned(ConstMovs[Count]) then
  12338. begin
  12339. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12340. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12341. end;
  12342. case fState of
  12343. tsSimple:
  12344. begin
  12345. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12346. { No branch to delete }
  12347. end;
  12348. tsDetour:
  12349. begin
  12350. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12351. { Preserve jump }
  12352. end;
  12353. tsBranching, tsDoubleBranchDifferent:
  12354. begin
  12355. if (fState = tsBranching) then
  12356. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12357. else
  12358. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12359. taicpu(fSecondJump).opcode := A_JCC;
  12360. taicpu(fSecondJump).condition := inverted_condition;
  12361. end;
  12362. tsDouble, tsDoubleBranchSame:
  12363. begin
  12364. if (fState = tsDouble) then
  12365. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12366. else
  12367. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12368. { Delete second jump }
  12369. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12370. fOptimizer.RemoveInstruction(fSecondJump);
  12371. end;
  12372. tsDoubleSecondBranching:
  12373. begin
  12374. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12375. { Delete second jump, preserve third jump as conditional }
  12376. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12377. fOptimizer.RemoveInstruction(fSecondJump);
  12378. taicpu(fThirdJump).opcode := A_JCC;
  12379. taicpu(fThirdJump).condition := condition;
  12380. end;
  12381. else
  12382. InternalError(2023110720);
  12383. end;
  12384. { Now we can safely decrement the reference count }
  12385. tasmlabel(fLabel).decrefs;
  12386. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12387. { Remove the original jump }
  12388. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12389. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12390. fState := tsProcessed;
  12391. end;
  12392. {$endif 8086}
  12393. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12394. var
  12395. hp1,hp2: tai;
  12396. carryadd_opcode : TAsmOp;
  12397. symbol: TAsmSymbol;
  12398. increg, tmpreg: TRegister;
  12399. {$ifndef i8086}
  12400. CMOVTracking: PCMOVTracking;
  12401. hp3,hp4,hp5: tai;
  12402. {$endif i8086}
  12403. TempBool: Boolean;
  12404. begin
  12405. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12406. DoJumpOptimizations(p, TempBool) then
  12407. Exit(True);
  12408. result:=false;
  12409. if GetNextInstruction(p,hp1) then
  12410. begin
  12411. if (hp1.typ=ait_label) then
  12412. begin
  12413. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12414. Exit;
  12415. end
  12416. else if (hp1.typ<>ait_instruction) then
  12417. Exit;
  12418. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12419. if (
  12420. (
  12421. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12422. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12423. (Taicpu(hp1).oper[0]^.val=1)
  12424. ) or
  12425. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12426. ) and
  12427. GetNextInstruction(hp1,hp2) and
  12428. (hp2.typ = ait_label) and
  12429. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12430. { jb @@1 cmc
  12431. inc/dec operand --> adc/sbb operand,0
  12432. @@1:
  12433. ... and ...
  12434. jnb @@1
  12435. inc/dec operand --> adc/sbb operand,0
  12436. @@1: }
  12437. begin
  12438. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12439. begin
  12440. case taicpu(hp1).opcode of
  12441. A_INC,
  12442. A_ADD:
  12443. carryadd_opcode:=A_ADC;
  12444. A_DEC,
  12445. A_SUB:
  12446. carryadd_opcode:=A_SBB;
  12447. else
  12448. InternalError(2021011001);
  12449. end;
  12450. Taicpu(p).clearop(0);
  12451. Taicpu(p).ops:=0;
  12452. Taicpu(p).is_jmp:=false;
  12453. Taicpu(p).opcode:=A_CMC;
  12454. Taicpu(p).condition:=C_NONE;
  12455. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12456. Taicpu(hp1).ops:=2;
  12457. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12458. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12459. else
  12460. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12461. Taicpu(hp1).loadconst(0,0);
  12462. Taicpu(hp1).opcode:=carryadd_opcode;
  12463. result:=true;
  12464. exit;
  12465. end
  12466. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12467. begin
  12468. case taicpu(hp1).opcode of
  12469. A_INC,
  12470. A_ADD:
  12471. carryadd_opcode:=A_ADC;
  12472. A_DEC,
  12473. A_SUB:
  12474. carryadd_opcode:=A_SBB;
  12475. else
  12476. InternalError(2021011002);
  12477. end;
  12478. Taicpu(hp1).ops:=2;
  12479. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12480. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12481. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12482. else
  12483. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12484. Taicpu(hp1).loadconst(0,0);
  12485. Taicpu(hp1).opcode:=carryadd_opcode;
  12486. RemoveCurrentP(p, hp1);
  12487. result:=true;
  12488. exit;
  12489. end
  12490. {
  12491. jcc @@1 setcc tmpreg
  12492. inc/dec/add/sub operand -> (movzx tmpreg)
  12493. @@1: add/sub tmpreg,operand
  12494. While this increases code size slightly, it makes the code much faster if the
  12495. jump is unpredictable
  12496. }
  12497. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12498. begin
  12499. { search for an available register which is volatile }
  12500. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12501. if increg <> NR_NO then
  12502. begin
  12503. { We don't need to check if tmpreg is in hp1 or not, because
  12504. it will be marked as in use at p (if not, this is
  12505. indictive of a compiler bug). }
  12506. TAsmLabel(symbol).decrefs;
  12507. Taicpu(p).clearop(0);
  12508. Taicpu(p).ops:=1;
  12509. Taicpu(p).is_jmp:=false;
  12510. Taicpu(p).opcode:=A_SETcc;
  12511. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12512. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12513. Taicpu(p).loadreg(0,increg);
  12514. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12515. begin
  12516. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12517. R_SUBW:
  12518. begin
  12519. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12520. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12521. end;
  12522. R_SUBD:
  12523. begin
  12524. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12525. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12526. end;
  12527. {$ifdef x86_64}
  12528. R_SUBQ:
  12529. begin
  12530. { MOVZX doesn't have a 64-bit variant, because
  12531. the 32-bit version implicitly zeroes the
  12532. upper 32-bits of the destination register }
  12533. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12534. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12535. setsubreg(tmpreg, R_SUBQ);
  12536. end;
  12537. {$endif x86_64}
  12538. else
  12539. Internalerror(2020030601);
  12540. end;
  12541. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12542. asml.InsertAfter(hp2,p);
  12543. end
  12544. else
  12545. tmpreg := increg;
  12546. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12547. begin
  12548. Taicpu(hp1).ops:=2;
  12549. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12550. end;
  12551. Taicpu(hp1).loadreg(0,tmpreg);
  12552. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12553. Result := True;
  12554. { p is no longer a Jcc instruction, so exit }
  12555. Exit;
  12556. end;
  12557. end;
  12558. end;
  12559. { Detect the following:
  12560. jmp<cond> @Lbl1
  12561. jmp @Lbl2
  12562. ...
  12563. @Lbl1:
  12564. ret
  12565. Change to:
  12566. jmp<inv_cond> @Lbl2
  12567. ret
  12568. }
  12569. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12570. begin
  12571. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12572. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12573. MatchInstruction(hp2,A_RET,[S_NO]) then
  12574. begin
  12575. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12576. { Change label address to that of the unconditional jump }
  12577. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12578. TAsmLabel(symbol).DecRefs;
  12579. taicpu(hp1).opcode := A_RET;
  12580. taicpu(hp1).is_jmp := false;
  12581. taicpu(hp1).ops := taicpu(hp2).ops;
  12582. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12583. case taicpu(hp2).ops of
  12584. 0:
  12585. taicpu(hp1).clearop(0);
  12586. 1:
  12587. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12588. else
  12589. internalerror(2016041302);
  12590. end;
  12591. end;
  12592. {$ifndef i8086}
  12593. end
  12594. {
  12595. convert
  12596. j<c> .L1
  12597. mov 1,reg
  12598. jmp .L2
  12599. .L1
  12600. mov 0,reg
  12601. .L2
  12602. into
  12603. mov 0,reg
  12604. set<not(c)> reg
  12605. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12606. would destroy the flag contents
  12607. }
  12608. else if MatchInstruction(hp1,A_MOV,[]) and
  12609. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12610. {$ifdef i386}
  12611. (
  12612. { Under i386, ESI, EDI, EBP and ESP
  12613. don't have an 8-bit representation }
  12614. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12615. ) and
  12616. {$endif i386}
  12617. (taicpu(hp1).oper[0]^.val=1) and
  12618. GetNextInstruction(hp1,hp2) and
  12619. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12620. GetNextInstruction(hp2,hp3) and
  12621. (hp3.typ=ait_label) and
  12622. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12623. (tai_label(hp3).labsym.getrefs=1) and
  12624. GetNextInstruction(hp3,hp4) and
  12625. MatchInstruction(hp4,A_MOV,[]) and
  12626. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12627. (taicpu(hp4).oper[0]^.val=0) and
  12628. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12629. GetNextInstruction(hp4,hp5) and
  12630. (hp5.typ=ait_label) and
  12631. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12632. (tai_label(hp5).labsym.getrefs=1) then
  12633. begin
  12634. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12635. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12636. { remove last label }
  12637. RemoveInstruction(hp5);
  12638. { remove second label }
  12639. RemoveInstruction(hp3);
  12640. { remove jmp }
  12641. RemoveInstruction(hp2);
  12642. if taicpu(hp1).opsize=S_B then
  12643. RemoveInstruction(hp1)
  12644. else
  12645. taicpu(hp1).loadconst(0,0);
  12646. taicpu(hp4).opcode:=A_SETcc;
  12647. taicpu(hp4).opsize:=S_B;
  12648. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12649. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12650. taicpu(hp4).opercnt:=1;
  12651. taicpu(hp4).ops:=1;
  12652. taicpu(hp4).freeop(1);
  12653. RemoveCurrentP(p);
  12654. Result:=true;
  12655. exit;
  12656. end
  12657. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12658. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12659. begin
  12660. { check for
  12661. jCC xxx
  12662. <several movs>
  12663. xxx:
  12664. Also spot:
  12665. Jcc xxx
  12666. <several movs>
  12667. jmp xxx
  12668. Change to:
  12669. <several cmovs with inverted condition>
  12670. jmp xxx (only for the 2nd case)
  12671. }
  12672. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12673. if CMOVTracking^.State <> tsInvalid then
  12674. begin
  12675. CMovTracking^.Process(p);
  12676. Result := True;
  12677. end;
  12678. CMOVTracking^.Done;
  12679. {$endif i8086}
  12680. end;
  12681. end;
  12682. end;
  12683. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12684. var
  12685. hp1,hp2,hp3: tai;
  12686. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12687. NewSize: TOpSize;
  12688. NewRegSize: TSubRegister;
  12689. Limit: TCgInt;
  12690. SwapOper: POper;
  12691. begin
  12692. result:=false;
  12693. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12694. GetNextInstruction(p,hp1) and
  12695. (hp1.typ = ait_instruction);
  12696. if reg_and_hp1_is_instr and
  12697. (
  12698. (taicpu(hp1).opcode <> A_LEA) or
  12699. { If the LEA instruction can be converted into an arithmetic instruction,
  12700. it may be possible to then fold it. }
  12701. (
  12702. { If the flags register is in use, don't change the instruction
  12703. to an ADD otherwise this will scramble the flags. [Kit] }
  12704. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12705. ConvertLEA(taicpu(hp1))
  12706. )
  12707. ) and
  12708. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12709. GetNextInstruction(hp1,hp2) and
  12710. MatchInstruction(hp2,A_MOV,[]) and
  12711. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12712. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12713. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12714. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12715. {$ifdef i386}
  12716. { not all registers have byte size sub registers on i386 }
  12717. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12718. {$endif i386}
  12719. (((taicpu(hp1).ops=2) and
  12720. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12721. ((taicpu(hp1).ops=1) and
  12722. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12723. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12724. begin
  12725. { change movsX/movzX reg/ref, reg2
  12726. add/sub/or/... reg3/$const, reg2
  12727. mov reg2 reg/ref
  12728. to add/sub/or/... reg3/$const, reg/ref }
  12729. { by example:
  12730. movswl %si,%eax movswl %si,%eax p
  12731. decl %eax addl %edx,%eax hp1
  12732. movw %ax,%si movw %ax,%si hp2
  12733. ->
  12734. movswl %si,%eax movswl %si,%eax p
  12735. decw %eax addw %edx,%eax hp1
  12736. movw %ax,%si movw %ax,%si hp2
  12737. }
  12738. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12739. {
  12740. ->
  12741. movswl %si,%eax movswl %si,%eax p
  12742. decw %si addw %dx,%si hp1
  12743. movw %ax,%si movw %ax,%si hp2
  12744. }
  12745. case taicpu(hp1).ops of
  12746. 1:
  12747. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12748. 2:
  12749. begin
  12750. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12751. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12752. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12753. end;
  12754. else
  12755. internalerror(2008042702);
  12756. end;
  12757. {
  12758. ->
  12759. decw %si addw %dx,%si p
  12760. }
  12761. DebugMsg(SPeepholeOptimization + 'var3',p);
  12762. RemoveCurrentP(p, hp1);
  12763. RemoveInstruction(hp2);
  12764. Result := True;
  12765. Exit;
  12766. end;
  12767. if reg_and_hp1_is_instr and
  12768. (taicpu(hp1).opcode = A_MOV) and
  12769. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12770. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12771. {$ifdef x86_64}
  12772. { check for implicit extension to 64 bit }
  12773. or
  12774. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12775. (taicpu(hp1).opsize=S_Q) and
  12776. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12777. )
  12778. {$endif x86_64}
  12779. )
  12780. then
  12781. begin
  12782. { change
  12783. movx %reg1,%reg2
  12784. mov %reg2,%reg3
  12785. dealloc %reg2
  12786. into
  12787. movx %reg,%reg3
  12788. }
  12789. TransferUsedRegs(TmpUsedRegs);
  12790. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12791. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12792. begin
  12793. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12794. {$ifdef x86_64}
  12795. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12796. (taicpu(hp1).opsize=S_Q) then
  12797. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12798. else
  12799. {$endif x86_64}
  12800. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12801. RemoveInstruction(hp1);
  12802. Result := True;
  12803. Exit;
  12804. end;
  12805. end;
  12806. if reg_and_hp1_is_instr and
  12807. ((taicpu(hp1).opcode=A_MOV) or
  12808. (taicpu(hp1).opcode=A_ADD) or
  12809. (taicpu(hp1).opcode=A_SUB) or
  12810. (taicpu(hp1).opcode=A_CMP) or
  12811. (taicpu(hp1).opcode=A_OR) or
  12812. (taicpu(hp1).opcode=A_XOR) or
  12813. (taicpu(hp1).opcode=A_AND)
  12814. ) and
  12815. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12816. begin
  12817. AndTest := (taicpu(hp1).opcode=A_AND) and
  12818. GetNextInstruction(hp1, hp2) and
  12819. (hp2.typ = ait_instruction) and
  12820. (
  12821. (
  12822. (taicpu(hp2).opcode=A_TEST) and
  12823. (
  12824. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12825. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12826. (
  12827. { If the AND and TEST instructions share a constant, this is also valid }
  12828. (taicpu(hp1).oper[0]^.typ = top_const) and
  12829. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12830. )
  12831. ) and
  12832. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12833. ) or
  12834. (
  12835. (taicpu(hp2).opcode=A_CMP) and
  12836. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12837. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12838. )
  12839. );
  12840. { change
  12841. movx (oper),%reg2
  12842. and $x,%reg2
  12843. test %reg2,%reg2
  12844. dealloc %reg2
  12845. into
  12846. op %reg1,%reg3
  12847. if the second op accesses only the bits stored in reg1
  12848. }
  12849. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12850. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12851. (taicpu(hp1).oper[0]^.typ = top_const) and
  12852. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12853. AndTest then
  12854. begin
  12855. { Check if the AND constant is in range }
  12856. case taicpu(p).opsize of
  12857. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12858. begin
  12859. NewSize := S_B;
  12860. Limit := $FF;
  12861. end;
  12862. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12863. begin
  12864. NewSize := S_W;
  12865. Limit := $FFFF;
  12866. end;
  12867. {$ifdef x86_64}
  12868. S_LQ:
  12869. begin
  12870. NewSize := S_L;
  12871. Limit := $FFFFFFFF;
  12872. end;
  12873. {$endif x86_64}
  12874. else
  12875. InternalError(2021120303);
  12876. end;
  12877. if (
  12878. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12879. { Check for negative operands }
  12880. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12881. ) and
  12882. GetNextInstruction(hp2,hp3) and
  12883. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12884. (taicpu(hp3).condition in [C_E,C_NE]) then
  12885. begin
  12886. TransferUsedRegs(TmpUsedRegs);
  12887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12888. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12889. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12890. begin
  12891. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12892. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12893. taicpu(hp1).opcode := A_TEST;
  12894. taicpu(hp1).opsize := NewSize;
  12895. RemoveInstruction(hp2);
  12896. RemoveCurrentP(p, hp1);
  12897. Result:=true;
  12898. exit;
  12899. end;
  12900. end;
  12901. end;
  12902. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12903. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12904. (taicpu(hp1).opsize=S_B)) or
  12905. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12906. (taicpu(hp1).opsize=S_W))
  12907. {$ifdef x86_64}
  12908. or ((taicpu(p).opsize=S_LQ) and
  12909. (taicpu(hp1).opsize=S_L))
  12910. {$endif x86_64}
  12911. ) and
  12912. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12913. begin
  12914. { change
  12915. movx %reg1,%reg2
  12916. op %reg2,%reg3
  12917. dealloc %reg2
  12918. into
  12919. op %reg1,%reg3
  12920. if the second op accesses only the bits stored in reg1
  12921. }
  12922. TransferUsedRegs(TmpUsedRegs);
  12923. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12924. if AndTest then
  12925. begin
  12926. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12927. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12928. end
  12929. else
  12930. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12931. if not RegUsed then
  12932. begin
  12933. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12934. if taicpu(p).oper[0]^.typ=top_reg then
  12935. begin
  12936. case taicpu(hp1).opsize of
  12937. S_B:
  12938. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12939. S_W:
  12940. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12941. S_L:
  12942. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12943. else
  12944. Internalerror(2020102301);
  12945. end;
  12946. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12947. end
  12948. else
  12949. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12950. RemoveCurrentP(p);
  12951. if AndTest then
  12952. RemoveInstruction(hp2);
  12953. result:=true;
  12954. exit;
  12955. end;
  12956. end
  12957. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12958. (
  12959. { Bitwise operations only }
  12960. (taicpu(hp1).opcode=A_AND) or
  12961. (taicpu(hp1).opcode=A_TEST) or
  12962. (
  12963. (taicpu(hp1).oper[0]^.typ = top_const) and
  12964. (
  12965. (taicpu(hp1).opcode=A_OR) or
  12966. (taicpu(hp1).opcode=A_XOR)
  12967. )
  12968. )
  12969. ) and
  12970. (
  12971. (taicpu(hp1).oper[0]^.typ = top_const) or
  12972. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12973. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12974. ) then
  12975. begin
  12976. { change
  12977. movx %reg2,%reg2
  12978. op const,%reg2
  12979. into
  12980. op const,%reg2 (smaller version)
  12981. movx %reg2,%reg2
  12982. also change
  12983. movx %reg1,%reg2
  12984. and/test (oper),%reg2
  12985. dealloc %reg2
  12986. into
  12987. and/test (oper),%reg1
  12988. }
  12989. case taicpu(p).opsize of
  12990. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12991. begin
  12992. NewSize := S_B;
  12993. NewRegSize := R_SUBL;
  12994. Limit := $FF;
  12995. end;
  12996. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12997. begin
  12998. NewSize := S_W;
  12999. NewRegSize := R_SUBW;
  13000. Limit := $FFFF;
  13001. end;
  13002. {$ifdef x86_64}
  13003. S_LQ:
  13004. begin
  13005. NewSize := S_L;
  13006. NewRegSize := R_SUBD;
  13007. Limit := $FFFFFFFF;
  13008. end;
  13009. {$endif x86_64}
  13010. else
  13011. Internalerror(2021120302);
  13012. end;
  13013. TransferUsedRegs(TmpUsedRegs);
  13014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13015. if AndTest then
  13016. begin
  13017. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13018. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13019. end
  13020. else
  13021. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13022. if
  13023. (
  13024. (taicpu(p).opcode = A_MOVZX) and
  13025. (
  13026. (taicpu(hp1).opcode=A_AND) or
  13027. (taicpu(hp1).opcode=A_TEST)
  13028. ) and
  13029. not (
  13030. { If both are references, then the final instruction will have
  13031. both operands as references, which is not allowed }
  13032. (taicpu(p).oper[0]^.typ = top_ref) and
  13033. (taicpu(hp1).oper[0]^.typ = top_ref)
  13034. ) and
  13035. not RegUsed
  13036. ) or
  13037. (
  13038. (
  13039. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13040. not RegUsed
  13041. ) and
  13042. (taicpu(p).oper[0]^.typ = top_reg) and
  13043. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13044. (taicpu(hp1).oper[0]^.typ = top_const) and
  13045. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13046. ) then
  13047. begin
  13048. {$if defined(i386) or defined(i8086)}
  13049. { If the target size is 8-bit, make sure we can actually encode it }
  13050. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  13051. Exit;
  13052. {$endif i386 or i8086}
  13053. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13054. taicpu(hp1).opsize := NewSize;
  13055. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13056. if AndTest then
  13057. begin
  13058. RemoveInstruction(hp2);
  13059. if not RegUsed then
  13060. begin
  13061. taicpu(hp1).opcode := A_TEST;
  13062. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13063. begin
  13064. { Make sure the reference is the second operand }
  13065. SwapOper := taicpu(hp1).oper[0];
  13066. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13067. taicpu(hp1).oper[1] := SwapOper;
  13068. end;
  13069. end;
  13070. end;
  13071. case taicpu(hp1).oper[0]^.typ of
  13072. top_reg:
  13073. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13074. top_const:
  13075. { For the AND/TEST case }
  13076. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13077. else
  13078. ;
  13079. end;
  13080. if RegUsed then
  13081. begin
  13082. AsmL.Remove(p);
  13083. AsmL.InsertAfter(p, hp1);
  13084. p := hp1;
  13085. end
  13086. else
  13087. RemoveCurrentP(p, hp1);
  13088. result:=true;
  13089. exit;
  13090. end;
  13091. end;
  13092. end;
  13093. if reg_and_hp1_is_instr and
  13094. (taicpu(p).oper[0]^.typ = top_reg) and
  13095. (
  13096. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13097. ) and
  13098. (taicpu(hp1).oper[0]^.typ = top_const) and
  13099. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13100. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13101. { Minimum shift value allowed is the bit difference between the sizes }
  13102. (taicpu(hp1).oper[0]^.val >=
  13103. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13104. 8 * (
  13105. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13106. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13107. )
  13108. ) then
  13109. begin
  13110. { For:
  13111. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13112. shl/sal ##, %reg1
  13113. Remove the movsx/movzx instruction if the shift overwrites the
  13114. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13115. }
  13116. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13117. RemoveCurrentP(p, hp1);
  13118. Result := True;
  13119. Exit;
  13120. end
  13121. else if reg_and_hp1_is_instr and
  13122. (taicpu(p).oper[0]^.typ = top_reg) and
  13123. (
  13124. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13125. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13126. ) and
  13127. (taicpu(hp1).oper[0]^.typ = top_const) and
  13128. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13129. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13130. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13131. (taicpu(hp1).oper[0]^.val <
  13132. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13133. 8 * (
  13134. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13135. )
  13136. ) then
  13137. begin
  13138. { For:
  13139. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13140. sar ##, %reg1 shr ##, %reg1
  13141. Move the shift to before the movx instruction if the shift value
  13142. is not too large.
  13143. }
  13144. asml.Remove(hp1);
  13145. asml.InsertBefore(hp1, p);
  13146. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13147. case taicpu(p).opsize of
  13148. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13149. taicpu(hp1).opsize := S_B;
  13150. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13151. taicpu(hp1).opsize := S_W;
  13152. {$ifdef x86_64}
  13153. S_LQ:
  13154. taicpu(hp1).opsize := S_L;
  13155. {$endif}
  13156. else
  13157. InternalError(2020112401);
  13158. end;
  13159. if (taicpu(hp1).opcode = A_SHR) then
  13160. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13161. else
  13162. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13163. Result := True;
  13164. end;
  13165. if reg_and_hp1_is_instr and
  13166. (taicpu(p).oper[0]^.typ = top_reg) and
  13167. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13168. (
  13169. (taicpu(hp1).opcode = taicpu(p).opcode)
  13170. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13171. {$ifdef x86_64}
  13172. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13173. {$endif x86_64}
  13174. ) then
  13175. begin
  13176. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13177. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13178. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13179. begin
  13180. {
  13181. For example:
  13182. movzbw %al,%ax
  13183. movzwl %ax,%eax
  13184. Compress into:
  13185. movzbl %al,%eax
  13186. }
  13187. RegUsed := False;
  13188. case taicpu(p).opsize of
  13189. S_BW:
  13190. case taicpu(hp1).opsize of
  13191. S_WL:
  13192. begin
  13193. taicpu(p).opsize := S_BL;
  13194. RegUsed := True;
  13195. end;
  13196. {$ifdef x86_64}
  13197. S_WQ:
  13198. begin
  13199. if taicpu(p).opcode = A_MOVZX then
  13200. begin
  13201. taicpu(p).opsize := S_BL;
  13202. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13203. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13204. end
  13205. else
  13206. taicpu(p).opsize := S_BQ;
  13207. RegUsed := True;
  13208. end;
  13209. {$endif x86_64}
  13210. else
  13211. ;
  13212. end;
  13213. {$ifdef x86_64}
  13214. S_BL:
  13215. case taicpu(hp1).opsize of
  13216. S_LQ:
  13217. begin
  13218. if taicpu(p).opcode = A_MOVZX then
  13219. begin
  13220. taicpu(p).opsize := S_BL;
  13221. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13222. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13223. end
  13224. else
  13225. taicpu(p).opsize := S_BQ;
  13226. RegUsed := True;
  13227. end;
  13228. else
  13229. ;
  13230. end;
  13231. S_WL:
  13232. case taicpu(hp1).opsize of
  13233. S_LQ:
  13234. begin
  13235. if taicpu(p).opcode = A_MOVZX then
  13236. begin
  13237. taicpu(p).opsize := S_WL;
  13238. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13239. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13240. end
  13241. else
  13242. taicpu(p).opsize := S_WQ;
  13243. RegUsed := True;
  13244. end;
  13245. else
  13246. ;
  13247. end;
  13248. {$endif x86_64}
  13249. else
  13250. ;
  13251. end;
  13252. if RegUsed then
  13253. begin
  13254. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13255. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13256. RemoveInstruction(hp1);
  13257. Result := True;
  13258. Exit;
  13259. end;
  13260. end;
  13261. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13262. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13263. GetNextInstruction(hp1, hp2) and
  13264. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13265. (
  13266. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13267. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13268. {$ifdef x86_64}
  13269. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13270. {$endif x86_64}
  13271. ) and
  13272. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13273. (
  13274. (
  13275. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13276. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13277. ) or
  13278. (
  13279. { Only allow the operands in reverse order for TEST instructions }
  13280. (taicpu(hp2).opcode = A_TEST) and
  13281. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13282. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13283. )
  13284. ) then
  13285. begin
  13286. {
  13287. For example:
  13288. movzbl %al,%eax
  13289. movzbl (ref),%edx
  13290. andl %edx,%eax
  13291. (%edx deallocated)
  13292. Change to:
  13293. andb (ref),%al
  13294. movzbl %al,%eax
  13295. Rules are:
  13296. - First two instructions have the same opcode and opsize
  13297. - First instruction's operands are the same super-register
  13298. - Second instruction operates on a different register
  13299. - Third instruction is AND, OR, XOR or TEST
  13300. - Third instruction's operands are the destination registers of the first two instructions
  13301. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13302. - Second instruction's destination register is deallocated afterwards
  13303. }
  13304. TransferUsedRegs(TmpUsedRegs);
  13305. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13306. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13307. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13308. begin
  13309. case taicpu(p).opsize of
  13310. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13311. NewSize := S_B;
  13312. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13313. NewSize := S_W;
  13314. {$ifdef x86_64}
  13315. S_LQ:
  13316. NewSize := S_L;
  13317. {$endif x86_64}
  13318. else
  13319. InternalError(2021120301);
  13320. end;
  13321. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13322. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13323. taicpu(hp2).opsize := NewSize;
  13324. RemoveInstruction(hp1);
  13325. { With TEST, it's best to keep the MOVX instruction at the top }
  13326. if (taicpu(hp2).opcode <> A_TEST) then
  13327. begin
  13328. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13329. asml.Remove(p);
  13330. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13331. asml.InsertAfter(p, hp2);
  13332. p := hp2;
  13333. end
  13334. else
  13335. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13336. Result := True;
  13337. Exit;
  13338. end;
  13339. end;
  13340. end;
  13341. if taicpu(p).opcode=A_MOVZX then
  13342. begin
  13343. { removes superfluous And's after movzx's }
  13344. if reg_and_hp1_is_instr and
  13345. (taicpu(hp1).opcode = A_AND) and
  13346. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13347. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13348. {$ifdef x86_64}
  13349. { check for implicit extension to 64 bit }
  13350. or
  13351. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13352. (taicpu(hp1).opsize=S_Q) and
  13353. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13354. )
  13355. {$endif x86_64}
  13356. )
  13357. then
  13358. begin
  13359. case taicpu(p).opsize Of
  13360. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13361. if (taicpu(hp1).oper[0]^.val = $ff) then
  13362. begin
  13363. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13364. RemoveInstruction(hp1);
  13365. Result:=true;
  13366. exit;
  13367. end;
  13368. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13369. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13370. begin
  13371. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13372. RemoveInstruction(hp1);
  13373. Result:=true;
  13374. exit;
  13375. end;
  13376. {$ifdef x86_64}
  13377. S_LQ:
  13378. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13379. begin
  13380. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13381. RemoveInstruction(hp1);
  13382. Result:=true;
  13383. exit;
  13384. end;
  13385. {$endif x86_64}
  13386. else
  13387. ;
  13388. end;
  13389. { we cannot get rid of the and, but can we get rid of the movz ?}
  13390. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13391. begin
  13392. case taicpu(p).opsize Of
  13393. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13394. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13395. begin
  13396. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13397. RemoveCurrentP(p,hp1);
  13398. Result:=true;
  13399. exit;
  13400. end;
  13401. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13402. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13403. begin
  13404. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13405. RemoveCurrentP(p,hp1);
  13406. Result:=true;
  13407. exit;
  13408. end;
  13409. {$ifdef x86_64}
  13410. S_LQ:
  13411. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13412. begin
  13413. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13414. RemoveCurrentP(p,hp1);
  13415. Result:=true;
  13416. exit;
  13417. end;
  13418. {$endif x86_64}
  13419. else
  13420. ;
  13421. end;
  13422. end;
  13423. end;
  13424. { changes some movzx constructs to faster synonyms (all examples
  13425. are given with eax/ax, but are also valid for other registers)}
  13426. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13427. begin
  13428. case taicpu(p).opsize of
  13429. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13430. (the machine code is equivalent to movzbl %al,%eax), but the
  13431. code generator still generates that assembler instruction and
  13432. it is silently converted. This should probably be checked.
  13433. [Kit] }
  13434. S_BW:
  13435. begin
  13436. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13437. (
  13438. not IsMOVZXAcceptable
  13439. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13440. or (
  13441. (cs_opt_size in current_settings.optimizerswitches) and
  13442. (taicpu(p).oper[1]^.reg = NR_AX)
  13443. )
  13444. ) then
  13445. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13446. begin
  13447. DebugMsg(SPeepholeOptimization + 'var7',p);
  13448. taicpu(p).opcode := A_AND;
  13449. taicpu(p).changeopsize(S_W);
  13450. taicpu(p).loadConst(0,$ff);
  13451. Result := True;
  13452. end
  13453. else if not IsMOVZXAcceptable and
  13454. GetNextInstruction(p, hp1) and
  13455. (tai(hp1).typ = ait_instruction) and
  13456. (taicpu(hp1).opcode = A_AND) and
  13457. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13458. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13459. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13460. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13461. begin
  13462. DebugMsg(SPeepholeOptimization + 'var8',p);
  13463. taicpu(p).opcode := A_MOV;
  13464. taicpu(p).changeopsize(S_W);
  13465. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13466. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13467. Result := True;
  13468. end;
  13469. end;
  13470. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13471. S_BL:
  13472. if not IsMOVZXAcceptable then
  13473. begin
  13474. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13475. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13476. begin
  13477. DebugMsg(SPeepholeOptimization + 'var9',p);
  13478. taicpu(p).opcode := A_AND;
  13479. taicpu(p).changeopsize(S_L);
  13480. taicpu(p).loadConst(0,$ff);
  13481. Result := True;
  13482. end
  13483. else if GetNextInstruction(p, hp1) and
  13484. (tai(hp1).typ = ait_instruction) and
  13485. (taicpu(hp1).opcode = A_AND) and
  13486. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13487. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13488. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13489. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13490. begin
  13491. DebugMsg(SPeepholeOptimization + 'var10',p);
  13492. taicpu(p).opcode := A_MOV;
  13493. taicpu(p).changeopsize(S_L);
  13494. { do not use R_SUBWHOLE
  13495. as movl %rdx,%eax
  13496. is invalid in assembler PM }
  13497. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13498. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13499. Result := True;
  13500. end;
  13501. end;
  13502. {$endif i8086}
  13503. S_WL:
  13504. if not IsMOVZXAcceptable then
  13505. begin
  13506. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13507. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13508. begin
  13509. DebugMsg(SPeepholeOptimization + 'var11',p);
  13510. taicpu(p).opcode := A_AND;
  13511. taicpu(p).changeopsize(S_L);
  13512. taicpu(p).loadConst(0,$ffff);
  13513. Result := True;
  13514. end
  13515. else if GetNextInstruction(p, hp1) and
  13516. (tai(hp1).typ = ait_instruction) and
  13517. (taicpu(hp1).opcode = A_AND) and
  13518. (taicpu(hp1).oper[0]^.typ = top_const) and
  13519. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13520. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13521. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13522. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13523. begin
  13524. DebugMsg(SPeepholeOptimization + 'var12',p);
  13525. taicpu(p).opcode := A_MOV;
  13526. taicpu(p).changeopsize(S_L);
  13527. { do not use R_SUBWHOLE
  13528. as movl %rdx,%eax
  13529. is invalid in assembler PM }
  13530. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13531. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13532. Result := True;
  13533. end;
  13534. end;
  13535. else
  13536. InternalError(2017050705);
  13537. end;
  13538. end
  13539. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13540. begin
  13541. if GetNextInstruction(p, hp1) and
  13542. (tai(hp1).typ = ait_instruction) and
  13543. (taicpu(hp1).opcode = A_AND) and
  13544. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13545. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13546. begin
  13547. case taicpu(p).opsize Of
  13548. S_BL:
  13549. if (taicpu(hp1).opsize <> S_L) or
  13550. (taicpu(hp1).oper[0]^.val > $FF) then
  13551. begin
  13552. DebugMsg(SPeepholeOptimization + 'var13',p);
  13553. taicpu(hp1).changeopsize(S_L);
  13554. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13555. Include(OptsToCheck, aoc_ForceNewIteration);
  13556. end;
  13557. S_WL:
  13558. if (taicpu(hp1).opsize <> S_L) or
  13559. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13560. begin
  13561. DebugMsg(SPeepholeOptimization + 'var14',p);
  13562. taicpu(hp1).changeopsize(S_L);
  13563. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13564. Include(OptsToCheck, aoc_ForceNewIteration);
  13565. end;
  13566. S_BW:
  13567. if (taicpu(hp1).opsize <> S_W) or
  13568. (taicpu(hp1).oper[0]^.val > $FF) then
  13569. begin
  13570. DebugMsg(SPeepholeOptimization + 'var15',p);
  13571. taicpu(hp1).changeopsize(S_W);
  13572. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13573. Include(OptsToCheck, aoc_ForceNewIteration);
  13574. end;
  13575. else
  13576. Internalerror(2017050704)
  13577. end;
  13578. end;
  13579. end;
  13580. end;
  13581. end;
  13582. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13583. var
  13584. hp1, hp2 : tai;
  13585. MaskLength : Cardinal;
  13586. MaskedBits : TCgInt;
  13587. ActiveReg : TRegister;
  13588. begin
  13589. Result:=false;
  13590. { There are no optimisations for reference targets }
  13591. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13592. Exit;
  13593. while GetNextInstruction(p, hp1) and
  13594. (hp1.typ = ait_instruction) do
  13595. begin
  13596. if (taicpu(p).oper[0]^.typ = top_const) then
  13597. begin
  13598. case taicpu(hp1).opcode of
  13599. A_AND:
  13600. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13601. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13602. { the second register must contain the first one, so compare their subreg types }
  13603. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13604. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13605. { change
  13606. and const1, reg
  13607. and const2, reg
  13608. to
  13609. and (const1 and const2), reg
  13610. }
  13611. begin
  13612. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13613. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13614. RemoveCurrentP(p, hp1);
  13615. Result:=true;
  13616. exit;
  13617. end;
  13618. A_CMP:
  13619. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13620. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13621. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13622. { Just check that the condition on the next instruction is compatible }
  13623. GetNextInstruction(hp1, hp2) and
  13624. (hp2.typ = ait_instruction) and
  13625. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13626. then
  13627. { change
  13628. and 2^n, reg
  13629. cmp 2^n, reg
  13630. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13631. to
  13632. and 2^n, reg
  13633. test reg, reg
  13634. j(~c) / set(~c) / cmov(~c)
  13635. }
  13636. begin
  13637. { Keep TEST instruction in, rather than remove it, because
  13638. it may trigger other optimisations such as MovAndTest2Test }
  13639. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13640. taicpu(hp1).opcode := A_TEST;
  13641. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13642. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13643. Result := True;
  13644. Exit;
  13645. end
  13646. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13647. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13648. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13649. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13650. { change
  13651. and $ff/$ff/$ffff, reg
  13652. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13653. dealloc reg
  13654. to
  13655. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13656. }
  13657. begin
  13658. TransferUsedRegs(TmpUsedRegs);
  13659. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13660. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13661. begin
  13662. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13663. case taicpu(p).oper[0]^.val of
  13664. $ff:
  13665. begin
  13666. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13667. taicpu(hp1).opsize:=S_B;
  13668. end;
  13669. $ffff:
  13670. begin
  13671. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13672. taicpu(hp1).opsize:=S_W;
  13673. end;
  13674. $ffffffff:
  13675. begin
  13676. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13677. taicpu(hp1).opsize:=S_L;
  13678. end;
  13679. else
  13680. Internalerror(2023030401);
  13681. end;
  13682. RemoveCurrentP(p);
  13683. Result := True;
  13684. Exit;
  13685. end;
  13686. end;
  13687. A_MOVZX:
  13688. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13689. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13690. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13691. (
  13692. (
  13693. (taicpu(p).opsize=S_W) and
  13694. (taicpu(hp1).opsize=S_BW)
  13695. ) or
  13696. (
  13697. (taicpu(p).opsize=S_L) and
  13698. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13699. )
  13700. {$ifdef x86_64}
  13701. or
  13702. (
  13703. (taicpu(p).opsize=S_Q) and
  13704. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13705. )
  13706. {$endif x86_64}
  13707. ) then
  13708. begin
  13709. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13710. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13711. ) or
  13712. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13713. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13714. then
  13715. begin
  13716. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13717. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13718. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13719. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13720. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13721. }
  13722. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13723. RemoveInstruction(hp1);
  13724. { See if there are other optimisations possible }
  13725. Continue;
  13726. end;
  13727. end;
  13728. A_SHL:
  13729. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13730. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13731. begin
  13732. {$ifopt R+}
  13733. {$define RANGE_WAS_ON}
  13734. {$R-}
  13735. {$endif}
  13736. { get length of potential and mask }
  13737. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13738. { really a mask? }
  13739. {$ifdef RANGE_WAS_ON}
  13740. {$R+}
  13741. {$endif}
  13742. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13743. { unmasked part shifted out? }
  13744. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13745. begin
  13746. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13747. RemoveCurrentP(p, hp1);
  13748. Result:=true;
  13749. exit;
  13750. end;
  13751. end;
  13752. A_SHR:
  13753. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13754. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13755. (taicpu(hp1).oper[0]^.val <= 63) then
  13756. begin
  13757. { Does SHR combined with the AND cover all the bits?
  13758. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13759. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13760. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13761. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13762. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13763. begin
  13764. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13765. RemoveCurrentP(p, hp1);
  13766. Result := True;
  13767. Exit;
  13768. end;
  13769. end;
  13770. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13771. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13772. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13773. begin
  13774. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13775. (
  13776. (
  13777. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13778. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13779. ) or (
  13780. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13781. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13782. {$ifdef x86_64}
  13783. ) or (
  13784. (taicpu(hp1).opsize = S_LQ) and
  13785. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13786. {$endif x86_64}
  13787. )
  13788. ) then
  13789. begin
  13790. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13791. begin
  13792. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13793. RemoveInstruction(hp1);
  13794. { See if there are other optimisations possible }
  13795. Continue;
  13796. end;
  13797. { The super-registers are the same though.
  13798. Note that this change by itself doesn't improve
  13799. code speed, but it opens up other optimisations. }
  13800. {$ifdef x86_64}
  13801. { Convert 64-bit register to 32-bit }
  13802. case taicpu(hp1).opsize of
  13803. S_BQ:
  13804. begin
  13805. taicpu(hp1).opsize := S_BL;
  13806. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13807. end;
  13808. S_WQ:
  13809. begin
  13810. taicpu(hp1).opsize := S_WL;
  13811. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13812. end
  13813. else
  13814. ;
  13815. end;
  13816. {$endif x86_64}
  13817. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13818. taicpu(hp1).opcode := A_MOVZX;
  13819. { See if there are other optimisations possible }
  13820. Continue;
  13821. end;
  13822. end;
  13823. else
  13824. ;
  13825. end;
  13826. end
  13827. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13828. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13829. begin
  13830. {$ifdef x86_64}
  13831. if (taicpu(p).opsize = S_Q) then
  13832. begin
  13833. { Never necessary }
  13834. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13835. RemoveCurrentP(p, hp1);
  13836. Result := True;
  13837. Exit;
  13838. end;
  13839. {$endif x86_64}
  13840. { Forward check to determine necessity of and %reg,%reg }
  13841. TransferUsedRegs(TmpUsedRegs);
  13842. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13843. { Saves on a bunch of dereferences }
  13844. ActiveReg := taicpu(p).oper[1]^.reg;
  13845. case taicpu(hp1).opcode of
  13846. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13847. if (
  13848. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13849. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13850. ) and
  13851. (
  13852. (taicpu(hp1).opcode <> A_MOV) or
  13853. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13854. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13855. ) and
  13856. not (
  13857. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13858. (taicpu(hp1).opcode = A_MOV) and
  13859. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13860. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13861. ) and
  13862. (
  13863. (
  13864. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13865. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13866. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13867. ) or
  13868. (
  13869. {$ifdef x86_64}
  13870. (
  13871. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13872. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13873. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13874. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13875. ) and
  13876. {$endif x86_64}
  13877. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13878. )
  13879. ) then
  13880. begin
  13881. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13882. RemoveCurrentP(p, hp1);
  13883. Result := True;
  13884. Exit;
  13885. end;
  13886. A_ADD,
  13887. A_AND,
  13888. A_BSF,
  13889. A_BSR,
  13890. A_BTC,
  13891. A_BTR,
  13892. A_BTS,
  13893. A_OR,
  13894. A_SUB,
  13895. A_XOR:
  13896. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13897. if (
  13898. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13899. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13900. ) and
  13901. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13902. begin
  13903. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13904. RemoveCurrentP(p, hp1);
  13905. Result := True;
  13906. Exit;
  13907. end;
  13908. A_CMP,
  13909. A_TEST:
  13910. if (
  13911. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13912. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13913. ) and
  13914. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13915. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13916. begin
  13917. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13918. RemoveCurrentP(p, hp1);
  13919. Result := True;
  13920. Exit;
  13921. end;
  13922. A_BSWAP,
  13923. A_NEG,
  13924. A_NOT:
  13925. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13926. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13927. begin
  13928. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13929. RemoveCurrentP(p, hp1);
  13930. Result := True;
  13931. Exit;
  13932. end;
  13933. else
  13934. ;
  13935. end;
  13936. end;
  13937. if (taicpu(hp1).is_jmp) and
  13938. (taicpu(hp1).opcode<>A_JMP) and
  13939. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13940. begin
  13941. { change
  13942. and x, reg
  13943. jxx
  13944. to
  13945. test x, reg
  13946. jxx
  13947. if reg is deallocated before the
  13948. jump, but only if it's a conditional jump (PFV)
  13949. }
  13950. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13951. taicpu(p).opcode := A_TEST;
  13952. Exit;
  13953. end;
  13954. Break;
  13955. end;
  13956. { Lone AND tests }
  13957. if (taicpu(p).oper[0]^.typ = top_const) then
  13958. begin
  13959. {
  13960. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13961. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13962. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13963. }
  13964. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13965. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13966. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13967. begin
  13968. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13969. if taicpu(p).opsize = S_L then
  13970. begin
  13971. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13972. Result := True;
  13973. end;
  13974. end;
  13975. end;
  13976. { Backward check to determine necessity of and %reg,%reg }
  13977. if (taicpu(p).oper[0]^.typ = top_reg) and
  13978. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13979. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13980. GetLastInstruction(p, hp2) and
  13981. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13982. { Check size of adjacent instruction to determine if the AND is
  13983. effectively a null operation }
  13984. (
  13985. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13986. { Note: Don't include S_Q }
  13987. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13988. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13989. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13990. ) then
  13991. begin
  13992. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13993. { If GetNextInstruction returned False, hp1 will be nil }
  13994. RemoveCurrentP(p, hp1);
  13995. Result := True;
  13996. Exit;
  13997. end;
  13998. end;
  13999. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14000. var
  14001. hp1, hp2: tai;
  14002. NewRef: TReference;
  14003. Distance: Cardinal;
  14004. TempTracking: TAllUsedRegs;
  14005. { This entire nested function is used in an if-statement below, but we
  14006. want to avoid all the used reg transfers and GetNextInstruction calls
  14007. until we really have to check }
  14008. function MemRegisterNotUsedLater: Boolean; inline;
  14009. var
  14010. hp2: tai;
  14011. begin
  14012. TransferUsedRegs(TmpUsedRegs);
  14013. hp2 := p;
  14014. repeat
  14015. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14016. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14017. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14018. end;
  14019. begin
  14020. Result := False;
  14021. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14022. (taicpu(p).oper[1]^.typ = top_reg) then
  14023. begin
  14024. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14025. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14026. (hp1.typ <> ait_instruction) or
  14027. not
  14028. (
  14029. (cs_opt_level3 in current_settings.optimizerswitches) or
  14030. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14031. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14032. ) then
  14033. Exit;
  14034. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14035. addq $x, %rax
  14036. movq %rax, %rdx
  14037. sarq $63, %rdx
  14038. (%rax still in use)
  14039. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14040. leaq $x(%rax),%rdx
  14041. addq $x, %rax
  14042. sarq $63, %rdx
  14043. ...which is okay since it breaks the dependency chain between
  14044. addq and movq, but if OptPass2MOV is called first:
  14045. addq $x, %rax
  14046. cqto
  14047. ...which is better in all ways, taking only 2 cycles to execute
  14048. and much smaller in code size.
  14049. }
  14050. { The extra register tracking is quite strenuous }
  14051. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14052. MatchInstruction(hp1, A_MOV, []) then
  14053. begin
  14054. { Update the register tracking to the MOV instruction }
  14055. CopyUsedRegs(TempTracking);
  14056. hp2 := p;
  14057. repeat
  14058. UpdateUsedRegs(tai(hp2.Next));
  14059. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14060. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14061. OptPass2ADD get called again }
  14062. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14063. begin
  14064. { Reset the tracking to the current instruction }
  14065. RestoreUsedRegs(TempTracking);
  14066. ReleaseUsedRegs(TempTracking);
  14067. Result := True;
  14068. Exit;
  14069. end;
  14070. { Reset the tracking to the current instruction }
  14071. RestoreUsedRegs(TempTracking);
  14072. ReleaseUsedRegs(TempTracking);
  14073. { If OptPass2MOV returned True, we don't need to set Result to
  14074. True if hp1 didn't change because the ADD instruction didn't
  14075. get modified and we'll be evaluating hp1 again when the
  14076. peephole optimizer reaches it }
  14077. end;
  14078. { Change:
  14079. add %reg2,%reg1
  14080. (%reg2 not modified in between)
  14081. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14082. To:
  14083. mov/s/z #(%reg1,%reg2),%reg1
  14084. }
  14085. if (taicpu(p).oper[0]^.typ = top_reg) and
  14086. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14087. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14088. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14089. (
  14090. (
  14091. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14092. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14093. { r/esp cannot be an index }
  14094. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14095. ) or (
  14096. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14097. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14098. )
  14099. ) and (
  14100. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14101. (
  14102. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14103. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14104. MemRegisterNotUsedLater
  14105. )
  14106. ) then
  14107. begin
  14108. if (
  14109. { Instructions are guaranteed to be adjacent on -O2 and under }
  14110. (cs_opt_level3 in current_settings.optimizerswitches) and
  14111. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14112. ) then
  14113. begin
  14114. { If the other register is used in between, move the MOV
  14115. instruction to right after the ADD instruction so a
  14116. saving can still be made }
  14117. Asml.Remove(hp1);
  14118. Asml.InsertAfter(hp1, p);
  14119. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14120. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14121. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14122. RemoveCurrentp(p, hp1);
  14123. end
  14124. else
  14125. begin
  14126. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14127. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14128. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14129. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14130. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14131. { hp1 may not be the immediate next instruction under -O3 }
  14132. RemoveCurrentp(p)
  14133. else
  14134. RemoveCurrentp(p, hp1);
  14135. end;
  14136. Result := True;
  14137. Exit;
  14138. end;
  14139. { Change:
  14140. addl/q $x,%reg1
  14141. movl/q %reg1,%reg2
  14142. To:
  14143. leal/q $x(%reg1),%reg2
  14144. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14145. Breaks the dependency chain.
  14146. }
  14147. if (taicpu(p).oper[0]^.typ = top_const) and
  14148. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14149. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14150. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14151. (
  14152. { Instructions are guaranteed to be adjacent on -O2 and under }
  14153. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14154. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14155. ) then
  14156. begin
  14157. TransferUsedRegs(TmpUsedRegs);
  14158. hp2 := p;
  14159. repeat
  14160. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14161. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14162. if (
  14163. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14164. not (cs_opt_size in current_settings.optimizerswitches) or
  14165. (
  14166. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14167. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14168. )
  14169. ) then
  14170. begin
  14171. { Change the MOV instruction to a LEA instruction, and update the
  14172. first operand }
  14173. reference_reset(NewRef, 1, []);
  14174. NewRef.base := taicpu(p).oper[1]^.reg;
  14175. NewRef.scalefactor := 1;
  14176. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14177. taicpu(hp1).opcode := A_LEA;
  14178. taicpu(hp1).loadref(0, NewRef);
  14179. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14180. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14181. begin
  14182. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14183. { Move what is now the LEA instruction to before the ADD instruction }
  14184. Asml.Remove(hp1);
  14185. Asml.InsertBefore(hp1, p);
  14186. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14187. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14188. p := hp1;
  14189. end
  14190. else
  14191. begin
  14192. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14193. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14194. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14195. { hp1 may not be the immediate next instruction under -O3 }
  14196. RemoveCurrentp(p)
  14197. else
  14198. RemoveCurrentp(p, hp1);
  14199. end;
  14200. Result := True;
  14201. end;
  14202. end;
  14203. end;
  14204. end;
  14205. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14206. var
  14207. SubReg: TSubRegister;
  14208. hp1, hp2: tai;
  14209. CallJmp: Boolean;
  14210. begin
  14211. Result := False;
  14212. CallJmp := False;
  14213. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14214. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14215. with taicpu(p).oper[0]^.ref^ do
  14216. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14217. if (offset = 0) then
  14218. begin
  14219. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14220. begin
  14221. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14222. taicpu(p).opcode := A_ADD;
  14223. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14224. Result := True;
  14225. end
  14226. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14227. begin
  14228. if (base <> NR_NO) then
  14229. begin
  14230. if (scalefactor <= 1) then
  14231. begin
  14232. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14233. taicpu(p).opcode := A_ADD;
  14234. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14235. Result := True;
  14236. end;
  14237. end
  14238. else
  14239. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14240. if (scalefactor in [2, 4, 8]) then
  14241. begin
  14242. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14243. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14244. taicpu(p).opcode := A_SHL;
  14245. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14246. Result := True;
  14247. end;
  14248. end;
  14249. end
  14250. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14251. lot of latency, so break off the offset if %reg3 is used soon
  14252. afterwards }
  14253. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14254. { If 3-component addresses don't have additional latency, don't
  14255. perform this optimisation }
  14256. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14257. GetNextInstruction(p, hp1) and
  14258. (hp1.typ = ait_instruction) and
  14259. (
  14260. (
  14261. { Permit jumps and calls since they have a larger degree of overhead }
  14262. (
  14263. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14264. (
  14265. { ... unless the register specifies the location }
  14266. (taicpu(hp1).ops > 0) and
  14267. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14268. )
  14269. ) and
  14270. (
  14271. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14272. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14273. )
  14274. )
  14275. or
  14276. (
  14277. { Check up to two instructions ahead }
  14278. GetNextInstruction(hp1, hp2) and
  14279. (hp2.typ = ait_instruction) and
  14280. (
  14281. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14282. (
  14283. { Same as above }
  14284. (taicpu(hp2).ops > 0) and
  14285. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14286. )
  14287. ) and
  14288. (
  14289. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14290. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14291. )
  14292. )
  14293. ) then
  14294. begin
  14295. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14296. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14297. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14298. offset := 0;
  14299. if Assigned(symbol) or Assigned(relsymbol) then
  14300. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14301. else
  14302. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14303. { Inserting before the next instruction rather than after the
  14304. current instruction gives more accurate register tracking }
  14305. asml.InsertBefore(hp2, hp1);
  14306. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14307. Result := True;
  14308. end;
  14309. end;
  14310. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14311. var
  14312. hp1, hp2: tai;
  14313. NewRef: TReference;
  14314. Distance: Cardinal;
  14315. TempTracking: TAllUsedRegs;
  14316. begin
  14317. Result := False;
  14318. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14319. MatchOpType(taicpu(p),top_const,top_reg) then
  14320. begin
  14321. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14322. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14323. (hp1.typ <> ait_instruction) or
  14324. not
  14325. (
  14326. (cs_opt_level3 in current_settings.optimizerswitches) or
  14327. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14328. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14329. ) then
  14330. Exit;
  14331. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14332. subq $x, %rax
  14333. movq %rax, %rdx
  14334. sarq $63, %rdx
  14335. (%rax still in use)
  14336. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14337. leaq $-x(%rax),%rdx
  14338. movq $x, %rax
  14339. sarq $63, %rdx
  14340. ...which is okay since it breaks the dependency chain between
  14341. subq and movq, but if OptPass2MOV is called first:
  14342. subq $x, %rax
  14343. cqto
  14344. ...which is better in all ways, taking only 2 cycles to execute
  14345. and much smaller in code size.
  14346. }
  14347. { The extra register tracking is quite strenuous }
  14348. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14349. MatchInstruction(hp1, A_MOV, []) then
  14350. begin
  14351. { Update the register tracking to the MOV instruction }
  14352. CopyUsedRegs(TempTracking);
  14353. hp2 := p;
  14354. repeat
  14355. UpdateUsedRegs(tai(hp2.Next));
  14356. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14357. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14358. OptPass2SUB get called again }
  14359. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14360. begin
  14361. { Reset the tracking to the current instruction }
  14362. RestoreUsedRegs(TempTracking);
  14363. ReleaseUsedRegs(TempTracking);
  14364. Result := True;
  14365. Exit;
  14366. end;
  14367. { Reset the tracking to the current instruction }
  14368. RestoreUsedRegs(TempTracking);
  14369. ReleaseUsedRegs(TempTracking);
  14370. { If OptPass2MOV returned True, we don't need to set Result to
  14371. True if hp1 didn't change because the SUB instruction didn't
  14372. get modified and we'll be evaluating hp1 again when the
  14373. peephole optimizer reaches it }
  14374. end;
  14375. { Change:
  14376. subl/q $x,%reg1
  14377. movl/q %reg1,%reg2
  14378. To:
  14379. leal/q $-x(%reg1),%reg2
  14380. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14381. Breaks the dependency chain and potentially permits the removal of
  14382. a CMP instruction if one follows.
  14383. }
  14384. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14385. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14386. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14387. (
  14388. { Instructions are guaranteed to be adjacent on -O2 and under }
  14389. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14390. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14391. ) then
  14392. begin
  14393. TransferUsedRegs(TmpUsedRegs);
  14394. hp2 := p;
  14395. repeat
  14396. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14397. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14398. if (
  14399. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14400. not (cs_opt_size in current_settings.optimizerswitches) or
  14401. (
  14402. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14403. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14404. )
  14405. ) then
  14406. begin
  14407. { Change the MOV instruction to a LEA instruction, and update the
  14408. first operand }
  14409. reference_reset(NewRef, 1, []);
  14410. NewRef.base := taicpu(p).oper[1]^.reg;
  14411. NewRef.scalefactor := 1;
  14412. NewRef.offset := -taicpu(p).oper[0]^.val;
  14413. taicpu(hp1).opcode := A_LEA;
  14414. taicpu(hp1).loadref(0, NewRef);
  14415. TransferUsedRegs(TmpUsedRegs);
  14416. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14417. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14418. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14419. begin
  14420. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14421. { Move what is now the LEA instruction to before the SUB instruction }
  14422. Asml.Remove(hp1);
  14423. Asml.InsertBefore(hp1, p);
  14424. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14425. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14426. p := hp1;
  14427. end
  14428. else
  14429. begin
  14430. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14431. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14432. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14433. { hp1 may not be the immediate next instruction under -O3 }
  14434. RemoveCurrentp(p)
  14435. else
  14436. RemoveCurrentp(p, hp1);
  14437. end;
  14438. Result := True;
  14439. end;
  14440. end;
  14441. end;
  14442. end;
  14443. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14444. begin
  14445. { we can skip all instructions not messing with the stack pointer }
  14446. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14447. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14448. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14449. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14450. ({(taicpu(hp1).ops=0) or }
  14451. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14452. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14453. ) and }
  14454. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14455. )
  14456. ) do
  14457. GetNextInstruction(hp1,hp1);
  14458. Result:=assigned(hp1);
  14459. end;
  14460. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14461. var
  14462. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14463. begin
  14464. Result:=false;
  14465. hp5:=nil;
  14466. hp6:=nil;
  14467. hp7:=nil;
  14468. hp8:=nil;
  14469. { replace
  14470. leal(q) x(<stackpointer>),<stackpointer>
  14471. <optional .seh_stackalloc ...>
  14472. <optional .seh_endprologue ...>
  14473. call procname
  14474. <optional NOP>
  14475. leal(q) -x(<stackpointer>),<stackpointer>
  14476. <optional VZEROUPPER>
  14477. ret
  14478. by
  14479. jmp procname
  14480. but do it only on level 4 because it destroys stack back traces
  14481. }
  14482. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14483. MatchOpType(taicpu(p),top_ref,top_reg) and
  14484. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14485. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14486. { the -8, -24, -40 are not required, but bail out early if possible,
  14487. higher values are unlikely }
  14488. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14489. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14490. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14491. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14492. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14493. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14494. GetNextInstruction(p, hp1) and
  14495. { Take a copy of hp1 }
  14496. SetAndTest(hp1, hp4) and
  14497. { trick to skip label }
  14498. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14499. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14500. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14501. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14502. SkipSimpleInstructions(hp1) and
  14503. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14504. GetNextInstruction(hp1, hp2) and
  14505. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14506. { skip nop instruction on win64 }
  14507. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14508. SetAndTest(hp2,hp6) and
  14509. GetNextInstruction(hp2,hp2) and
  14510. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14511. ) and
  14512. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14513. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14514. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14515. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14516. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14517. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14518. { Segment register will be NR_NO }
  14519. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14520. GetNextInstruction(hp2, hp3) and
  14521. { trick to skip label }
  14522. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14523. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14524. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14525. SetAndTest(hp3,hp5) and
  14526. GetNextInstruction(hp3,hp3) and
  14527. MatchInstruction(hp3,A_RET,[S_NO])
  14528. )
  14529. ) and
  14530. (taicpu(hp3).ops=0) then
  14531. begin
  14532. taicpu(hp1).opcode := A_JMP;
  14533. taicpu(hp1).is_jmp := true;
  14534. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14535. { search for the stackalloc directive and remove it }
  14536. hp7:=tai(p.next);
  14537. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14538. begin
  14539. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14540. begin
  14541. { sanity check }
  14542. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14543. Internalerror(2024012201);
  14544. hp8:=tai(hp7.next);
  14545. RemoveInstruction(tai(hp7));
  14546. hp7:=hp8;
  14547. break;
  14548. end
  14549. else
  14550. hp7:=tai(hp7.next);
  14551. end;
  14552. RemoveCurrentP(p, hp4);
  14553. RemoveInstruction(hp2);
  14554. RemoveInstruction(hp3);
  14555. { if there is a vzeroupper instruction then move it before the jmp }
  14556. if Assigned(hp5) then
  14557. begin
  14558. AsmL.Remove(hp5);
  14559. ASmL.InsertBefore(hp5,hp1)
  14560. end;
  14561. { remove nop on win64 }
  14562. if Assigned(hp6) then
  14563. RemoveInstruction(hp6);
  14564. Result:=true;
  14565. end;
  14566. end;
  14567. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14568. {$ifdef x86_64}
  14569. var
  14570. hp1, hp2, hp3, hp4, hp5: tai;
  14571. {$endif x86_64}
  14572. begin
  14573. Result:=false;
  14574. {$ifdef x86_64}
  14575. hp5:=nil;
  14576. { replace
  14577. push %rax
  14578. call procname
  14579. pop %rcx
  14580. ret
  14581. by
  14582. jmp procname
  14583. but do it only on level 4 because it destroys stack back traces
  14584. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14585. for all supported calling conventions
  14586. }
  14587. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14588. MatchOpType(taicpu(p),top_reg) and
  14589. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14590. GetNextInstruction(p, hp1) and
  14591. { Take a copy of hp1 }
  14592. SetAndTest(hp1, hp4) and
  14593. { trick to skip label }
  14594. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14595. SkipSimpleInstructions(hp1) and
  14596. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14597. GetNextInstruction(hp1, hp2) and
  14598. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14599. MatchOpType(taicpu(hp2),top_reg) and
  14600. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14601. GetNextInstruction(hp2, hp3) and
  14602. { trick to skip label }
  14603. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14604. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14605. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14606. SetAndTest(hp3,hp5) and
  14607. GetNextInstruction(hp3,hp3) and
  14608. MatchInstruction(hp3,A_RET,[S_NO])
  14609. )
  14610. ) and
  14611. (taicpu(hp3).ops=0) then
  14612. begin
  14613. taicpu(hp1).opcode := A_JMP;
  14614. taicpu(hp1).is_jmp := true;
  14615. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14616. RemoveCurrentP(p, hp4);
  14617. RemoveInstruction(hp2);
  14618. RemoveInstruction(hp3);
  14619. if Assigned(hp5) then
  14620. begin
  14621. AsmL.Remove(hp5);
  14622. ASmL.InsertBefore(hp5,hp1)
  14623. end;
  14624. Result:=true;
  14625. end;
  14626. {$endif x86_64}
  14627. end;
  14628. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14629. var
  14630. Value, RegName: string;
  14631. hp1: tai;
  14632. begin
  14633. Result:=false;
  14634. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14635. begin
  14636. case taicpu(p).oper[0]^.val of
  14637. 0:
  14638. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14639. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14640. (
  14641. { See if we can still convert the instruction }
  14642. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14643. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14644. ) then
  14645. begin
  14646. { change "mov $0,%reg" into "xor %reg,%reg" }
  14647. taicpu(p).opcode := A_XOR;
  14648. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14649. Result := True;
  14650. {$ifdef x86_64}
  14651. end
  14652. else if (taicpu(p).opsize = S_Q) then
  14653. begin
  14654. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14655. { The actual optimization }
  14656. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14657. taicpu(p).changeopsize(S_L);
  14658. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14659. Result := True;
  14660. end;
  14661. $1..$FFFFFFFF:
  14662. begin
  14663. { Code size reduction by J. Gareth "Kit" Moreton }
  14664. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14665. case taicpu(p).opsize of
  14666. S_Q:
  14667. begin
  14668. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14669. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14670. { The actual optimization }
  14671. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14672. taicpu(p).changeopsize(S_L);
  14673. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14674. Result := True;
  14675. end;
  14676. else
  14677. { Do nothing };
  14678. end;
  14679. {$endif x86_64}
  14680. end;
  14681. -1:
  14682. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14683. if (cs_opt_size in current_settings.optimizerswitches) and
  14684. (taicpu(p).opsize <> S_B) and
  14685. (
  14686. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14687. (
  14688. { See if we can still convert the instruction }
  14689. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14690. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14691. )
  14692. ) then
  14693. begin
  14694. { change "mov $-1,%reg" into "or $-1,%reg" }
  14695. { NOTES:
  14696. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14697. - This operation creates a false dependency on the register, so only do it when optimising for size
  14698. - It is possible to set memory operands using this method, but this creates an even greater false dependency, so don't do this at all
  14699. }
  14700. taicpu(p).opcode := A_OR;
  14701. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14702. Result := True;
  14703. end;
  14704. else
  14705. { Do nothing };
  14706. end;
  14707. end;
  14708. end;
  14709. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14710. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14711. begin
  14712. Result := False;
  14713. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14714. Exit;
  14715. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14716. so don't bother optimising }
  14717. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14718. Exit;
  14719. if (taicpu(p).oper[0]^.typ <> top_const) or
  14720. { If the value can fit into an 8-bit signed integer, a smaller
  14721. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14722. falls within this range }
  14723. (
  14724. (taicpu(p).oper[0]^.val > -128) and
  14725. (taicpu(p).oper[0]^.val <= 127)
  14726. ) then
  14727. Exit;
  14728. { If we're optimising for size, this is acceptable }
  14729. if (cs_opt_size in current_settings.optimizerswitches) then
  14730. Exit(True);
  14731. if (taicpu(p).oper[1]^.typ = top_reg) and
  14732. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14733. Exit(True);
  14734. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14735. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14736. Exit(True);
  14737. end;
  14738. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14739. var
  14740. hp1: tai;
  14741. Value: TCGInt;
  14742. begin
  14743. Result := False;
  14744. if MatchOpType(taicpu(p), top_const, top_reg) then
  14745. begin
  14746. { Detect:
  14747. andw x, %ax (0 <= x < $8000)
  14748. ...
  14749. movzwl %ax,%eax
  14750. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14751. }
  14752. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14753. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14754. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14755. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14756. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14757. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14758. begin
  14759. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14760. taicpu(hp1).opcode := A_CWDE;
  14761. taicpu(hp1).clearop(0);
  14762. taicpu(hp1).clearop(1);
  14763. taicpu(hp1).ops := 0;
  14764. { A change was made, but not with p, so don't set Result, but
  14765. notify the compiler that a change was made }
  14766. Include(OptsToCheck, aoc_ForceNewIteration);
  14767. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14768. end;
  14769. end;
  14770. { If "not x" is a power of 2 (popcnt = 1), change:
  14771. and $x, %reg/ref
  14772. To:
  14773. btr lb(x), %reg/ref
  14774. }
  14775. if IsBTXAcceptable(p) and
  14776. (
  14777. { Make sure a TEST doesn't follow that plays with the register }
  14778. not GetNextInstruction(p, hp1) or
  14779. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14780. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14781. ) then
  14782. begin
  14783. {$push}{$R-}{$Q-}
  14784. { Value is a sign-extended 32-bit integer - just correct it
  14785. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14786. checks to see if this operand is an immediate. }
  14787. Value := not taicpu(p).oper[0]^.val;
  14788. {$pop}
  14789. {$ifdef x86_64}
  14790. if taicpu(p).opsize = S_L then
  14791. {$endif x86_64}
  14792. Value := Value and $FFFFFFFF;
  14793. if (PopCnt(QWord(Value)) = 1) then
  14794. begin
  14795. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14796. taicpu(p).opcode := A_BTR;
  14797. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14798. Result := True;
  14799. Exit;
  14800. end;
  14801. end;
  14802. end;
  14803. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14804. begin
  14805. Result := False;
  14806. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14807. Exit;
  14808. { Convert:
  14809. movswl %ax,%eax -> cwtl
  14810. movslq %eax,%rax -> cdqe
  14811. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14812. refer to the same opcode and depends only on the assembler's
  14813. current operand-size attribute. [Kit]
  14814. }
  14815. with taicpu(p) do
  14816. case opsize of
  14817. S_WL:
  14818. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14819. begin
  14820. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14821. opcode := A_CWDE;
  14822. clearop(0);
  14823. clearop(1);
  14824. ops := 0;
  14825. Result := True;
  14826. end;
  14827. {$ifdef x86_64}
  14828. S_LQ:
  14829. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14830. begin
  14831. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14832. opcode := A_CDQE;
  14833. clearop(0);
  14834. clearop(1);
  14835. ops := 0;
  14836. Result := True;
  14837. end;
  14838. {$endif x86_64}
  14839. else
  14840. ;
  14841. end;
  14842. end;
  14843. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14844. var
  14845. hp1, hp2: tai;
  14846. IdentityMask, Shift: TCGInt;
  14847. LimitSize: Topsize;
  14848. DoNotMerge: Boolean;
  14849. begin
  14850. Result := False;
  14851. { All these optimisations work on "shr const,%reg" }
  14852. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14853. Exit;
  14854. DoNotMerge := False;
  14855. Shift := taicpu(p).oper[0]^.val;
  14856. LimitSize := taicpu(p).opsize;
  14857. hp1 := p;
  14858. repeat
  14859. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14860. Break;
  14861. { Detect:
  14862. shr x, %reg
  14863. and y, %reg
  14864. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14865. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14866. }
  14867. case taicpu(hp1).opcode of
  14868. A_AND:
  14869. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14870. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14871. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14872. begin
  14873. { Make sure the FLAGS register isn't in use }
  14874. TransferUsedRegs(TmpUsedRegs);
  14875. hp2 := p;
  14876. repeat
  14877. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14878. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14879. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14880. begin
  14881. { Generate the identity mask }
  14882. case taicpu(p).opsize of
  14883. S_B:
  14884. IdentityMask := $FF shr Shift;
  14885. S_W:
  14886. IdentityMask := $FFFF shr Shift;
  14887. S_L:
  14888. IdentityMask := $FFFFFFFF shr Shift;
  14889. {$ifdef x86_64}
  14890. S_Q:
  14891. { We need to force the operands to be unsigned 64-bit
  14892. integers otherwise the wrong value is generated }
  14893. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14894. {$endif x86_64}
  14895. else
  14896. InternalError(2022081501);
  14897. end;
  14898. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14899. begin
  14900. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14901. { All the possible 1 bits are covered, so we can remove the AND }
  14902. hp2 := tai(hp1.Previous);
  14903. RemoveInstruction(hp1);
  14904. { p wasn't actually changed, so don't set Result to True,
  14905. but a change was nonetheless made elsewhere }
  14906. Include(OptsToCheck, aoc_ForceNewIteration);
  14907. { Do another pass in case other AND or MOVZX instructions
  14908. follow }
  14909. hp1 := hp2;
  14910. Continue;
  14911. end;
  14912. end;
  14913. end;
  14914. A_TEST, A_CMP, A_Jcc:
  14915. { Skip over conditional jumps and relevant comparisons }
  14916. Continue;
  14917. A_MOVZX:
  14918. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14919. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14920. begin
  14921. { Since the original register is being read as is, subsequent
  14922. SHRs must not be merged at this point }
  14923. DoNotMerge := True;
  14924. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14925. begin
  14926. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14927. begin
  14928. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14929. { All the possible 1 bits are covered, so we can remove the AND }
  14930. hp2 := tai(hp1.Previous);
  14931. RemoveInstruction(hp1);
  14932. hp1 := hp2;
  14933. end
  14934. else { Different register target }
  14935. begin
  14936. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14937. taicpu(hp1).opcode := A_MOV;
  14938. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14939. case taicpu(hp1).opsize of
  14940. S_BW:
  14941. taicpu(hp1).opsize := S_W;
  14942. S_BL, S_WL:
  14943. taicpu(hp1).opsize := S_L;
  14944. else
  14945. InternalError(2022081503);
  14946. end;
  14947. end;
  14948. end
  14949. else if (Shift > 0) and
  14950. (taicpu(p).opsize = S_W) and
  14951. (taicpu(hp1).opsize = S_WL) and
  14952. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14953. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14954. begin
  14955. { Detect:
  14956. shr x, %ax (x > 0)
  14957. ...
  14958. movzwl %ax,%eax
  14959. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14960. }
  14961. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14962. taicpu(hp1).opcode := A_CWDE;
  14963. taicpu(hp1).clearop(0);
  14964. taicpu(hp1).clearop(1);
  14965. taicpu(hp1).ops := 0;
  14966. end;
  14967. { Move onto the next instruction }
  14968. Continue;
  14969. end;
  14970. A_SHL, A_SAL, A_SHR:
  14971. if (taicpu(hp1).opsize <= LimitSize) and
  14972. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14973. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14974. begin
  14975. { Make sure the sizes don't exceed the register size limit
  14976. (measured by the shift value falling below the limit) }
  14977. if taicpu(hp1).opsize < LimitSize then
  14978. LimitSize := taicpu(hp1).opsize;
  14979. if taicpu(hp1).opcode = A_SHR then
  14980. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14981. else
  14982. begin
  14983. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14984. DoNotMerge := True;
  14985. end;
  14986. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14987. Break;
  14988. { Since we've established that the combined shift is within
  14989. limits, we can actually combine the adjacent SHR
  14990. instructions even if they're different sizes }
  14991. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14992. begin
  14993. hp2 := tai(hp1.Previous);
  14994. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14995. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14996. RemoveInstruction(hp1);
  14997. hp1 := hp2;
  14998. end;
  14999. { Move onto the next instruction }
  15000. Continue;
  15001. end;
  15002. else
  15003. ;
  15004. end;
  15005. Break;
  15006. until False;
  15007. { Detect the following (looking backwards):
  15008. shr %cl,%reg
  15009. shr x, %reg
  15010. Swap the two SHR instructions to minimise a pipeline stall.
  15011. }
  15012. if GetLastInstruction(p, hp1) and
  15013. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15014. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15015. { First operand will be %cl }
  15016. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15017. { Just to be sure }
  15018. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15019. begin
  15020. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15021. { Moving the entries this way ensures the register tracking remains correct }
  15022. Asml.Remove(p);
  15023. Asml.InsertBefore(p, hp1);
  15024. p := hp1;
  15025. { Don't set Result to True because the current instruction is now
  15026. "shr %cl,%reg" and there's nothing more we can do with it }
  15027. end;
  15028. end;
  15029. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15030. var
  15031. hp1, hp2: tai;
  15032. Opposite, SecondOpposite: TAsmOp;
  15033. NewCond: TAsmCond;
  15034. begin
  15035. Result := False;
  15036. { Change:
  15037. add/sub 128,(dest)
  15038. To:
  15039. sub/add -128,(dest)
  15040. This generaally takes fewer bytes to encode because -128 can be stored
  15041. in a signed byte, whereas +128 cannot.
  15042. }
  15043. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15044. begin
  15045. if taicpu(p).opcode = A_ADD then
  15046. Opposite := A_SUB
  15047. else
  15048. Opposite := A_ADD;
  15049. { Be careful if the flags are in use, because the CF flag inverts
  15050. when changing from ADD to SUB and vice versa }
  15051. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15052. GetNextInstruction(p, hp1) then
  15053. begin
  15054. TransferUsedRegs(TmpUsedRegs);
  15055. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15056. hp2 := hp1;
  15057. { Scan ahead to check if everything's safe }
  15058. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15059. begin
  15060. if (hp1.typ <> ait_instruction) then
  15061. { Probably unsafe since the flags are still in use }
  15062. Exit;
  15063. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15064. { Stop searching at an unconditional jump }
  15065. Break;
  15066. if not
  15067. (
  15068. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15069. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15070. ) and
  15071. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15072. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15073. Exit;
  15074. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15075. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15076. { Move to the next instruction }
  15077. GetNextInstruction(hp1, hp1);
  15078. end;
  15079. while Assigned(hp2) and (hp2 <> hp1) do
  15080. begin
  15081. NewCond := C_None;
  15082. case taicpu(hp2).condition of
  15083. C_A, C_NBE:
  15084. NewCond := C_BE;
  15085. C_B, C_C, C_NAE:
  15086. NewCond := C_AE;
  15087. C_AE, C_NB, C_NC:
  15088. NewCond := C_B;
  15089. C_BE, C_NA:
  15090. NewCond := C_A;
  15091. else
  15092. { No change needed };
  15093. end;
  15094. if NewCond <> C_None then
  15095. begin
  15096. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15097. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15098. taicpu(hp2).condition := NewCond;
  15099. end
  15100. else
  15101. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15102. begin
  15103. { Because of the flipping of the carry bit, to ensure
  15104. the operation remains equivalent, ADC becomes SBB
  15105. and vice versa, and the constant is not-inverted.
  15106. If multiple ADCs or SBBs appear in a row, each one
  15107. changed causes the carry bit to invert, so they all
  15108. need to be flipped }
  15109. if taicpu(hp2).opcode = A_ADC then
  15110. SecondOpposite := A_SBB
  15111. else
  15112. SecondOpposite := A_ADC;
  15113. if taicpu(hp2).oper[0]^.typ <> top_const then
  15114. { Should have broken out of this optimisation already }
  15115. InternalError(2021112901);
  15116. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  15117. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  15118. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15119. taicpu(hp2).opcode := SecondOpposite;
  15120. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15121. end;
  15122. { Move to the next instruction }
  15123. GetNextInstruction(hp2, hp2);
  15124. end;
  15125. if (hp2 <> hp1) then
  15126. InternalError(2021111501);
  15127. end;
  15128. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15129. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15130. taicpu(p).opcode := Opposite;
  15131. taicpu(p).oper[0]^.val := -128;
  15132. { No further optimisations can be made on this instruction, so move
  15133. onto the next one to save time }
  15134. p := tai(p.Next);
  15135. UpdateUsedRegs(p);
  15136. Result := True;
  15137. Exit;
  15138. end;
  15139. { Detect:
  15140. add/sub %reg2,(dest)
  15141. add/sub x, (dest)
  15142. (dest can be a register or a reference)
  15143. Swap the instructions to minimise a pipeline stall. This reverses the
  15144. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15145. optimisations could be made.
  15146. }
  15147. if (taicpu(p).oper[0]^.typ = top_reg) and
  15148. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15149. (
  15150. (
  15151. (taicpu(p).oper[1]^.typ = top_reg) and
  15152. { We can try searching further ahead if we're writing to a register }
  15153. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15154. ) or
  15155. (
  15156. (taicpu(p).oper[1]^.typ = top_ref) and
  15157. GetNextInstruction(p, hp1)
  15158. )
  15159. ) and
  15160. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15161. (taicpu(hp1).oper[0]^.typ = top_const) and
  15162. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15163. begin
  15164. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15165. TransferUsedRegs(TmpUsedRegs);
  15166. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15167. hp2 := p;
  15168. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15169. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15170. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15171. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15172. begin
  15173. asml.remove(hp1);
  15174. asml.InsertBefore(hp1, p);
  15175. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15176. Result := True;
  15177. end;
  15178. end;
  15179. end;
  15180. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15181. var
  15182. hp1: tai;
  15183. begin
  15184. Result:=false;
  15185. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15186. while GetNextInstruction(p, hp1) and
  15187. TrySwapMovCmp(p, hp1) do
  15188. begin
  15189. if MatchInstruction(hp1, A_MOV, []) then
  15190. begin
  15191. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15192. begin
  15193. { A little hacky, but since CMP doesn't read the flags, only
  15194. modify them, it's safe if they get scrambled by MOV -> XOR }
  15195. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15196. Result := PostPeepholeOptMov(hp1);
  15197. {$ifdef x86_64}
  15198. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15199. { Used to shrink instruction size }
  15200. PostPeepholeOptXor(hp1);
  15201. {$endif x86_64}
  15202. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15203. end
  15204. else
  15205. begin
  15206. Result := PostPeepholeOptMov(hp1);
  15207. {$ifdef x86_64}
  15208. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15209. { Used to shrink instruction size }
  15210. PostPeepholeOptXor(hp1);
  15211. {$endif x86_64}
  15212. end;
  15213. end;
  15214. { Enabling this flag is actually a null operation, but it marks
  15215. the code as 'modified' during this pass }
  15216. Include(OptsToCheck, aoc_ForceNewIteration);
  15217. end;
  15218. { change "cmp $0, %reg" to "test %reg, %reg" }
  15219. if MatchOpType(taicpu(p),top_const,top_reg) and
  15220. (taicpu(p).oper[0]^.val = 0) then
  15221. begin
  15222. taicpu(p).opcode := A_TEST;
  15223. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15224. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15225. Result:=true;
  15226. end;
  15227. end;
  15228. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15229. var
  15230. IsTestConstX, IsValid : Boolean;
  15231. hp1,hp2 : tai;
  15232. begin
  15233. Result:=false;
  15234. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15235. if (taicpu(p).opcode = A_TEST) then
  15236. while GetNextInstruction(p, hp1) and
  15237. TrySwapMovCmp(p, hp1) do
  15238. begin
  15239. if MatchInstruction(hp1, A_MOV, []) then
  15240. begin
  15241. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15242. begin
  15243. { A little hacky, but since TEST doesn't read the flags, only
  15244. modify them, it's safe if they get scrambled by MOV -> XOR }
  15245. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15246. Result := PostPeepholeOptMov(hp1);
  15247. {$ifdef x86_64}
  15248. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15249. { Used to shrink instruction size }
  15250. PostPeepholeOptXor(hp1);
  15251. {$endif x86_64}
  15252. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15253. end
  15254. else
  15255. begin
  15256. Result := PostPeepholeOptMov(hp1);
  15257. {$ifdef x86_64}
  15258. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15259. { Used to shrink instruction size }
  15260. PostPeepholeOptXor(hp1);
  15261. {$endif x86_64}
  15262. end;
  15263. end;
  15264. { Enabling this flag is actually a null operation, but it marks
  15265. the code as 'modified' during this pass }
  15266. Include(OptsToCheck, aoc_ForceNewIteration);
  15267. end;
  15268. { If x is a power of 2 (popcnt = 1), change:
  15269. or $x, %reg/ref
  15270. To:
  15271. bts lb(x), %reg/ref
  15272. }
  15273. if (taicpu(p).opcode = A_OR) and
  15274. IsBTXAcceptable(p) and
  15275. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15276. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15277. (
  15278. { Don't optimise if a test instruction follows }
  15279. not GetNextInstruction(p, hp1) or
  15280. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15281. ) then
  15282. begin
  15283. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  15284. taicpu(p).opcode := A_BTS;
  15285. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15286. Result := True;
  15287. Exit;
  15288. end;
  15289. { If x is a power of 2 (popcnt = 1), change:
  15290. test $x, %reg/ref
  15291. je / sete / cmove (or jne / setne)
  15292. To:
  15293. bt lb(x), %reg/ref
  15294. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15295. }
  15296. if (taicpu(p).opcode = A_TEST) and
  15297. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15298. (taicpu(p).oper[0]^.typ = top_const) and
  15299. (
  15300. (cs_opt_size in current_settings.optimizerswitches) or
  15301. (
  15302. (taicpu(p).oper[1]^.typ = top_reg) and
  15303. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15304. ) or
  15305. (
  15306. (taicpu(p).oper[1]^.typ <> top_reg) and
  15307. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15308. )
  15309. ) and
  15310. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15311. { For sizes less than S_L, the byte size is equal or larger with BT,
  15312. so don't bother optimising }
  15313. (taicpu(p).opsize >= S_L) then
  15314. begin
  15315. IsValid := True;
  15316. { Check the next set of instructions, watching the FLAGS register
  15317. and the conditions used }
  15318. TransferUsedRegs(TmpUsedRegs);
  15319. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15320. hp1 := p;
  15321. hp2 := nil;
  15322. while GetNextInstruction(hp1, hp1) do
  15323. begin
  15324. if not Assigned(hp2) then
  15325. { The first instruction after TEST }
  15326. hp2 := hp1;
  15327. if (hp1.typ <> ait_instruction) then
  15328. begin
  15329. { If the flags are no longer in use, everything is fine }
  15330. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15331. IsValid := False;
  15332. Break;
  15333. end;
  15334. case taicpu(hp1).condition of
  15335. C_None:
  15336. begin
  15337. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15338. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15339. { Something is not quite normal, so play safe and don't change }
  15340. IsValid := False;
  15341. Break;
  15342. end;
  15343. C_E, C_Z, C_NE, C_NZ:
  15344. { This is fine };
  15345. else
  15346. begin
  15347. { Unsupported condition }
  15348. IsValid := False;
  15349. Break;
  15350. end;
  15351. end;
  15352. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15353. end;
  15354. if IsValid then
  15355. begin
  15356. while hp2 <> hp1 do
  15357. begin
  15358. case taicpu(hp2).condition of
  15359. C_Z, C_E:
  15360. taicpu(hp2).condition := C_NC;
  15361. C_NZ, C_NE:
  15362. taicpu(hp2).condition := C_C;
  15363. else
  15364. { Should not get this by this point }
  15365. InternalError(2022110701);
  15366. end;
  15367. GetNextInstruction(hp2, hp2);
  15368. end;
  15369. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  15370. taicpu(p).opcode := A_BT;
  15371. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15372. Result := True;
  15373. Exit;
  15374. end;
  15375. end;
  15376. { removes the line marked with (x) from the sequence
  15377. and/or/xor/add/sub/... $x, %y
  15378. test/or %y, %y | test $-1, %y (x)
  15379. j(n)z _Label
  15380. as the first instruction already adjusts the ZF
  15381. %y operand may also be a reference }
  15382. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15383. MatchOperand(taicpu(p).oper[0]^,-1);
  15384. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15385. GetLastInstruction(p, hp1) and
  15386. (tai(hp1).typ = ait_instruction) and
  15387. GetNextInstruction(p,hp2) and
  15388. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15389. case taicpu(hp1).opcode Of
  15390. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15391. { These two instructions set the zero flag if the result is zero }
  15392. A_POPCNT, A_LZCNT:
  15393. begin
  15394. if (
  15395. { With POPCNT, an input of zero will set the zero flag
  15396. because the population count of zero is zero }
  15397. (taicpu(hp1).opcode = A_POPCNT) and
  15398. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15399. (
  15400. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15401. { Faster than going through the second half of the 'or'
  15402. condition below }
  15403. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15404. )
  15405. ) or (
  15406. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15407. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15408. { and in case of carry for A(E)/B(E)/C/NC }
  15409. (
  15410. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15411. (
  15412. (taicpu(hp1).opcode <> A_ADD) and
  15413. (taicpu(hp1).opcode <> A_SUB) and
  15414. (taicpu(hp1).opcode <> A_LZCNT)
  15415. )
  15416. )
  15417. ) then
  15418. begin
  15419. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15420. RemoveCurrentP(p, hp2);
  15421. Result:=true;
  15422. Exit;
  15423. end;
  15424. end;
  15425. A_SHL, A_SAL, A_SHR, A_SAR:
  15426. begin
  15427. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15428. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15429. { therefore, it's only safe to do this optimization for }
  15430. { shifts by a (nonzero) constant }
  15431. (taicpu(hp1).oper[0]^.typ = top_const) and
  15432. (taicpu(hp1).oper[0]^.val <> 0) and
  15433. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15434. { and in case of carry for A(E)/B(E)/C/NC }
  15435. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15436. begin
  15437. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15438. RemoveCurrentP(p, hp2);
  15439. Result:=true;
  15440. Exit;
  15441. end;
  15442. end;
  15443. A_DEC, A_INC, A_NEG:
  15444. begin
  15445. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15446. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15447. { and in case of carry for A(E)/B(E)/C/NC }
  15448. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15449. begin
  15450. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15451. RemoveCurrentP(p, hp2);
  15452. Result:=true;
  15453. Exit;
  15454. end;
  15455. end;
  15456. A_ANDN, A_BZHI:
  15457. begin
  15458. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15459. { Only the zero and sign flags are consistent with what the result is }
  15460. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15461. begin
  15462. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15463. RemoveCurrentP(p, hp2);
  15464. Result:=true;
  15465. Exit;
  15466. end;
  15467. end;
  15468. A_BEXTR:
  15469. begin
  15470. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15471. { Only the zero flag is set }
  15472. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15473. begin
  15474. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15475. RemoveCurrentP(p, hp2);
  15476. Result:=true;
  15477. Exit;
  15478. end;
  15479. end;
  15480. else
  15481. ;
  15482. end; { case }
  15483. { change "test $-1,%reg" into "test %reg,%reg" }
  15484. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15485. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15486. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15487. if MatchInstruction(p, A_OR, []) and
  15488. { Can only match if they're both registers }
  15489. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15490. begin
  15491. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15492. taicpu(p).opcode := A_TEST;
  15493. { No need to set Result to True, as we've done all the optimisations we can }
  15494. end;
  15495. end;
  15496. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15497. var
  15498. hp1,hp3 : tai;
  15499. {$ifndef x86_64}
  15500. hp2 : taicpu;
  15501. {$endif x86_64}
  15502. begin
  15503. Result:=false;
  15504. hp3:=nil;
  15505. {$ifndef x86_64}
  15506. { don't do this on modern CPUs, this really hurts them due to
  15507. broken call/ret pairing }
  15508. if (current_settings.optimizecputype < cpu_Pentium2) and
  15509. not(cs_create_pic in current_settings.moduleswitches) and
  15510. GetNextInstruction(p, hp1) and
  15511. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15512. MatchOpType(taicpu(hp1),top_ref) and
  15513. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15514. begin
  15515. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15516. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15517. InsertLLItem(p.previous, p, hp2);
  15518. taicpu(p).opcode := A_JMP;
  15519. taicpu(p).is_jmp := true;
  15520. RemoveInstruction(hp1);
  15521. Result:=true;
  15522. end
  15523. else
  15524. {$endif x86_64}
  15525. { replace
  15526. call procname
  15527. ret
  15528. by
  15529. jmp procname
  15530. but do it only on level 4 because it destroys stack back traces
  15531. else if the subroutine is marked as no return, remove the ret
  15532. }
  15533. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15534. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15535. GetNextInstruction(p, hp1) and
  15536. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15537. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15538. SetAndTest(hp1,hp3) and
  15539. GetNextInstruction(hp1,hp1) and
  15540. MatchInstruction(hp1,A_RET,[S_NO])
  15541. )
  15542. ) and
  15543. (taicpu(hp1).ops=0) then
  15544. begin
  15545. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15546. { we might destroy stack alignment here if we do not do a call }
  15547. (target_info.stackalign<=sizeof(SizeUInt)) then
  15548. begin
  15549. taicpu(p).opcode := A_JMP;
  15550. taicpu(p).is_jmp := true;
  15551. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15552. end
  15553. else
  15554. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15555. RemoveInstruction(hp1);
  15556. if Assigned(hp3) then
  15557. begin
  15558. AsmL.Remove(hp3);
  15559. AsmL.InsertBefore(hp3,p)
  15560. end;
  15561. Result:=true;
  15562. end;
  15563. end;
  15564. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15565. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15566. begin
  15567. case OpSize of
  15568. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15569. Result := (Val <= $FF) and (Val >= -128);
  15570. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15571. Result := (Val <= $FFFF) and (Val >= -32768);
  15572. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15573. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15574. else
  15575. Result := True;
  15576. end;
  15577. end;
  15578. var
  15579. hp1, hp2 : tai;
  15580. SizeChange: Boolean;
  15581. PreMessage: string;
  15582. begin
  15583. Result := False;
  15584. if (taicpu(p).oper[0]^.typ = top_reg) and
  15585. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15586. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15587. begin
  15588. { Change (using movzbl %al,%eax as an example):
  15589. movzbl %al, %eax movzbl %al, %eax
  15590. cmpl x, %eax testl %eax,%eax
  15591. To:
  15592. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15593. movzbl %al, %eax movzbl %al, %eax
  15594. Smaller instruction and minimises pipeline stall as the CPU
  15595. doesn't have to wait for the register to get zero-extended. [Kit]
  15596. Also allow if the smaller of the two registers is being checked,
  15597. as this still removes the false dependency.
  15598. }
  15599. if
  15600. (
  15601. (
  15602. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15603. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15604. ) or (
  15605. { If MatchOperand returns True, they must both be registers }
  15606. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15607. )
  15608. ) and
  15609. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15610. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15611. begin
  15612. PreMessage := debug_op2str(taicpu(hp1).opcode) + debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' -> ' + debug_op2str(taicpu(hp1).opcode);
  15613. asml.Remove(hp1);
  15614. asml.InsertBefore(hp1, p);
  15615. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15616. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15617. begin
  15618. taicpu(hp1).opcode := A_TEST;
  15619. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15620. end;
  15621. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15622. case taicpu(p).opsize of
  15623. S_BW, S_BL:
  15624. begin
  15625. SizeChange := taicpu(hp1).opsize <> S_B;
  15626. taicpu(hp1).changeopsize(S_B);
  15627. end;
  15628. S_WL:
  15629. begin
  15630. SizeChange := taicpu(hp1).opsize <> S_W;
  15631. taicpu(hp1).changeopsize(S_W);
  15632. end
  15633. else
  15634. InternalError(2020112701);
  15635. end;
  15636. UpdateUsedRegs(tai(p.Next));
  15637. { Check if the register is used aferwards - if not, we can
  15638. remove the movzx instruction completely }
  15639. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15640. begin
  15641. { Hp1 is a better position than p for debugging purposes }
  15642. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15643. RemoveCurrentp(p, hp1);
  15644. Result := True;
  15645. end;
  15646. if SizeChange then
  15647. DebugMsg(SPeepholeOptimization + PreMessage +
  15648. debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (smaller and minimises pipeline stall - MovzxCmp2CmpMovzx)', hp1)
  15649. else
  15650. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15651. Exit;
  15652. end;
  15653. { Change (using movzwl %ax,%eax as an example):
  15654. movzwl %ax, %eax
  15655. movb %al, (dest) (Register is smaller than read register in movz)
  15656. To:
  15657. movb %al, (dest) (Move one back to avoid a false dependency)
  15658. movzwl %ax, %eax
  15659. }
  15660. if (taicpu(hp1).opcode = A_MOV) and
  15661. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15662. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15663. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15664. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15665. begin
  15666. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15667. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15668. asml.Remove(hp1);
  15669. asml.InsertBefore(hp1, p);
  15670. if taicpu(hp1).oper[1]^.typ = top_reg then
  15671. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15672. { Check if the register is used aferwards - if not, we can
  15673. remove the movzx instruction completely }
  15674. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15675. begin
  15676. { Hp1 is a better position than p for debugging purposes }
  15677. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15678. RemoveCurrentp(p, hp1);
  15679. Result := True;
  15680. end;
  15681. Exit;
  15682. end;
  15683. end;
  15684. end;
  15685. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15686. var
  15687. hp1: tai;
  15688. {$ifdef x86_64}
  15689. PreMessage, RegName: string;
  15690. {$endif x86_64}
  15691. begin
  15692. Result := False;
  15693. { If x is a power of 2 (popcnt = 1), change:
  15694. xor $x, %reg/ref
  15695. To:
  15696. btc lb(x), %reg/ref
  15697. }
  15698. if IsBTXAcceptable(p) and
  15699. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15700. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15701. (
  15702. { Don't optimise if a test instruction follows }
  15703. not GetNextInstruction(p, hp1) or
  15704. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15705. ) then
  15706. begin
  15707. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  15708. taicpu(p).opcode := A_BTC;
  15709. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15710. Result := True;
  15711. Exit;
  15712. end;
  15713. {$ifdef x86_64}
  15714. { Code size reduction by J. Gareth "Kit" Moreton }
  15715. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15716. as this removes the REX prefix }
  15717. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15718. Exit;
  15719. if taicpu(p).oper[0]^.typ <> top_reg then
  15720. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15721. InternalError(2018011500);
  15722. case taicpu(p).opsize of
  15723. S_Q:
  15724. begin
  15725. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15726. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15727. { The actual optimization }
  15728. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15729. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15730. taicpu(p).changeopsize(S_L);
  15731. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15732. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15733. end;
  15734. else
  15735. ;
  15736. end;
  15737. {$endif x86_64}
  15738. end;
  15739. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15740. var
  15741. XReg: TRegister;
  15742. begin
  15743. Result := False;
  15744. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15745. Smaller encoding and slightly faster on some platforms (also works for
  15746. ZMM-sized registers) }
  15747. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15748. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15749. begin
  15750. XReg := taicpu(p).oper[0]^.reg;
  15751. if (taicpu(p).oper[1]^.reg = XReg) then
  15752. begin
  15753. taicpu(p).changeopsize(S_XMM);
  15754. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15755. if (cs_opt_size in current_settings.optimizerswitches) then
  15756. begin
  15757. { Change input registers to %xmm0 to reduce size. Note that
  15758. there's a risk of a false dependency doing this, so only
  15759. optimise for size here }
  15760. XReg := NR_XMM0;
  15761. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15762. end
  15763. else
  15764. begin
  15765. setsubreg(XReg, R_SUBMMX);
  15766. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15767. end;
  15768. taicpu(p).oper[0]^.reg := XReg;
  15769. taicpu(p).oper[1]^.reg := XReg;
  15770. Result := True;
  15771. end;
  15772. end;
  15773. end;
  15774. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15775. var
  15776. OperIdx: Integer;
  15777. begin
  15778. for OperIdx := 0 to p.ops - 1 do
  15779. if p.oper[OperIdx]^.typ = top_ref then
  15780. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15781. end;
  15782. end.