2
0

aoptx86.pas 728 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187
  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. private
  73. function SkipSimpleInstructions(var hp1: tai): Boolean;
  74. protected
  75. class function IsMOVZXAcceptable: Boolean; static; inline;
  76. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  77. { Attempts to allocate a volatile integer register for use between p and hp,
  78. using AUsedRegs for the current register usage information. Returns NR_NO
  79. if no free register could be found }
  80. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  81. { Attempts to allocate a volatile MM 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 GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  86. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  87. { checks whether reading the value in reg1 depends on the value of reg2. This
  88. is very similar to SuperRegisterEquals, except it takes into account that
  89. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  90. depend on the value in AH). }
  91. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  92. { Replaces all references to AOldReg in a memory reference to ANewReg }
  93. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an operand to ANewReg }
  95. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  96. { Replaces all references to AOldReg in an instruction to ANewReg,
  97. except where the register is being written }
  98. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  99. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  100. or writes to a global symbol }
  101. class function IsRefSafe(const ref: PReference): Boolean; static;
  102. { Returns true if the given MOV instruction can be safely converted to CMOV }
  103. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  104. { Like UpdateUsedRegs, but ignores deallocations }
  105. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  106. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  107. class function IsBTXAcceptable(p : tai) : boolean; static;
  108. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  109. conversion was successful }
  110. function ConvertLEA(const p : taicpu): Boolean;
  111. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  112. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  113. procedure DebugMsg(const s : string; p : tai);inline;
  114. class function IsExitCode(p : tai) : boolean; static;
  115. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  116. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  117. procedure RemoveLastDeallocForFuncRes(p : tai);
  118. function DoArithCombineOpt(var p : tai) : Boolean;
  119. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  120. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  121. function PrePeepholeOptSxx(var p : tai) : boolean;
  122. function PrePeepholeOptIMUL(var p : tai) : boolean;
  123. function PrePeepholeOptAND(var p : tai) : boolean;
  124. function OptPass1Test(var p: tai): boolean;
  125. function OptPass1Add(var p: tai): boolean;
  126. function OptPass1AND(var p : tai) : boolean;
  127. function OptPass1_V_MOVAP(var p : tai) : boolean;
  128. function OptPass1VOP(var p : tai) : boolean;
  129. function OptPass1MOV(var p : tai) : boolean;
  130. function OptPass1Movx(var p : tai) : boolean;
  131. function OptPass1MOVXX(var p : tai) : boolean;
  132. function OptPass1OP(var p : tai) : boolean;
  133. function OptPass1LEA(var p : tai) : boolean;
  134. function OptPass1Sub(var p : tai) : boolean;
  135. function OptPass1SHLSAL(var p : tai) : boolean;
  136. function OptPass1SHR(var p : tai) : boolean;
  137. function OptPass1FSTP(var p : tai) : boolean;
  138. function OptPass1FLD(var p : tai) : boolean;
  139. function OptPass1Cmp(var p : tai) : boolean;
  140. function OptPass1PXor(var p : tai) : boolean;
  141. function OptPass1VPXor(var p: tai): boolean;
  142. function OptPass1Imul(var p : tai) : boolean;
  143. function OptPass1Jcc(var p : tai) : boolean;
  144. function OptPass1SHXX(var p: tai): boolean;
  145. function OptPass1VMOVDQ(var p: tai): Boolean;
  146. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  147. function OptPass1STCCLC(var p: tai): Boolean;
  148. function OptPass2STCCLC(var p: tai): Boolean;
  149. function OptPass2CMOVcc(var p: tai): Boolean;
  150. function OptPass2Movx(var p : tai): Boolean;
  151. function OptPass2MOV(var p : tai) : boolean;
  152. function OptPass2Imul(var p : tai) : boolean;
  153. function OptPass2Jmp(var p : tai) : boolean;
  154. function OptPass2Jcc(var p : tai) : boolean;
  155. function OptPass2Lea(var p: tai): Boolean;
  156. function OptPass2SUB(var p: tai): Boolean;
  157. function OptPass2ADD(var p : tai): Boolean;
  158. function OptPass2SETcc(var p : tai) : boolean;
  159. function OptPass2Cmp(var p: tai): Boolean;
  160. function OptPass2Test(var p: tai): Boolean;
  161. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  162. function PostPeepholeOptMov(var p : tai) : Boolean;
  163. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  164. function PostPeepholeOptXor(var p : tai) : Boolean;
  165. function PostPeepholeOptAnd(var p : tai) : boolean;
  166. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  167. function PostPeepholeOptCmp(var p : tai) : Boolean;
  168. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  169. function PostPeepholeOptCall(var p : tai) : Boolean;
  170. function PostPeepholeOptLea(var p : tai) : Boolean;
  171. function PostPeepholeOptPush(var p: tai): Boolean;
  172. function PostPeepholeOptShr(var p : tai) : boolean;
  173. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  174. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  175. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  176. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  177. function TrySwapMovOp(var p, hp1: tai): Boolean;
  178. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  179. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  180. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  181. { Processor-dependent reference optimisation }
  182. class procedure OptimizeRefs(var p: taicpu); static;
  183. end;
  184. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  185. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  187. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  188. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  189. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  190. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  191. {$if max_operands>2}
  192. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  193. {$endif max_operands>2}
  194. function RefsEqual(const r1, r2: treference): boolean;
  195. { Note that Result is set to True if the references COULD overlap but the
  196. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  197. might still overlap because %reg2 could be equal to %reg1-4 }
  198. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  199. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  200. { returns true, if ref is a reference using only the registers passed as base and index
  201. and having an offset }
  202. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  203. implementation
  204. uses
  205. cutils,verbose,
  206. systems,
  207. globals,
  208. cpuinfo,
  209. procinfo,
  210. paramgr,
  211. aasmbase,
  212. aoptbase,aoptutils,
  213. symconst,symsym,
  214. cgx86,
  215. itcpugas;
  216. {$ifndef 8086}
  217. const
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. type
  221. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  222. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  223. tsProcessed);
  224. { For OptPass2Jcc }
  225. TCMOVTracking = object
  226. private
  227. CMOVScore, ConstCount: LongInt;
  228. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  229. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  230. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  231. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  232. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  233. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  234. fOptimizer: TX86AsmOptimizer;
  235. fLabel: TAsmSymbol;
  236. fInsertionPoint,
  237. fCondition,
  238. fInitialJump,
  239. fFirstMovBlock,
  240. fFirstMovBlockStop,
  241. fSecondJump,
  242. fThirdJump,
  243. fSecondMovBlock,
  244. fSecondMovBlockStop,
  245. fMidLabel,
  246. fEndLabel,
  247. fAllocationRange: tai;
  248. fState: TCMovTrackingState;
  249. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  250. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  251. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  252. public
  253. RegisterTracking: TAllUsedRegs;
  254. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  255. destructor Done;
  256. procedure Process(out new_p: tai);
  257. property State: TCMovTrackingState read fState;
  258. end;
  259. PCMOVTracking = ^TCMOVTracking;
  260. {$endif 8086}
  261. {$ifdef DEBUG_AOPTCPU}
  262. const
  263. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  264. {$else DEBUG_AOPTCPU}
  265. { Empty strings help the optimizer to remove string concatenations that won't
  266. ever appear to the user on release builds. [Kit] }
  267. const
  268. SPeepholeOptimization = '';
  269. {$endif DEBUG_AOPTCPU}
  270. LIST_STEP_SIZE = 4;
  271. type
  272. TJumpTrackingItem = class(TLinkedListItem)
  273. private
  274. FSymbol: TAsmSymbol;
  275. FRefs: LongInt;
  276. public
  277. constructor Create(ASymbol: TAsmSymbol);
  278. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  279. property Symbol: TAsmSymbol read FSymbol;
  280. property Refs: LongInt read FRefs;
  281. end;
  282. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  283. begin
  284. inherited Create;
  285. FSymbol := ASymbol;
  286. FRefs := 0;
  287. end;
  288. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  289. begin
  290. Inc(FRefs);
  291. end;
  292. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  293. begin
  294. result :=
  295. (instr.typ = ait_instruction) and
  296. (taicpu(instr).opcode = op) and
  297. ((opsize = []) or (taicpu(instr).opsize in opsize));
  298. end;
  299. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  300. begin
  301. result :=
  302. (instr.typ = ait_instruction) and
  303. ((taicpu(instr).opcode = op1) or
  304. (taicpu(instr).opcode = op2)
  305. ) and
  306. ((opsize = []) or (taicpu(instr).opsize in opsize));
  307. end;
  308. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  309. begin
  310. result :=
  311. (instr.typ = ait_instruction) and
  312. ((taicpu(instr).opcode = op1) or
  313. (taicpu(instr).opcode = op2) or
  314. (taicpu(instr).opcode = op3)
  315. ) and
  316. ((opsize = []) or (taicpu(instr).opsize in opsize));
  317. end;
  318. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  319. const opsize : topsizes) : boolean;
  320. var
  321. op : TAsmOp;
  322. begin
  323. result:=false;
  324. if (instr.typ <> ait_instruction) or
  325. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  326. exit;
  327. for op in ops do
  328. begin
  329. if taicpu(instr).opcode = op then
  330. begin
  331. result:=true;
  332. exit;
  333. end;
  334. end;
  335. end;
  336. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  337. begin
  338. result := (oper.typ = top_reg) and (oper.reg = reg);
  339. end;
  340. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  341. begin
  342. result := (oper.typ = top_const) and (oper.val = a);
  343. end;
  344. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  345. begin
  346. result := oper1.typ = oper2.typ;
  347. if result then
  348. case oper1.typ of
  349. top_const:
  350. Result:=oper1.val = oper2.val;
  351. top_reg:
  352. Result:=oper1.reg = oper2.reg;
  353. top_ref:
  354. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  355. else
  356. internalerror(2013102801);
  357. end
  358. end;
  359. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  360. begin
  361. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  362. if result then
  363. case oper1.typ of
  364. top_const:
  365. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  366. top_reg:
  367. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  368. top_ref:
  369. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  370. else
  371. internalerror(2020052401);
  372. end
  373. end;
  374. function RefsEqual(const r1, r2: treference): boolean;
  375. begin
  376. RefsEqual :=
  377. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  378. (r1.relsymbol = r2.relsymbol) and
  379. (r1.segment = r2.segment) and (r1.base = r2.base) and
  380. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  381. (r1.offset = r2.offset) and
  382. (r1.volatility + r2.volatility = []);
  383. end;
  384. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  385. begin
  386. if (r1.symbol<>r2.symbol) then
  387. { If the index registers are different, there's a chance one could
  388. be set so it equals the other symbol }
  389. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  390. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  391. (r1.relsymbol = r2.relsymbol) and
  392. (r1.segment = r2.segment) and (r1.base = r2.base) and
  393. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  394. (r1.volatility + r2.volatility = []) then
  395. { In this case, it all depends on the offsets }
  396. Exit(abs(r1.offset - r2.offset) < Range);
  397. { There's a chance things MIGHT overlap, so take no chances }
  398. Result := True;
  399. end;
  400. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  401. begin
  402. Result:=(ref.offset=0) and
  403. (ref.scalefactor in [0,1]) and
  404. (ref.segment=NR_NO) and
  405. (ref.symbol=nil) and
  406. (ref.relsymbol=nil) and
  407. ((base=NR_INVALID) or
  408. (ref.base=base)) and
  409. ((index=NR_INVALID) or
  410. (ref.index=index)) and
  411. (ref.volatility=[]);
  412. end;
  413. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  414. begin
  415. Result:=(ref.scalefactor in [0,1]) and
  416. (ref.segment=NR_NO) and
  417. (ref.symbol=nil) and
  418. (ref.relsymbol=nil) and
  419. ((base=NR_INVALID) or
  420. (ref.base=base)) and
  421. ((index=NR_INVALID) or
  422. (ref.index=index)) and
  423. (ref.volatility=[]);
  424. end;
  425. function InstrReadsFlags(p: tai): boolean;
  426. begin
  427. InstrReadsFlags := true;
  428. case p.typ of
  429. ait_instruction:
  430. if InsProp[taicpu(p).opcode].Ch*
  431. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  432. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  433. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  434. exit;
  435. ait_label:
  436. exit;
  437. else
  438. ;
  439. end;
  440. InstrReadsFlags := false;
  441. end;
  442. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  443. begin
  444. Next:=Current;
  445. repeat
  446. Result:=GetNextInstruction(Next,Next);
  447. until not (Result) or
  448. not(cs_opt_level3 in current_settings.optimizerswitches) or
  449. (Next.typ<>ait_instruction) or
  450. RegInInstruction(reg,Next) or
  451. is_calljmp(taicpu(Next).opcode);
  452. end;
  453. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  454. var
  455. GetNextResult: Boolean;
  456. begin
  457. Result:=0;
  458. Next:=Current;
  459. repeat
  460. GetNextResult := GetNextInstruction(Next,Next);
  461. if GetNextResult then
  462. Inc(Result)
  463. else
  464. { Must return zero upon hitting the end of the linked list without a match }
  465. Result := 0;
  466. until not (GetNextResult) or
  467. not(cs_opt_level3 in current_settings.optimizerswitches) or
  468. (Next.typ<>ait_instruction) or
  469. RegInInstruction(reg,Next) or
  470. is_calljmp(taicpu(Next).opcode);
  471. end;
  472. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  473. procedure TrackJump(Symbol: TAsmSymbol);
  474. var
  475. Search: TJumpTrackingItem;
  476. begin
  477. { See if an entry already exists in our jump tracking list
  478. (faster to search backwards due to the higher chance of
  479. matching destinations) }
  480. Search := TJumpTrackingItem(JumpTracking.Last);
  481. while Assigned(Search) do
  482. begin
  483. if Search.Symbol = Symbol then
  484. begin
  485. { Found it - remove it so it can be pushed to the front }
  486. JumpTracking.Remove(Search);
  487. Break;
  488. end;
  489. Search := TJumpTrackingItem(Search.Previous);
  490. end;
  491. if not Assigned(Search) then
  492. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  493. JumpTracking.Concat(Search);
  494. Search.IncRefs;
  495. end;
  496. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  497. var
  498. Search: TJumpTrackingItem;
  499. begin
  500. Result := False;
  501. { See if this label appears in the tracking list }
  502. Search := TJumpTrackingItem(JumpTracking.Last);
  503. while Assigned(Search) do
  504. begin
  505. if Search.Symbol = Symbol then
  506. begin
  507. { Found it - let's see what we can discover }
  508. if Search.Symbol.getrefs = Search.Refs then
  509. begin
  510. { Success - all the references are accounted for }
  511. JumpTracking.Remove(Search);
  512. Search.Free;
  513. { It is logically impossible for CrossJump to be false here
  514. because we must have run into a conditional jump for
  515. this label at some point }
  516. if not CrossJump then
  517. InternalError(2022041710);
  518. if JumpTracking.First = nil then
  519. { Tracking list is now empty - no more cross jumps }
  520. CrossJump := False;
  521. Result := True;
  522. Exit;
  523. end;
  524. { If the references don't match, it's possible to enter
  525. this label through other means, so drop out }
  526. Exit;
  527. end;
  528. Search := TJumpTrackingItem(Search.Previous);
  529. end;
  530. end;
  531. var
  532. Next_Label: tai;
  533. begin
  534. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  535. Next := Current;
  536. repeat
  537. Result := GetNextInstruction(Next,Next);
  538. if not Result then
  539. Break;
  540. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  541. if is_calljmpuncondret(taicpu(Next).opcode) then
  542. begin
  543. if (taicpu(Next).opcode = A_JMP) and
  544. { Remove dead code now to save time }
  545. RemoveDeadCodeAfterJump(taicpu(Next)) then
  546. { A jump was removed, but not the current instruction, and
  547. Result doesn't necessarily translate into an optimisation
  548. routine's Result, so use the "Force New Iteration" flag so
  549. mark a new pass }
  550. Include(OptsToCheck, aoc_ForceNewIteration);
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) and
  562. GetNextInstruction(Next, Next_Label) then
  563. begin
  564. { If we have JMP .lbl, and the label after it has all of its
  565. references tracked, then this is probably an if-else style of
  566. block and we can keep tracking. If the label for this jump
  567. then appears later and is fully tracked, then it's the end
  568. of the if-else blocks and the code paths converge (thus
  569. marking the end of the cross-jump) }
  570. if (Next_Label.typ = ait_label) then
  571. begin
  572. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  573. begin
  574. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  575. Next := Next_Label;
  576. { CrossJump gets set to false by LabelAccountedFor if the
  577. list is completely emptied (as it indicates that all
  578. code paths have converged). We could avoid this nuance
  579. by moving the TrackJump call to before the
  580. LabelAccountedFor call, but this is slower in situations
  581. where LabelAccountedFor would return False due to the
  582. creation of a new object that is not used and destroyed
  583. soon after. }
  584. CrossJump := True;
  585. Continue;
  586. end;
  587. end
  588. else if (Next_Label.typ <> ait_marker) then
  589. { We just did a RemoveDeadCodeAfterJump, so either we find
  590. a label, the end of the procedure or some kind of marker}
  591. InternalError(2022041720);
  592. end;
  593. Result := False;
  594. Exit;
  595. end
  596. else
  597. begin
  598. if not Assigned(JumpTracking) then
  599. begin
  600. { Cross-label optimisations often causes other optimisations
  601. to perform worse because they're not given the chance to
  602. optimise locally. In this case, don't do the cross-label
  603. optimisations yet, but flag them as a potential possibility
  604. for the next iteration of Pass 1 }
  605. if not NotFirstIteration then
  606. Include(OptsToCheck, aoc_ForceNewIteration);
  607. end
  608. else if IsJumpToLabel(taicpu(Next)) then
  609. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  610. else
  611. { Conditional jumps should always be a jump to label }
  612. InternalError(2022041701);
  613. CrossJump := True;
  614. Continue;
  615. end;
  616. if Next.typ = ait_label then
  617. begin
  618. if not Assigned(JumpTracking) then
  619. begin
  620. { Cross-label optimisations often causes other optimisations
  621. to perform worse because they're not given the chance to
  622. optimise locally. In this case, don't do the cross-label
  623. optimisations yet, but flag them as a potential possibility
  624. for the next iteration of Pass 1 }
  625. if not NotFirstIteration then
  626. Include(OptsToCheck, aoc_ForceNewIteration);
  627. end
  628. else if LabelAccountedFor(tai_label(Next).labsym) then
  629. Continue;
  630. { If we reach here, we're at a label that hasn't been seen before
  631. (or JumpTracking was nil) }
  632. Break;
  633. end;
  634. until not Result or
  635. not (cs_opt_level3 in current_settings.optimizerswitches) or
  636. not (Next.typ in [ait_label, ait_instruction]) or
  637. RegInInstruction(reg,Next);
  638. end;
  639. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  640. begin
  641. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  642. begin
  643. Result:=GetNextInstruction(Current,Next);
  644. exit;
  645. end;
  646. Next:=tai(Current.Next);
  647. Result:=false;
  648. while assigned(Next) do
  649. begin
  650. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  651. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  652. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  653. exit
  654. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  655. begin
  656. Result:=true;
  657. exit;
  658. end;
  659. Next:=tai(Next.Next);
  660. end;
  661. end;
  662. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  663. begin
  664. Result:=RegReadByInstruction(reg,hp);
  665. end;
  666. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  667. var
  668. p: taicpu;
  669. opcount: longint;
  670. begin
  671. RegReadByInstruction := false;
  672. if hp.typ <> ait_instruction then
  673. exit;
  674. p := taicpu(hp);
  675. case p.opcode of
  676. A_CALL:
  677. regreadbyinstruction := true;
  678. A_IMUL:
  679. case p.ops of
  680. 1:
  681. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  682. (
  683. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  684. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  685. );
  686. 2,3:
  687. regReadByInstruction :=
  688. reginop(reg,p.oper[0]^) or
  689. reginop(reg,p.oper[1]^);
  690. else
  691. InternalError(2019112801);
  692. end;
  693. A_MUL:
  694. begin
  695. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  696. (
  697. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  698. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  699. );
  700. end;
  701. A_IDIV,A_DIV:
  702. begin
  703. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  704. (
  705. (getregtype(reg)=R_INTREGISTER) and
  706. (
  707. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  708. )
  709. );
  710. end;
  711. else
  712. begin
  713. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  714. begin
  715. RegReadByInstruction := false;
  716. exit;
  717. end;
  718. for opcount := 0 to p.ops-1 do
  719. if (p.oper[opCount]^.typ = top_ref) and
  720. RegInRef(reg,p.oper[opcount]^.ref^) then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. { special handling for SSE MOVSD }
  726. if (p.opcode=A_MOVSD) and (p.ops>0) then
  727. begin
  728. if p.ops<>2 then
  729. internalerror(2017042702);
  730. regReadByInstruction := reginop(reg,p.oper[0]^) or
  731. (
  732. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  733. );
  734. exit;
  735. end;
  736. with insprop[p.opcode] do
  737. begin
  738. case getregtype(reg) of
  739. R_INTREGISTER:
  740. begin
  741. case getsupreg(reg) of
  742. RS_EAX:
  743. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  744. begin
  745. RegReadByInstruction := true;
  746. exit
  747. end;
  748. RS_ECX:
  749. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. RS_EDX:
  755. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  756. begin
  757. RegReadByInstruction := true;
  758. exit
  759. end;
  760. RS_EBX:
  761. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  762. begin
  763. RegReadByInstruction := true;
  764. exit
  765. end;
  766. RS_ESP:
  767. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  768. begin
  769. RegReadByInstruction := true;
  770. exit
  771. end;
  772. RS_EBP:
  773. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  774. begin
  775. RegReadByInstruction := true;
  776. exit
  777. end;
  778. RS_ESI:
  779. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  780. begin
  781. RegReadByInstruction := true;
  782. exit
  783. end;
  784. RS_EDI:
  785. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  786. begin
  787. RegReadByInstruction := true;
  788. exit
  789. end;
  790. end;
  791. end;
  792. R_MMREGISTER:
  793. begin
  794. case getsupreg(reg) of
  795. RS_XMM0:
  796. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  797. begin
  798. RegReadByInstruction := true;
  799. exit
  800. end;
  801. end;
  802. end;
  803. else
  804. ;
  805. end;
  806. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  807. begin
  808. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  809. begin
  810. case p.condition of
  811. C_A,C_NBE, { CF=0 and ZF=0 }
  812. C_BE,C_NA: { CF=1 or ZF=1 }
  813. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  814. C_AE,C_NB,C_NC, { CF=0 }
  815. C_B,C_NAE,C_C: { CF=1 }
  816. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  817. C_NE,C_NZ, { ZF=0 }
  818. C_E,C_Z: { ZF=1 }
  819. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  820. C_G,C_NLE, { ZF=0 and SF=OF }
  821. C_LE,C_NG: { ZF=1 or SF<>OF }
  822. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  823. C_GE,C_NL, { SF=OF }
  824. C_L,C_NGE: { SF<>OF }
  825. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  826. C_NO, { OF=0 }
  827. C_O: { OF=1 }
  828. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  829. C_NP,C_PO, { PF=0 }
  830. C_P,C_PE: { PF=1 }
  831. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  832. C_NS, { SF=0 }
  833. C_S: { SF=1 }
  834. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  835. else
  836. internalerror(2017042701);
  837. end;
  838. if RegReadByInstruction then
  839. exit;
  840. end;
  841. case getsubreg(reg) of
  842. R_SUBW,R_SUBD,R_SUBQ:
  843. RegReadByInstruction :=
  844. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  845. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  846. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  847. R_SUBFLAGCARRY:
  848. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  849. R_SUBFLAGPARITY:
  850. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  851. R_SUBFLAGAUXILIARY:
  852. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  853. R_SUBFLAGZERO:
  854. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  855. R_SUBFLAGSIGN:
  856. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  857. R_SUBFLAGOVERFLOW:
  858. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  859. R_SUBFLAGINTERRUPT:
  860. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  861. R_SUBFLAGDIRECTION:
  862. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  863. else
  864. internalerror(2017042601);
  865. end;
  866. exit;
  867. end;
  868. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  869. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  870. (p.oper[0]^.reg=p.oper[1]^.reg) then
  871. exit;
  872. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  873. begin
  874. RegReadByInstruction := true;
  875. exit
  876. end;
  877. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  878. begin
  879. RegReadByInstruction := true;
  880. exit
  881. end;
  882. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  883. begin
  884. RegReadByInstruction := true;
  885. exit
  886. end;
  887. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  888. begin
  889. RegReadByInstruction := true;
  890. exit
  891. end;
  892. end;
  893. end;
  894. end;
  895. end;
  896. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  897. begin
  898. result:=false;
  899. if p1.typ<>ait_instruction then
  900. exit;
  901. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  902. exit(true);
  903. if (getregtype(reg)=R_INTREGISTER) and
  904. { change information for xmm movsd are not correct }
  905. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  906. begin
  907. { Handle instructions that behave differently depending on the size and operand count }
  908. case taicpu(p1).opcode of
  909. A_MUL, A_DIV, A_IDIV:
  910. if taicpu(p1).opsize = S_B then
  911. Result := (getsupreg(Reg) = RS_EAX)
  912. else
  913. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  914. A_IMUL:
  915. if taicpu(p1).ops = 1 then
  916. begin
  917. if taicpu(p1).opsize = S_B then
  918. Result := (getsupreg(Reg) = RS_EAX)
  919. else
  920. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  921. end;
  922. { If ops are greater than 1, call inherited method }
  923. else
  924. case getsupreg(reg) of
  925. { RS_EAX = RS_RAX on x86-64 }
  926. RS_EAX:
  927. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. RS_ECX:
  929. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. RS_EDX:
  931. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. RS_EBX:
  933. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. RS_ESP:
  935. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  936. RS_EBP:
  937. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  938. RS_ESI:
  939. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  940. RS_EDI:
  941. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  942. else
  943. ;
  944. end;
  945. end;
  946. if result then
  947. exit;
  948. end
  949. else if getregtype(reg)=R_MMREGISTER then
  950. begin
  951. case getsupreg(reg) of
  952. RS_XMM0:
  953. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  954. else
  955. ;
  956. end;
  957. if result then
  958. exit;
  959. end
  960. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  961. begin
  962. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  963. exit(true);
  964. case getsubreg(reg) of
  965. R_SUBFLAGCARRY:
  966. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  967. R_SUBFLAGPARITY:
  968. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  969. R_SUBFLAGAUXILIARY:
  970. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  971. R_SUBFLAGZERO:
  972. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  973. R_SUBFLAGSIGN:
  974. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  975. R_SUBFLAGOVERFLOW:
  976. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  977. R_SUBFLAGINTERRUPT:
  978. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  979. R_SUBFLAGDIRECTION:
  980. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  981. R_SUBW,R_SUBD,R_SUBQ:
  982. { Everything except the direction bits }
  983. Result:=
  984. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  985. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  986. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  987. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  988. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  989. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  990. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  991. else
  992. ;
  993. end;
  994. if result then
  995. exit;
  996. end
  997. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  998. exit(true);
  999. Result:=inherited RegInInstruction(Reg, p1);
  1000. end;
  1001. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1002. const
  1003. WriteOps: array[0..3] of set of TInsChange =
  1004. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1005. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1006. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1007. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1008. var
  1009. OperIdx: Integer;
  1010. begin
  1011. Result := False;
  1012. if p1.typ <> ait_instruction then
  1013. exit;
  1014. with insprop[taicpu(p1).opcode] do
  1015. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1016. begin
  1017. case getsubreg(reg) of
  1018. R_SUBW,R_SUBD,R_SUBQ:
  1019. Result :=
  1020. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1021. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1022. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1023. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1024. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1025. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1026. R_SUBFLAGCARRY:
  1027. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1028. R_SUBFLAGPARITY:
  1029. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1030. R_SUBFLAGAUXILIARY:
  1031. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1032. R_SUBFLAGZERO:
  1033. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1034. R_SUBFLAGSIGN:
  1035. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1036. R_SUBFLAGOVERFLOW:
  1037. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1038. R_SUBFLAGINTERRUPT:
  1039. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1040. R_SUBFLAGDIRECTION:
  1041. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1042. else
  1043. internalerror(2017042602);
  1044. end;
  1045. exit;
  1046. end;
  1047. case taicpu(p1).opcode of
  1048. A_CALL:
  1049. { We could potentially set Result to False if the register in
  1050. question is non-volatile for the subroutine's calling convention,
  1051. but this would require detecting the calling convention in use and
  1052. also assuming that the routine doesn't contain malformed assembly
  1053. language, for example... so it could only be done under -O4 as it
  1054. would be considered a side-effect. [Kit] }
  1055. Result := True;
  1056. A_MOVSD:
  1057. { special handling for SSE MOVSD }
  1058. if (taicpu(p1).ops>0) then
  1059. begin
  1060. if taicpu(p1).ops<>2 then
  1061. internalerror(2017042703);
  1062. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1063. end;
  1064. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1065. so fix it here (FK)
  1066. }
  1067. A_VMOVSS,
  1068. A_VMOVSD:
  1069. begin
  1070. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1071. exit;
  1072. end;
  1073. A_MUL, A_DIV, A_IDIV:
  1074. begin
  1075. if taicpu(p1).opsize = S_B then
  1076. Result := (getsupreg(Reg) = RS_EAX)
  1077. else
  1078. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1079. end;
  1080. A_IMUL:
  1081. begin
  1082. if taicpu(p1).ops = 1 then
  1083. begin
  1084. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1085. end
  1086. else
  1087. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1088. Exit;
  1089. end;
  1090. else
  1091. ;
  1092. end;
  1093. if Result then
  1094. exit;
  1095. with insprop[taicpu(p1).opcode] do
  1096. begin
  1097. if getregtype(reg)=R_INTREGISTER then
  1098. begin
  1099. case getsupreg(reg) of
  1100. RS_EAX:
  1101. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1102. begin
  1103. Result := True;
  1104. exit
  1105. end;
  1106. RS_ECX:
  1107. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1108. begin
  1109. Result := True;
  1110. exit
  1111. end;
  1112. RS_EDX:
  1113. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1114. begin
  1115. Result := True;
  1116. exit
  1117. end;
  1118. RS_EBX:
  1119. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1120. begin
  1121. Result := True;
  1122. exit
  1123. end;
  1124. RS_ESP:
  1125. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1126. begin
  1127. Result := True;
  1128. exit
  1129. end;
  1130. RS_EBP:
  1131. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1132. begin
  1133. Result := True;
  1134. exit
  1135. end;
  1136. RS_ESI:
  1137. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1138. begin
  1139. Result := True;
  1140. exit
  1141. end;
  1142. RS_EDI:
  1143. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1144. begin
  1145. Result := True;
  1146. exit
  1147. end;
  1148. end;
  1149. end;
  1150. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1151. if (WriteOps[OperIdx]*Ch<>[]) and
  1152. { The register doesn't get modified inside a reference }
  1153. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1154. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1155. begin
  1156. Result := true;
  1157. exit
  1158. end;
  1159. end;
  1160. end;
  1161. {$ifdef DEBUG_AOPTCPU}
  1162. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1163. begin
  1164. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1165. end;
  1166. function debug_tostr(i: tcgint): string; inline;
  1167. begin
  1168. Result := tostr(i);
  1169. end;
  1170. function debug_hexstr(i: tcgint): string;
  1171. begin
  1172. Result := '0x';
  1173. case i of
  1174. 0..$FF:
  1175. Result := Result + hexstr(i, 2);
  1176. $100..$FFFF:
  1177. Result := Result + hexstr(i, 4);
  1178. $10000..$FFFFFF:
  1179. Result := Result + hexstr(i, 6);
  1180. $1000000..$FFFFFFFF:
  1181. Result := Result + hexstr(i, 8);
  1182. else
  1183. Result := Result + hexstr(i, 16);
  1184. end;
  1185. end;
  1186. function debug_regname(r: TRegister): string; inline;
  1187. begin
  1188. Result := '%' + std_regname(r);
  1189. end;
  1190. { Debug output function - creates a string representation of an operator }
  1191. function debug_operstr(oper: TOper): string;
  1192. begin
  1193. case oper.typ of
  1194. top_const:
  1195. Result := '$' + debug_tostr(oper.val);
  1196. top_reg:
  1197. Result := debug_regname(oper.reg);
  1198. top_ref:
  1199. begin
  1200. if oper.ref^.offset <> 0 then
  1201. Result := debug_tostr(oper.ref^.offset) + '('
  1202. else
  1203. Result := '(';
  1204. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1205. begin
  1206. Result := Result + debug_regname(oper.ref^.base);
  1207. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1208. Result := Result + ',' + debug_regname(oper.ref^.index);
  1209. end
  1210. else
  1211. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1212. Result := Result + debug_regname(oper.ref^.index);
  1213. if (oper.ref^.scalefactor > 1) then
  1214. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1215. else
  1216. Result := Result + ')';
  1217. end;
  1218. else
  1219. Result := '[UNKNOWN]';
  1220. end;
  1221. end;
  1222. function debug_op2str(opcode: tasmop): string; inline;
  1223. begin
  1224. Result := std_op2str[opcode];
  1225. end;
  1226. function debug_opsize2str(opsize: topsize): string; inline;
  1227. begin
  1228. Result := gas_opsize2str[opsize];
  1229. end;
  1230. {$else DEBUG_AOPTCPU}
  1231. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1232. begin
  1233. end;
  1234. function debug_tostr(i: tcgint): string; inline;
  1235. begin
  1236. Result := '';
  1237. end;
  1238. function debug_hexstr(i: tcgint): string; inline;
  1239. begin
  1240. Result := '';
  1241. end;
  1242. function debug_regname(r: TRegister): string; inline;
  1243. begin
  1244. Result := '';
  1245. end;
  1246. function debug_operstr(oper: TOper): string; inline;
  1247. begin
  1248. Result := '';
  1249. end;
  1250. function debug_op2str(opcode: tasmop): string; inline;
  1251. begin
  1252. Result := '';
  1253. end;
  1254. function debug_opsize2str(opsize: topsize): string; inline;
  1255. begin
  1256. Result := '';
  1257. end;
  1258. {$endif DEBUG_AOPTCPU}
  1259. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1260. begin
  1261. {$ifdef x86_64}
  1262. { Always fine on x86-64 }
  1263. Result := True;
  1264. {$else x86_64}
  1265. Result :=
  1266. {$ifdef i8086}
  1267. (current_settings.cputype >= cpu_386) and
  1268. {$endif i8086}
  1269. (
  1270. { Always accept if optimising for size }
  1271. (cs_opt_size in current_settings.optimizerswitches) or
  1272. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1273. (current_settings.optimizecputype >= cpu_Pentium2)
  1274. );
  1275. {$endif x86_64}
  1276. end;
  1277. { Attempts to allocate a volatile integer register for use between p and hp,
  1278. using AUsedRegs for the current register usage information. Returns NR_NO
  1279. if no free register could be found }
  1280. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1281. var
  1282. RegSet: TCPURegisterSet;
  1283. CurrentSuperReg: Integer;
  1284. CurrentReg: TRegister;
  1285. Currentp: tai;
  1286. Breakout: Boolean;
  1287. begin
  1288. Result := NR_NO;
  1289. RegSet :=
  1290. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1291. current_procinfo.saved_regs_int;
  1292. (*
  1293. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1294. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1295. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1296. *)
  1297. for CurrentSuperReg in RegSet do
  1298. begin
  1299. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1300. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1301. {$if defined(i386) or defined(i8086)}
  1302. { If the target size is 8-bit, make sure we can actually encode it }
  1303. and (
  1304. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1305. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1306. )
  1307. {$endif i386 or i8086}
  1308. then
  1309. begin
  1310. Currentp := p;
  1311. Breakout := False;
  1312. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1313. begin
  1314. case Currentp.typ of
  1315. ait_instruction:
  1316. begin
  1317. if RegInInstruction(CurrentReg, Currentp) then
  1318. begin
  1319. Breakout := True;
  1320. Break;
  1321. end;
  1322. { Cannot allocate across an unconditional jump }
  1323. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1324. Exit;
  1325. end;
  1326. ait_marker:
  1327. { Don't try anything more if a marker is hit }
  1328. Exit;
  1329. ait_regalloc:
  1330. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. else
  1336. ;
  1337. end;
  1338. end;
  1339. if Breakout then
  1340. { Try the next register }
  1341. Continue;
  1342. { We have a free register available }
  1343. Result := CurrentReg;
  1344. if not DontAlloc then
  1345. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1346. Exit;
  1347. end;
  1348. end;
  1349. end;
  1350. { Attempts to allocate a volatile MM register for use between p and hp,
  1351. using AUsedRegs for the current register usage information. Returns NR_NO
  1352. if no free register could be found }
  1353. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1354. var
  1355. RegSet: TCPURegisterSet;
  1356. CurrentSuperReg: Integer;
  1357. CurrentReg: TRegister;
  1358. Currentp: tai;
  1359. Breakout: Boolean;
  1360. begin
  1361. Result := NR_NO;
  1362. RegSet :=
  1363. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1364. current_procinfo.saved_regs_mm;
  1365. for CurrentSuperReg in RegSet do
  1366. begin
  1367. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1368. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1369. begin
  1370. Currentp := p;
  1371. Breakout := False;
  1372. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1373. begin
  1374. case Currentp.typ of
  1375. ait_instruction:
  1376. begin
  1377. if RegInInstruction(CurrentReg, Currentp) then
  1378. begin
  1379. Breakout := True;
  1380. Break;
  1381. end;
  1382. { Cannot allocate across an unconditional jump }
  1383. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1384. Exit;
  1385. end;
  1386. ait_marker:
  1387. { Don't try anything more if a marker is hit }
  1388. Exit;
  1389. ait_regalloc:
  1390. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1391. begin
  1392. Breakout := True;
  1393. Break;
  1394. end;
  1395. else
  1396. ;
  1397. end;
  1398. end;
  1399. if Breakout then
  1400. { Try the next register }
  1401. Continue;
  1402. { We have a free register available }
  1403. Result := CurrentReg;
  1404. if not DontAlloc then
  1405. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1406. Exit;
  1407. end;
  1408. end;
  1409. end;
  1410. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1411. begin
  1412. if not SuperRegistersEqual(reg1,reg2) then
  1413. exit(false);
  1414. if getregtype(reg1)<>R_INTREGISTER then
  1415. exit(true); {because SuperRegisterEqual is true}
  1416. case getsubreg(reg1) of
  1417. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1418. higher, it preserves the high bits, so the new value depends on
  1419. reg2's previous value. In other words, it is equivalent to doing:
  1420. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1421. R_SUBL:
  1422. exit(getsubreg(reg2)=R_SUBL);
  1423. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1424. higher, it actually does a:
  1425. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1426. R_SUBH:
  1427. exit(getsubreg(reg2)=R_SUBH);
  1428. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1429. bits of reg2:
  1430. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1431. R_SUBW:
  1432. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1433. { a write to R_SUBD always overwrites every other subregister,
  1434. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1435. R_SUBD,
  1436. R_SUBQ:
  1437. exit(true);
  1438. else
  1439. internalerror(2017042801);
  1440. end;
  1441. end;
  1442. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1443. begin
  1444. if not SuperRegistersEqual(reg1,reg2) then
  1445. exit(false);
  1446. if getregtype(reg1)<>R_INTREGISTER then
  1447. exit(true); {because SuperRegisterEqual is true}
  1448. case getsubreg(reg1) of
  1449. R_SUBL:
  1450. exit(getsubreg(reg2)<>R_SUBH);
  1451. R_SUBH:
  1452. exit(getsubreg(reg2)<>R_SUBL);
  1453. R_SUBW,
  1454. R_SUBD,
  1455. R_SUBQ:
  1456. exit(true);
  1457. else
  1458. internalerror(2017042802);
  1459. end;
  1460. end;
  1461. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1462. var
  1463. hp1 : tai;
  1464. l : TCGInt;
  1465. begin
  1466. result:=false;
  1467. if not(GetNextInstruction(p, hp1)) then
  1468. exit;
  1469. { changes the code sequence
  1470. shr/sar const1, x
  1471. shl const2, x
  1472. to
  1473. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1474. if (taicpu(p).oper[0]^.typ = top_const) and
  1475. MatchInstruction(hp1,A_SHL,[]) and
  1476. (taicpu(hp1).oper[0]^.typ = top_const) and
  1477. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1478. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1479. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1480. begin
  1481. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1482. not(cs_opt_size in current_settings.optimizerswitches) then
  1483. begin
  1484. { shr/sar const1, %reg
  1485. shl const2, %reg
  1486. with const1 > const2 }
  1487. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1488. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1489. taicpu(hp1).opcode := A_AND;
  1490. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1491. case taicpu(p).opsize Of
  1492. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1493. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1494. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1495. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1496. else
  1497. Internalerror(2017050703)
  1498. end;
  1499. end
  1500. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1501. not(cs_opt_size in current_settings.optimizerswitches) then
  1502. begin
  1503. { shr/sar const1, %reg
  1504. shl const2, %reg
  1505. with const1 < const2 }
  1506. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1507. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1508. taicpu(p).opcode := A_AND;
  1509. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1510. case taicpu(p).opsize Of
  1511. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1512. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1513. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1514. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1515. else
  1516. Internalerror(2017050702)
  1517. end;
  1518. end
  1519. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1520. begin
  1521. { shr/sar const1, %reg
  1522. shl const2, %reg
  1523. with const1 = const2 }
  1524. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1525. taicpu(p).opcode := A_AND;
  1526. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1527. case taicpu(p).opsize Of
  1528. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1529. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1530. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1531. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1532. else
  1533. Internalerror(2017050701)
  1534. end;
  1535. RemoveInstruction(hp1);
  1536. end;
  1537. end;
  1538. end;
  1539. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1540. var
  1541. opsize : topsize;
  1542. hp1, hp2 : tai;
  1543. tmpref : treference;
  1544. ShiftValue : Cardinal;
  1545. BaseValue : TCGInt;
  1546. begin
  1547. result:=false;
  1548. opsize:=taicpu(p).opsize;
  1549. { changes certain "imul const, %reg"'s to lea sequences }
  1550. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1551. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1552. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1553. if (taicpu(p).oper[0]^.val = 1) then
  1554. if (taicpu(p).ops = 2) then
  1555. { remove "imul $1, reg" }
  1556. begin
  1557. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1558. Result := RemoveCurrentP(p);
  1559. end
  1560. else
  1561. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1562. begin
  1563. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1564. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1565. asml.InsertAfter(hp1, p);
  1566. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1567. RemoveCurrentP(p, hp1);
  1568. Result := True;
  1569. end
  1570. else if ((taicpu(p).ops <= 2) or
  1571. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1572. not(cs_opt_size in current_settings.optimizerswitches) and
  1573. (not(GetNextInstruction(p, hp1)) or
  1574. not((tai(hp1).typ = ait_instruction) and
  1575. ((taicpu(hp1).opcode=A_Jcc) and
  1576. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1577. begin
  1578. {
  1579. imul X, reg1, reg2 to
  1580. lea (reg1,reg1,Y), reg2
  1581. shl ZZ,reg2
  1582. imul XX, reg1 to
  1583. lea (reg1,reg1,YY), reg1
  1584. shl ZZ,reg2
  1585. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1586. it does not exist as a separate optimization target in FPC though.
  1587. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1588. at most two zeros
  1589. }
  1590. reference_reset(tmpref,1,[]);
  1591. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1592. begin
  1593. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1594. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1595. TmpRef.base := taicpu(p).oper[1]^.reg;
  1596. TmpRef.index := taicpu(p).oper[1]^.reg;
  1597. if not(BaseValue in [3,5,9]) then
  1598. Internalerror(2018110101);
  1599. TmpRef.ScaleFactor := BaseValue-1;
  1600. if (taicpu(p).ops = 2) then
  1601. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1602. else
  1603. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1604. AsmL.InsertAfter(hp1,p);
  1605. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1606. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1607. RemoveCurrentP(p, hp1);
  1608. if ShiftValue>0 then
  1609. begin
  1610. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1611. AsmL.InsertAfter(hp2,hp1);
  1612. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1613. end;
  1614. Result := True;
  1615. end;
  1616. end;
  1617. end;
  1618. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1619. begin
  1620. Result := False;
  1621. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1622. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1623. begin
  1624. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1625. taicpu(p).opcode := A_MOV;
  1626. Result := True;
  1627. end;
  1628. end;
  1629. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1630. var
  1631. p: taicpu absolute hp; { Implicit typecast }
  1632. i: Integer;
  1633. begin
  1634. Result := False;
  1635. if not assigned(hp) or
  1636. (hp.typ <> ait_instruction) then
  1637. Exit;
  1638. Prefetch(insprop[p.opcode]);
  1639. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1640. with insprop[p.opcode] do
  1641. begin
  1642. case getsubreg(reg) of
  1643. R_SUBW,R_SUBD,R_SUBQ:
  1644. Result:=
  1645. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1646. uncommon flags are checked first }
  1647. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1648. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1649. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1652. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1653. R_SUBFLAGCARRY:
  1654. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1655. R_SUBFLAGPARITY:
  1656. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1657. R_SUBFLAGAUXILIARY:
  1658. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1659. R_SUBFLAGZERO:
  1660. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1661. R_SUBFLAGSIGN:
  1662. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1663. R_SUBFLAGOVERFLOW:
  1664. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1665. R_SUBFLAGINTERRUPT:
  1666. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1667. R_SUBFLAGDIRECTION:
  1668. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1669. else
  1670. internalerror(2017050501);
  1671. end;
  1672. exit;
  1673. end;
  1674. { Handle special cases first }
  1675. case p.opcode of
  1676. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1677. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1678. begin
  1679. Result :=
  1680. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1681. (p.oper[1]^.typ = top_reg) and
  1682. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1683. (
  1684. (p.oper[0]^.typ = top_const) or
  1685. (
  1686. (p.oper[0]^.typ = top_reg) and
  1687. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1688. ) or (
  1689. (p.oper[0]^.typ = top_ref) and
  1690. not RegInRef(reg,p.oper[0]^.ref^)
  1691. )
  1692. );
  1693. end;
  1694. A_MUL, A_IMUL:
  1695. Result :=
  1696. (
  1697. (p.ops=3) and { IMUL only }
  1698. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1699. (
  1700. (
  1701. (p.oper[1]^.typ=top_reg) and
  1702. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1703. ) or (
  1704. (p.oper[1]^.typ=top_ref) and
  1705. not RegInRef(reg,p.oper[1]^.ref^)
  1706. )
  1707. )
  1708. ) or (
  1709. (
  1710. (p.ops=1) and
  1711. (
  1712. (
  1713. (
  1714. (p.oper[0]^.typ=top_reg) and
  1715. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1716. )
  1717. ) or (
  1718. (p.oper[0]^.typ=top_ref) and
  1719. not RegInRef(reg,p.oper[0]^.ref^)
  1720. )
  1721. ) and (
  1722. (
  1723. (p.opsize=S_B) and
  1724. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1725. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1726. ) or (
  1727. (p.opsize=S_W) and
  1728. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1729. ) or (
  1730. (p.opsize=S_L) and
  1731. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1732. {$ifdef x86_64}
  1733. ) or (
  1734. (p.opsize=S_Q) and
  1735. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1736. {$endif x86_64}
  1737. )
  1738. )
  1739. )
  1740. );
  1741. A_CBW:
  1742. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1743. {$ifndef x86_64}
  1744. A_LDS:
  1745. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1746. A_LES:
  1747. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1748. {$endif not x86_64}
  1749. A_LFS:
  1750. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1751. A_LGS:
  1752. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1753. A_LSS:
  1754. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1755. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1756. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1757. A_LODSB:
  1758. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1759. A_LODSW:
  1760. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1761. {$ifdef x86_64}
  1762. A_LODSQ:
  1763. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1764. {$endif x86_64}
  1765. A_LODSD:
  1766. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1767. A_FSTSW, A_FNSTSW:
  1768. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1769. else
  1770. begin
  1771. with insprop[p.opcode] do
  1772. begin
  1773. if (
  1774. { xor %reg,%reg etc. is classed as a new value }
  1775. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1776. MatchOpType(p, top_reg, top_reg) and
  1777. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1778. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1779. ) then
  1780. begin
  1781. Result := True;
  1782. Exit;
  1783. end;
  1784. { Make sure the entire register is overwritten }
  1785. if (getregtype(reg) = R_INTREGISTER) then
  1786. begin
  1787. if (p.ops > 0) then
  1788. begin
  1789. if RegInOp(reg, p.oper[0]^) then
  1790. begin
  1791. if (p.oper[0]^.typ = top_ref) then
  1792. begin
  1793. if RegInRef(reg, p.oper[0]^.ref^) then
  1794. begin
  1795. Result := False;
  1796. Exit;
  1797. end;
  1798. end
  1799. else if (p.oper[0]^.typ = top_reg) then
  1800. begin
  1801. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1802. begin
  1803. Result := False;
  1804. Exit;
  1805. end
  1806. else if ([Ch_WOp1]*Ch<>[]) then
  1807. begin
  1808. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1809. Result := True
  1810. else
  1811. begin
  1812. Result := False;
  1813. Exit;
  1814. end;
  1815. end;
  1816. end;
  1817. end;
  1818. if (p.ops > 1) then
  1819. begin
  1820. if RegInOp(reg, p.oper[1]^) then
  1821. begin
  1822. if (p.oper[1]^.typ = top_ref) then
  1823. begin
  1824. if RegInRef(reg, p.oper[1]^.ref^) then
  1825. begin
  1826. Result := False;
  1827. Exit;
  1828. end;
  1829. end
  1830. else if (p.oper[1]^.typ = top_reg) then
  1831. begin
  1832. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1833. begin
  1834. Result := False;
  1835. Exit;
  1836. end
  1837. else if ([Ch_WOp2]*Ch<>[]) then
  1838. begin
  1839. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1840. Result := True
  1841. else
  1842. begin
  1843. Result := False;
  1844. Exit;
  1845. end;
  1846. end;
  1847. end;
  1848. end;
  1849. if (p.ops > 2) then
  1850. begin
  1851. if RegInOp(reg, p.oper[2]^) then
  1852. begin
  1853. if (p.oper[2]^.typ = top_ref) then
  1854. begin
  1855. if RegInRef(reg, p.oper[2]^.ref^) then
  1856. begin
  1857. Result := False;
  1858. Exit;
  1859. end;
  1860. end
  1861. else if (p.oper[2]^.typ = top_reg) then
  1862. begin
  1863. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1864. begin
  1865. Result := False;
  1866. Exit;
  1867. end
  1868. else if ([Ch_WOp3]*Ch<>[]) then
  1869. begin
  1870. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1871. Result := True
  1872. else
  1873. begin
  1874. Result := False;
  1875. Exit;
  1876. end;
  1877. end;
  1878. end;
  1879. end;
  1880. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1881. begin
  1882. if (p.oper[3]^.typ = top_ref) then
  1883. begin
  1884. if RegInRef(reg, p.oper[3]^.ref^) then
  1885. begin
  1886. Result := False;
  1887. Exit;
  1888. end;
  1889. end
  1890. else if (p.oper[3]^.typ = top_reg) then
  1891. begin
  1892. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1893. begin
  1894. Result := False;
  1895. Exit;
  1896. end
  1897. else if ([Ch_WOp4]*Ch<>[]) then
  1898. begin
  1899. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1900. Result := True
  1901. else
  1902. begin
  1903. Result := False;
  1904. Exit;
  1905. end;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1913. case getsupreg(reg) of
  1914. RS_EAX:
  1915. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1916. begin
  1917. Result := True;
  1918. Exit;
  1919. end;
  1920. RS_ECX:
  1921. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1922. begin
  1923. Result := True;
  1924. Exit;
  1925. end;
  1926. RS_EDX:
  1927. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1928. begin
  1929. Result := True;
  1930. Exit;
  1931. end;
  1932. RS_EBX:
  1933. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1934. begin
  1935. Result := True;
  1936. Exit;
  1937. end;
  1938. RS_ESP:
  1939. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1940. begin
  1941. Result := True;
  1942. Exit;
  1943. end;
  1944. RS_EBP:
  1945. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1946. begin
  1947. Result := True;
  1948. Exit;
  1949. end;
  1950. RS_ESI:
  1951. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1952. begin
  1953. Result := True;
  1954. Exit;
  1955. end;
  1956. RS_EDI:
  1957. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1958. begin
  1959. Result := True;
  1960. Exit;
  1961. end;
  1962. else
  1963. ;
  1964. end;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. end;
  1970. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1971. var
  1972. hp2,hp3 : tai;
  1973. begin
  1974. { some x86-64 issue a NOP before the real exit code }
  1975. if MatchInstruction(p,A_NOP,[]) then
  1976. GetNextInstruction(p,p);
  1977. result:=assigned(p) and (p.typ=ait_instruction) and
  1978. ((taicpu(p).opcode = A_RET) or
  1979. ((taicpu(p).opcode=A_LEAVE) and
  1980. GetNextInstruction(p,hp2) and
  1981. MatchInstruction(hp2,A_RET,[S_NO])
  1982. ) or
  1983. (((taicpu(p).opcode=A_LEA) and
  1984. MatchOpType(taicpu(p),top_ref,top_reg) and
  1985. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1986. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1987. ) and
  1988. GetNextInstruction(p,hp2) and
  1989. MatchInstruction(hp2,A_RET,[S_NO])
  1990. ) or
  1991. ((((taicpu(p).opcode=A_MOV) and
  1992. MatchOpType(taicpu(p),top_reg,top_reg) and
  1993. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1994. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1995. ((taicpu(p).opcode=A_LEA) and
  1996. MatchOpType(taicpu(p),top_ref,top_reg) and
  1997. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1998. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1999. )
  2000. ) and
  2001. GetNextInstruction(p,hp2) and
  2002. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2003. MatchOpType(taicpu(hp2),top_reg) and
  2004. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2005. GetNextInstruction(hp2,hp3) and
  2006. MatchInstruction(hp3,A_RET,[S_NO])
  2007. )
  2008. );
  2009. end;
  2010. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2011. begin
  2012. isFoldableArithOp := False;
  2013. case hp1.opcode of
  2014. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2015. isFoldableArithOp :=
  2016. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2017. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2018. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2019. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2020. (taicpu(hp1).oper[1]^.reg = reg);
  2021. A_INC,A_DEC,A_NEG,A_NOT:
  2022. isFoldableArithOp :=
  2023. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2024. (taicpu(hp1).oper[0]^.reg = reg);
  2025. else
  2026. ;
  2027. end;
  2028. end;
  2029. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2030. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2031. var
  2032. hp2: tai;
  2033. begin
  2034. hp2 := p;
  2035. repeat
  2036. hp2 := tai(hp2.previous);
  2037. if assigned(hp2) and
  2038. (hp2.typ = ait_regalloc) and
  2039. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2040. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2041. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2042. begin
  2043. RemoveInstruction(hp2);
  2044. break;
  2045. end;
  2046. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2047. end;
  2048. begin
  2049. case current_procinfo.procdef.returndef.typ of
  2050. arraydef,recorddef,pointerdef,
  2051. stringdef,enumdef,procdef,objectdef,errordef,
  2052. filedef,setdef,procvardef,
  2053. classrefdef,forwarddef:
  2054. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2055. orddef:
  2056. if current_procinfo.procdef.returndef.size <> 0 then
  2057. begin
  2058. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2059. { for int64/qword }
  2060. if current_procinfo.procdef.returndef.size = 8 then
  2061. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2062. end;
  2063. else
  2064. ;
  2065. end;
  2066. end;
  2067. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2068. var
  2069. hp1,hp2 : tai;
  2070. begin
  2071. result:=false;
  2072. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2073. begin
  2074. { vmova* reg1,reg1
  2075. =>
  2076. <nop> }
  2077. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2078. begin
  2079. RemoveCurrentP(p);
  2080. result:=true;
  2081. exit;
  2082. end;
  2083. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2084. (hp1.typ = ait_instruction) and
  2085. (
  2086. { Under -O2 and below, the instructions are always adjacent }
  2087. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2088. (taicpu(hp1).ops <= 1) or
  2089. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2090. { If reg1 = reg3, reg1 must not be modified in between }
  2091. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2092. ) then
  2093. begin
  2094. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2095. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2096. begin
  2097. { vmova* reg1,reg2
  2098. ...
  2099. vmova* reg2,reg3
  2100. dealloc reg2
  2101. =>
  2102. vmova* reg1,reg3 }
  2103. TransferUsedRegs(TmpUsedRegs);
  2104. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2105. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2106. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2107. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2108. begin
  2109. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2110. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2111. TransferUsedRegs(TmpUsedRegs);
  2112. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2113. RemoveInstruction(hp1);
  2114. result:=true;
  2115. exit;
  2116. end;
  2117. { special case:
  2118. vmova* reg1,<op>
  2119. ...
  2120. vmova* <op>,reg1
  2121. =>
  2122. vmova* reg1,<op> }
  2123. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2124. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2125. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2126. ) then
  2127. begin
  2128. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2129. RemoveInstruction(hp1);
  2130. result:=true;
  2131. exit;
  2132. end
  2133. end
  2134. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2135. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2136. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2137. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2138. ) and
  2139. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2140. begin
  2141. { vmova* reg1,reg2
  2142. ...
  2143. vmovs* reg2,<op>
  2144. dealloc reg2
  2145. =>
  2146. vmovs* reg1,<op> }
  2147. TransferUsedRegs(TmpUsedRegs);
  2148. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2149. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2150. begin
  2151. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2152. taicpu(p).opcode:=taicpu(hp1).opcode;
  2153. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2154. TransferUsedRegs(TmpUsedRegs);
  2155. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2156. RemoveInstruction(hp1);
  2157. result:=true;
  2158. exit;
  2159. end
  2160. end;
  2161. if MatchInstruction(hp1,[A_VFMADDPD,
  2162. A_VFMADD132PD,
  2163. A_VFMADD132PS,
  2164. A_VFMADD132SD,
  2165. A_VFMADD132SS,
  2166. A_VFMADD213PD,
  2167. A_VFMADD213PS,
  2168. A_VFMADD213SD,
  2169. A_VFMADD213SS,
  2170. A_VFMADD231PD,
  2171. A_VFMADD231PS,
  2172. A_VFMADD231SD,
  2173. A_VFMADD231SS,
  2174. A_VFMADDSUB132PD,
  2175. A_VFMADDSUB132PS,
  2176. A_VFMADDSUB213PD,
  2177. A_VFMADDSUB213PS,
  2178. A_VFMADDSUB231PD,
  2179. A_VFMADDSUB231PS,
  2180. A_VFMSUB132PD,
  2181. A_VFMSUB132PS,
  2182. A_VFMSUB132SD,
  2183. A_VFMSUB132SS,
  2184. A_VFMSUB213PD,
  2185. A_VFMSUB213PS,
  2186. A_VFMSUB213SD,
  2187. A_VFMSUB213SS,
  2188. A_VFMSUB231PD,
  2189. A_VFMSUB231PS,
  2190. A_VFMSUB231SD,
  2191. A_VFMSUB231SS,
  2192. A_VFMSUBADD132PD,
  2193. A_VFMSUBADD132PS,
  2194. A_VFMSUBADD213PD,
  2195. A_VFMSUBADD213PS,
  2196. A_VFMSUBADD231PD,
  2197. A_VFMSUBADD231PS,
  2198. A_VFNMADD132PD,
  2199. A_VFNMADD132PS,
  2200. A_VFNMADD132SD,
  2201. A_VFNMADD132SS,
  2202. A_VFNMADD213PD,
  2203. A_VFNMADD213PS,
  2204. A_VFNMADD213SD,
  2205. A_VFNMADD213SS,
  2206. A_VFNMADD231PD,
  2207. A_VFNMADD231PS,
  2208. A_VFNMADD231SD,
  2209. A_VFNMADD231SS,
  2210. A_VFNMSUB132PD,
  2211. A_VFNMSUB132PS,
  2212. A_VFNMSUB132SD,
  2213. A_VFNMSUB132SS,
  2214. A_VFNMSUB213PD,
  2215. A_VFNMSUB213PS,
  2216. A_VFNMSUB213SD,
  2217. A_VFNMSUB213SS,
  2218. A_VFNMSUB231PD,
  2219. A_VFNMSUB231PS,
  2220. A_VFNMSUB231SD,
  2221. A_VFNMSUB231SS],[S_NO]) and
  2222. { we mix single and double opperations here because we assume that the compiler
  2223. generates vmovapd only after double operations and vmovaps only after single operations }
  2224. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2225. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2226. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2227. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2228. begin
  2229. TransferUsedRegs(TmpUsedRegs);
  2230. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2231. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2232. begin
  2233. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2234. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2235. RemoveCurrentP(p)
  2236. else
  2237. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2238. RemoveInstruction(hp2);
  2239. end;
  2240. end
  2241. else if (hp1.typ = ait_instruction) and
  2242. (((taicpu(p).opcode=A_MOVAPS) and
  2243. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2244. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2245. ((taicpu(p).opcode=A_MOVAPD) and
  2246. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2247. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2248. ) and
  2249. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2250. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2251. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2252. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2253. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2254. { change
  2255. movapX reg,reg2
  2256. addsX/subsX/... reg3, reg2
  2257. movapX reg2,reg
  2258. to
  2259. addsX/subsX/... reg3,reg
  2260. }
  2261. begin
  2262. TransferUsedRegs(TmpUsedRegs);
  2263. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2264. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2265. begin
  2266. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2267. debug_op2str(taicpu(p).opcode)+' '+
  2268. debug_op2str(taicpu(hp1).opcode)+' '+
  2269. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2270. { we cannot eliminate the first move if
  2271. the operations uses the same register for source and dest }
  2272. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2273. { Remember that hp1 is not necessarily the immediate
  2274. next instruction }
  2275. RemoveCurrentP(p);
  2276. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2277. RemoveInstruction(hp2);
  2278. result:=true;
  2279. end;
  2280. end
  2281. else if (hp1.typ = ait_instruction) and
  2282. (((taicpu(p).opcode=A_VMOVAPD) and
  2283. (taicpu(hp1).opcode=A_VCOMISD)) or
  2284. ((taicpu(p).opcode=A_VMOVAPS) and
  2285. ((taicpu(hp1).opcode=A_VCOMISS))
  2286. )
  2287. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2288. { change
  2289. movapX reg,reg1
  2290. vcomisX reg1,reg1
  2291. to
  2292. vcomisX reg,reg
  2293. }
  2294. begin
  2295. TransferUsedRegs(TmpUsedRegs);
  2296. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2297. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2298. begin
  2299. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2300. debug_op2str(taicpu(p).opcode)+' '+
  2301. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2302. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2303. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2304. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2305. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2306. RemoveCurrentP(p);
  2307. result:=true;
  2308. exit;
  2309. end;
  2310. end
  2311. end;
  2312. end;
  2313. end;
  2314. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2315. var
  2316. hp1 : tai;
  2317. begin
  2318. result:=false;
  2319. { replace
  2320. V<Op>X %mreg1,%mreg2,%mreg3
  2321. VMovX %mreg3,%mreg4
  2322. dealloc %mreg3
  2323. by
  2324. V<Op>X %mreg1,%mreg2,%mreg4
  2325. ?
  2326. }
  2327. if GetNextInstruction(p,hp1) and
  2328. { we mix single and double operations here because we assume that the compiler
  2329. generates vmovapd only after double operations and vmovaps only after single operations }
  2330. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2331. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2332. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2333. begin
  2334. TransferUsedRegs(TmpUsedRegs);
  2335. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2336. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2337. begin
  2338. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2339. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2340. RemoveInstruction(hp1);
  2341. result:=true;
  2342. end;
  2343. end;
  2344. end;
  2345. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2346. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2347. begin
  2348. Result := False;
  2349. { For safety reasons, only check for exact register matches }
  2350. { Check base register }
  2351. if (ref.base = AOldReg) then
  2352. begin
  2353. ref.base := ANewReg;
  2354. Result := True;
  2355. end;
  2356. { Check index register }
  2357. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2358. begin
  2359. ref.index := ANewReg;
  2360. Result := True;
  2361. end;
  2362. end;
  2363. { Replaces all references to AOldReg in an operand to ANewReg }
  2364. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2365. var
  2366. OldSupReg, NewSupReg: TSuperRegister;
  2367. OldSubReg, NewSubReg: TSubRegister;
  2368. OldRegType: TRegisterType;
  2369. ThisOper: POper;
  2370. begin
  2371. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2372. Result := False;
  2373. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2374. InternalError(2020011801);
  2375. OldSupReg := getsupreg(AOldReg);
  2376. OldSubReg := getsubreg(AOldReg);
  2377. OldRegType := getregtype(AOldReg);
  2378. NewSupReg := getsupreg(ANewReg);
  2379. NewSubReg := getsubreg(ANewReg);
  2380. if OldRegType <> getregtype(ANewReg) then
  2381. InternalError(2020011802);
  2382. if OldSubReg <> NewSubReg then
  2383. InternalError(2020011803);
  2384. case ThisOper^.typ of
  2385. top_reg:
  2386. if (
  2387. (ThisOper^.reg = AOldReg) or
  2388. (
  2389. (OldRegType = R_INTREGISTER) and
  2390. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2391. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2392. (
  2393. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2394. {$ifndef x86_64}
  2395. and (
  2396. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2397. don't have an 8-bit representation }
  2398. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2399. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2400. )
  2401. {$endif x86_64}
  2402. )
  2403. )
  2404. ) then
  2405. begin
  2406. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2407. Result := True;
  2408. end;
  2409. top_ref:
  2410. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2411. Result := True;
  2412. else
  2413. ;
  2414. end;
  2415. end;
  2416. { Replaces all references to AOldReg in an instruction to ANewReg }
  2417. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2418. const
  2419. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2420. var
  2421. OperIdx: Integer;
  2422. begin
  2423. Result := False;
  2424. for OperIdx := 0 to p.ops - 1 do
  2425. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2426. begin
  2427. { The shift and rotate instructions can only use CL }
  2428. if not (
  2429. (OperIdx = 0) and
  2430. { This second condition just helps to avoid unnecessarily
  2431. calling MatchInstruction for 10 different opcodes }
  2432. (p.oper[0]^.reg = NR_CL) and
  2433. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2434. ) then
  2435. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2436. end
  2437. else if p.oper[OperIdx]^.typ = top_ref then
  2438. { It's okay to replace registers in references that get written to }
  2439. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2440. end;
  2441. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2442. begin
  2443. Result :=
  2444. (ref^.index = NR_NO) and
  2445. (
  2446. {$ifdef x86_64}
  2447. (
  2448. (ref^.base = NR_RIP) and
  2449. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2450. ) or
  2451. {$endif x86_64}
  2452. (ref^.refaddr = addr_full) or
  2453. (ref^.base = NR_STACK_POINTER_REG) or
  2454. (ref^.base = current_procinfo.framepointer)
  2455. );
  2456. end;
  2457. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2458. var
  2459. l: asizeint;
  2460. begin
  2461. Result := False;
  2462. { Should have been checked previously }
  2463. if p.opcode <> A_LEA then
  2464. InternalError(2020072501);
  2465. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2466. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2467. not(cs_opt_size in current_settings.optimizerswitches) then
  2468. exit;
  2469. with p.oper[0]^.ref^ do
  2470. begin
  2471. if (base <> p.oper[1]^.reg) or
  2472. (index <> NR_NO) or
  2473. assigned(symbol) then
  2474. exit;
  2475. l:=offset;
  2476. if (l=1) and UseIncDec then
  2477. begin
  2478. p.opcode:=A_INC;
  2479. p.loadreg(0,p.oper[1]^.reg);
  2480. p.ops:=1;
  2481. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2482. end
  2483. else if (l=-1) and UseIncDec then
  2484. begin
  2485. p.opcode:=A_DEC;
  2486. p.loadreg(0,p.oper[1]^.reg);
  2487. p.ops:=1;
  2488. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2489. end
  2490. else
  2491. begin
  2492. if (l<0) and (l<>-2147483648) then
  2493. begin
  2494. p.opcode:=A_SUB;
  2495. p.loadConst(0,-l);
  2496. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2497. end
  2498. else
  2499. begin
  2500. p.opcode:=A_ADD;
  2501. p.loadConst(0,l);
  2502. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2503. end;
  2504. end;
  2505. end;
  2506. Result := True;
  2507. end;
  2508. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2509. var
  2510. CurrentReg, ReplaceReg: TRegister;
  2511. begin
  2512. Result := False;
  2513. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2514. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2515. case hp.opcode of
  2516. A_FSTSW, A_FNSTSW,
  2517. A_IN, A_INS, A_OUT, A_OUTS,
  2518. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2519. { These routines have explicit operands, but they are restricted in
  2520. what they can be (e.g. IN and OUT can only read from AL, AX or
  2521. EAX. }
  2522. Exit;
  2523. A_IMUL:
  2524. begin
  2525. { The 1-operand version writes to implicit registers
  2526. The 2-operand version reads from the first operator, and reads
  2527. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2528. the 3-operand version reads from a register that it doesn't write to
  2529. }
  2530. case hp.ops of
  2531. 1:
  2532. if (
  2533. (
  2534. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2535. ) or
  2536. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2537. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2538. begin
  2539. Result := True;
  2540. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2541. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2542. end;
  2543. 2:
  2544. { Only modify the first parameter }
  2545. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2546. begin
  2547. Result := True;
  2548. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2549. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2550. end;
  2551. 3:
  2552. { Only modify the second parameter }
  2553. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2554. begin
  2555. Result := True;
  2556. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2557. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2558. end;
  2559. else
  2560. InternalError(2020012901);
  2561. end;
  2562. end;
  2563. else
  2564. if (hp.ops > 0) and
  2565. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2566. begin
  2567. Result := True;
  2568. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2569. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2570. end;
  2571. end;
  2572. end;
  2573. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2574. var
  2575. hp2: tai;
  2576. p_SourceReg, p_TargetReg: TRegister;
  2577. begin
  2578. Result := False;
  2579. { Backward optimisation. If we have:
  2580. func. %reg1,%reg2
  2581. mov %reg2,%reg3
  2582. (dealloc %reg2)
  2583. Change to:
  2584. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2585. Perform similar optimisations with 1, 3 and 4-operand instructions
  2586. that only have one output.
  2587. }
  2588. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2589. begin
  2590. p_SourceReg := taicpu(p).oper[0]^.reg;
  2591. p_TargetReg := taicpu(p).oper[1]^.reg;
  2592. TransferUsedRegs(TmpUsedRegs);
  2593. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2594. GetLastInstruction(p, hp2) and
  2595. (hp2.typ = ait_instruction) and
  2596. { Have to make sure it's an instruction that only reads from
  2597. the first operands and only writes (not reads or modifies) to
  2598. the last one; in essence, a pure function such as BSR, POPCNT
  2599. or ANDN }
  2600. (
  2601. (
  2602. (taicpu(hp2).ops = 1) and
  2603. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2604. ) or
  2605. (
  2606. (taicpu(hp2).ops = 2) and
  2607. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2608. ) or
  2609. (
  2610. (taicpu(hp2).ops = 3) and
  2611. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2612. ) or
  2613. (
  2614. (taicpu(hp2).ops = 4) and
  2615. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2616. )
  2617. ) and
  2618. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2619. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2620. begin
  2621. case taicpu(hp2).opcode of
  2622. A_FSTSW, A_FNSTSW,
  2623. A_IN, A_INS, A_OUT, A_OUTS,
  2624. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2625. { These routines have explicit operands, but they are restricted in
  2626. what they can be (e.g. IN and OUT can only read from AL, AX or
  2627. EAX. }
  2628. ;
  2629. else
  2630. begin
  2631. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2632. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2633. if not RegInInstruction(p_TargetReg, hp2) then
  2634. begin
  2635. { Since we're allocating from an earlier point, we
  2636. need to remove the register from the tracking }
  2637. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2638. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2639. end;
  2640. RemoveCurrentp(p, hp1);
  2641. { If the Func was another MOV instruction, we might get
  2642. "mov %reg,%reg" that doesn't get removed in Pass 2
  2643. otherwise, so deal with it here (also do something
  2644. similar with lea (%reg),%reg}
  2645. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2646. begin
  2647. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2648. if p = hp2 then
  2649. RemoveCurrentp(p)
  2650. else
  2651. RemoveInstruction(hp2);
  2652. end;
  2653. Result := True;
  2654. Exit;
  2655. end;
  2656. end;
  2657. end;
  2658. end;
  2659. end;
  2660. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2661. begin
  2662. Result := False;
  2663. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2664. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2665. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2666. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2667. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2668. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2669. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2670. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2671. begin
  2672. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2673. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2674. Result := True;
  2675. end;
  2676. end;
  2677. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2678. var
  2679. hp1, hp2, hp3, hp4: tai;
  2680. DoOptimisation, TempBool: Boolean;
  2681. {$ifdef x86_64}
  2682. NewConst: TCGInt;
  2683. {$endif x86_64}
  2684. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2685. begin
  2686. if taicpu(hp1).opcode = signed_movop then
  2687. begin
  2688. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2689. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2690. end
  2691. else
  2692. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2693. end;
  2694. function TryConstMerge(var p1, p2: tai): Boolean;
  2695. var
  2696. ThisRef: TReference;
  2697. begin
  2698. Result := False;
  2699. ThisRef := taicpu(p2).oper[1]^.ref^;
  2700. { Only permit writes to the stack, since we can guarantee alignment with that }
  2701. if (ThisRef.index = NR_NO) and
  2702. (
  2703. (ThisRef.base = NR_STACK_POINTER_REG) or
  2704. (ThisRef.base = current_procinfo.framepointer)
  2705. ) then
  2706. begin
  2707. case taicpu(p).opsize of
  2708. S_B:
  2709. begin
  2710. { Word writes must be on a 2-byte boundary }
  2711. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2712. begin
  2713. { Reduce offset of second reference to see if it is sequential with the first }
  2714. Dec(ThisRef.offset, 1);
  2715. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2716. begin
  2717. { Make sure the constants aren't represented as a
  2718. negative number, as these won't merge properly }
  2719. taicpu(p1).opsize := S_W;
  2720. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2721. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2722. RemoveInstruction(p2);
  2723. Result := True;
  2724. end;
  2725. end;
  2726. end;
  2727. S_W:
  2728. begin
  2729. { Longword writes must be on a 4-byte boundary }
  2730. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2731. begin
  2732. { Reduce offset of second reference to see if it is sequential with the first }
  2733. Dec(ThisRef.offset, 2);
  2734. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2735. begin
  2736. { Make sure the constants aren't represented as a
  2737. negative number, as these won't merge properly }
  2738. taicpu(p1).opsize := S_L;
  2739. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2740. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2741. RemoveInstruction(p2);
  2742. Result := True;
  2743. end;
  2744. end;
  2745. end;
  2746. {$ifdef x86_64}
  2747. S_L:
  2748. begin
  2749. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2750. see if the constants can be encoded this way. }
  2751. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2752. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2753. { Quadword writes must be on an 8-byte boundary }
  2754. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2755. begin
  2756. { Reduce offset of second reference to see if it is sequential with the first }
  2757. Dec(ThisRef.offset, 4);
  2758. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2759. begin
  2760. { Make sure the constants aren't represented as a
  2761. negative number, as these won't merge properly }
  2762. taicpu(p1).opsize := S_Q;
  2763. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2764. taicpu(p1).oper[0]^.val := NewConst;
  2765. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2766. RemoveInstruction(p2);
  2767. Result := True;
  2768. end;
  2769. end;
  2770. end;
  2771. {$endif x86_64}
  2772. else
  2773. ;
  2774. end;
  2775. end;
  2776. end;
  2777. var
  2778. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2779. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2780. NewSize: topsize; NewOffset: asizeint;
  2781. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2782. SourceRef, TargetRef: TReference;
  2783. MovAligned, MovUnaligned: TAsmOp;
  2784. ThisRef: TReference;
  2785. JumpTracking: TLinkedList;
  2786. begin
  2787. Result:=false;
  2788. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2789. { remove mov reg1,reg1? }
  2790. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2791. then
  2792. begin
  2793. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2794. { take care of the register (de)allocs following p }
  2795. RemoveCurrentP(p, hp1);
  2796. Result:=true;
  2797. exit;
  2798. end;
  2799. { All the next optimisations require a next instruction }
  2800. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2801. Exit;
  2802. { Prevent compiler warnings }
  2803. p_TargetReg := NR_NO;
  2804. if taicpu(p).oper[1]^.typ = top_reg then
  2805. begin
  2806. { Saves on a large number of dereferences }
  2807. p_TargetReg := taicpu(p).oper[1]^.reg;
  2808. { Look for:
  2809. mov %reg1,%reg2
  2810. ??? %reg2,r/m
  2811. Change to:
  2812. mov %reg1,%reg2
  2813. ??? %reg1,r/m
  2814. }
  2815. if taicpu(p).oper[0]^.typ = top_reg then
  2816. begin
  2817. if RegReadByInstruction(p_TargetReg, hp1) and
  2818. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2819. begin
  2820. { A change has occurred, just not in p }
  2821. Result := True;
  2822. TransferUsedRegs(TmpUsedRegs);
  2823. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2824. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2825. { Just in case something didn't get modified (e.g. an
  2826. implicit register) }
  2827. not RegReadByInstruction(p_TargetReg, hp1) then
  2828. begin
  2829. { We can remove the original MOV }
  2830. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2831. RemoveCurrentp(p, hp1);
  2832. { UsedRegs got updated by RemoveCurrentp }
  2833. Result := True;
  2834. Exit;
  2835. end;
  2836. { If we know a MOV instruction has become a null operation, we might as well
  2837. get rid of it now to save time. }
  2838. if (taicpu(hp1).opcode = A_MOV) and
  2839. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2840. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2841. { Just being a register is enough to confirm it's a null operation }
  2842. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2843. begin
  2844. Result := True;
  2845. { Speed-up to reduce a pipeline stall... if we had something like...
  2846. movl %eax,%edx
  2847. movw %dx,%ax
  2848. ... the second instruction would change to movw %ax,%ax, but
  2849. given that it is now %ax that's active rather than %eax,
  2850. penalties might occur due to a partial register write, so instead,
  2851. change it to a MOVZX instruction when optimising for speed.
  2852. }
  2853. if not (cs_opt_size in current_settings.optimizerswitches) and
  2854. IsMOVZXAcceptable and
  2855. (taicpu(hp1).opsize < taicpu(p).opsize)
  2856. {$ifdef x86_64}
  2857. { operations already implicitly set the upper 64 bits to zero }
  2858. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2859. {$endif x86_64}
  2860. then
  2861. begin
  2862. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2863. case taicpu(p).opsize of
  2864. S_W:
  2865. if taicpu(hp1).opsize = S_B then
  2866. taicpu(hp1).opsize := S_BL
  2867. else
  2868. InternalError(2020012911);
  2869. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2870. case taicpu(hp1).opsize of
  2871. S_B:
  2872. taicpu(hp1).opsize := S_BL;
  2873. S_W:
  2874. taicpu(hp1).opsize := S_WL;
  2875. else
  2876. InternalError(2020012912);
  2877. end;
  2878. else
  2879. InternalError(2020012910);
  2880. end;
  2881. taicpu(hp1).opcode := A_MOVZX;
  2882. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2883. end
  2884. else
  2885. begin
  2886. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2887. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2888. RemoveInstruction(hp1);
  2889. { The instruction after what was hp1 is now the immediate next instruction,
  2890. so we can continue to make optimisations if it's present }
  2891. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2892. Exit;
  2893. hp1 := hp2;
  2894. end;
  2895. end;
  2896. end;
  2897. end;
  2898. end;
  2899. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2900. overwrites the original destination register. e.g.
  2901. movl ###,%reg2d
  2902. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2903. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2904. }
  2905. if (taicpu(p).oper[1]^.typ = top_reg) and
  2906. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2907. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2908. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2909. begin
  2910. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2911. begin
  2912. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2913. case taicpu(p).oper[0]^.typ of
  2914. top_const:
  2915. { We have something like:
  2916. movb $x, %regb
  2917. movzbl %regb,%regd
  2918. Change to:
  2919. movl $x, %regd
  2920. }
  2921. begin
  2922. case taicpu(hp1).opsize of
  2923. S_BW:
  2924. begin
  2925. convert_mov_value(A_MOVSX, $FF);
  2926. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2927. taicpu(p).opsize := S_W;
  2928. end;
  2929. S_BL:
  2930. begin
  2931. convert_mov_value(A_MOVSX, $FF);
  2932. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2933. taicpu(p).opsize := S_L;
  2934. end;
  2935. S_WL:
  2936. begin
  2937. convert_mov_value(A_MOVSX, $FFFF);
  2938. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2939. taicpu(p).opsize := S_L;
  2940. end;
  2941. {$ifdef x86_64}
  2942. S_BQ:
  2943. begin
  2944. convert_mov_value(A_MOVSX, $FF);
  2945. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2946. taicpu(p).opsize := S_Q;
  2947. end;
  2948. S_WQ:
  2949. begin
  2950. convert_mov_value(A_MOVSX, $FFFF);
  2951. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2952. taicpu(p).opsize := S_Q;
  2953. end;
  2954. S_LQ:
  2955. begin
  2956. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2957. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2958. taicpu(p).opsize := S_Q;
  2959. end;
  2960. {$endif x86_64}
  2961. else
  2962. { If hp1 was a MOV instruction, it should have been
  2963. optimised already }
  2964. InternalError(2020021001);
  2965. end;
  2966. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2967. RemoveInstruction(hp1);
  2968. Result := True;
  2969. Exit;
  2970. end;
  2971. top_ref:
  2972. begin
  2973. { We have something like:
  2974. movb mem, %regb
  2975. movzbl %regb,%regd
  2976. Change to:
  2977. movzbl mem, %regd
  2978. }
  2979. ThisRef := taicpu(p).oper[0]^.ref^;
  2980. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2981. begin
  2982. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2983. taicpu(hp1).loadref(0, ThisRef);
  2984. { Make sure any registers in the references are properly tracked }
  2985. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2986. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2987. if (ThisRef.index <> NR_NO) then
  2988. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2989. RemoveCurrentP(p, hp1);
  2990. Result := True;
  2991. Exit;
  2992. end;
  2993. end;
  2994. else
  2995. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2996. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2997. Exit;
  2998. end;
  2999. end
  3000. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3001. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3002. optimised }
  3003. else
  3004. begin
  3005. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3006. RemoveCurrentP(p, hp1);
  3007. Result := True;
  3008. Exit;
  3009. end;
  3010. end;
  3011. if (taicpu(hp1).opcode = A_AND) and
  3012. (taicpu(p).oper[1]^.typ = top_reg) and
  3013. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3014. begin
  3015. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3016. begin
  3017. case taicpu(p).opsize of
  3018. S_L:
  3019. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3020. begin
  3021. { Optimize out:
  3022. mov x, %reg
  3023. and ffffffffh, %reg
  3024. }
  3025. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3026. RemoveInstruction(hp1);
  3027. Result:=true;
  3028. exit;
  3029. end;
  3030. S_Q: { TODO: Confirm if this is even possible }
  3031. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3032. begin
  3033. { Optimize out:
  3034. mov x, %reg
  3035. and ffffffffffffffffh, %reg
  3036. }
  3037. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3038. RemoveInstruction(hp1);
  3039. Result:=true;
  3040. exit;
  3041. end;
  3042. else
  3043. ;
  3044. end;
  3045. if (
  3046. (taicpu(p).oper[0]^.typ=top_reg) or
  3047. (
  3048. (taicpu(p).oper[0]^.typ=top_ref) and
  3049. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3050. )
  3051. ) and
  3052. GetNextInstruction(hp1,hp2) and
  3053. MatchInstruction(hp2,A_TEST,[]) and
  3054. (
  3055. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3056. (
  3057. { If the register being tested is smaller than the one
  3058. that received a bitwise AND, permit it if the constant
  3059. fits into the smaller size }
  3060. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3061. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3062. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3063. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3064. (
  3065. (
  3066. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3067. (taicpu(hp1).oper[0]^.val <= $FF)
  3068. ) or
  3069. (
  3070. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3071. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3072. {$ifdef x86_64}
  3073. ) or
  3074. (
  3075. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3076. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3077. {$endif x86_64}
  3078. )
  3079. )
  3080. )
  3081. ) and
  3082. (
  3083. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3084. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3085. ) and
  3086. GetNextInstruction(hp2,hp3) and
  3087. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3088. (taicpu(hp3).condition in [C_E,C_NE]) then
  3089. begin
  3090. TransferUsedRegs(TmpUsedRegs);
  3091. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3092. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3093. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3094. begin
  3095. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3096. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3097. taicpu(hp1).opcode:=A_TEST;
  3098. { Shrink the TEST instruction down to the smallest possible size }
  3099. case taicpu(hp1).oper[0]^.val of
  3100. 0..255:
  3101. if (taicpu(hp1).opsize <> S_B)
  3102. {$ifndef x86_64}
  3103. and (
  3104. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3105. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3106. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3107. )
  3108. {$endif x86_64}
  3109. then
  3110. begin
  3111. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3112. { Only print debug message if the TEST instruction
  3113. is a different size before and after }
  3114. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3115. taicpu(hp1).opsize := S_B;
  3116. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3117. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3118. end;
  3119. 256..65535:
  3120. if (taicpu(hp1).opsize <> S_W) then
  3121. begin
  3122. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3123. { Only print debug message if the TEST instruction
  3124. is a different size before and after }
  3125. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3126. taicpu(hp1).opsize := S_W;
  3127. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3128. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3129. end;
  3130. {$ifdef x86_64}
  3131. 65536..$7FFFFFFF:
  3132. if (taicpu(hp1).opsize <> S_L) then
  3133. begin
  3134. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3135. { Only print debug message if the TEST instruction
  3136. is a different size before and after }
  3137. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3138. taicpu(hp1).opsize := S_L;
  3139. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3140. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3141. end;
  3142. {$endif x86_64}
  3143. else
  3144. ;
  3145. end;
  3146. RemoveInstruction(hp2);
  3147. RemoveCurrentP(p, hp1);
  3148. Result:=true;
  3149. exit;
  3150. end;
  3151. end;
  3152. end
  3153. else if IsMOVZXAcceptable and
  3154. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3155. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3156. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3157. then
  3158. begin
  3159. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3160. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3161. case taicpu(p).opsize of
  3162. S_B:
  3163. if (taicpu(hp1).oper[0]^.val = $ff) then
  3164. begin
  3165. { Convert:
  3166. movb x, %regl movb x, %regl
  3167. andw ffh, %regw andl ffh, %regd
  3168. To:
  3169. movzbw x, %regd movzbl x, %regd
  3170. (Identical registers, just different sizes)
  3171. }
  3172. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3173. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3174. case taicpu(hp1).opsize of
  3175. S_W: NewSize := S_BW;
  3176. S_L: NewSize := S_BL;
  3177. {$ifdef x86_64}
  3178. S_Q: NewSize := S_BQ;
  3179. {$endif x86_64}
  3180. else
  3181. InternalError(2018011510);
  3182. end;
  3183. end
  3184. else
  3185. NewSize := S_NO;
  3186. S_W:
  3187. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3188. begin
  3189. { Convert:
  3190. movw x, %regw
  3191. andl ffffh, %regd
  3192. To:
  3193. movzwl x, %regd
  3194. (Identical registers, just different sizes)
  3195. }
  3196. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3197. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3198. case taicpu(hp1).opsize of
  3199. S_L: NewSize := S_WL;
  3200. {$ifdef x86_64}
  3201. S_Q: NewSize := S_WQ;
  3202. {$endif x86_64}
  3203. else
  3204. InternalError(2018011511);
  3205. end;
  3206. end
  3207. else
  3208. NewSize := S_NO;
  3209. else
  3210. NewSize := S_NO;
  3211. end;
  3212. if NewSize <> S_NO then
  3213. begin
  3214. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3215. { The actual optimization }
  3216. taicpu(p).opcode := A_MOVZX;
  3217. taicpu(p).changeopsize(NewSize);
  3218. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3219. { Safeguard if "and" is followed by a conditional command }
  3220. TransferUsedRegs(TmpUsedRegs);
  3221. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3222. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3223. begin
  3224. { At this point, the "and" command is effectively equivalent to
  3225. "test %reg,%reg". This will be handled separately by the
  3226. Peephole Optimizer. [Kit] }
  3227. DebugMsg(SPeepholeOptimization + PreMessage +
  3228. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3229. end
  3230. else
  3231. begin
  3232. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3233. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3234. RemoveInstruction(hp1);
  3235. end;
  3236. Result := True;
  3237. Exit;
  3238. end;
  3239. end;
  3240. end;
  3241. if (taicpu(hp1).opcode = A_OR) and
  3242. (taicpu(p).oper[1]^.typ = top_reg) and
  3243. MatchOperand(taicpu(p).oper[0]^, 0) and
  3244. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3245. begin
  3246. { mov 0, %reg
  3247. or ###,%reg
  3248. Change to (only if the flags are not used):
  3249. mov ###,%reg
  3250. }
  3251. TransferUsedRegs(TmpUsedRegs);
  3252. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3253. DoOptimisation := True;
  3254. { Even if the flags are used, we might be able to do the optimisation
  3255. if the conditions are predictable }
  3256. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3257. begin
  3258. { Only perform if ### = %reg (the same register) or equal to 0,
  3259. so %reg is guaranteed to still have a value of zero }
  3260. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3261. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3262. begin
  3263. hp2 := hp1;
  3264. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3265. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3266. GetNextInstruction(hp2, hp3) do
  3267. begin
  3268. { Don't continue modifying if the flags state is getting changed }
  3269. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3270. Break;
  3271. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3272. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3273. begin
  3274. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3275. begin
  3276. { Condition is always true }
  3277. case taicpu(hp3).opcode of
  3278. A_Jcc:
  3279. begin
  3280. { Check for jump shortcuts before we destroy the condition }
  3281. hp4 := hp3;
  3282. DoJumpOptimizations(hp3, TempBool);
  3283. { Make sure hp3 hasn't changed }
  3284. if (hp4 = hp3) then
  3285. begin
  3286. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3287. MakeUnconditional(taicpu(hp3));
  3288. end;
  3289. Result := True;
  3290. end;
  3291. A_CMOVcc:
  3292. begin
  3293. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3294. taicpu(hp3).opcode := A_MOV;
  3295. taicpu(hp3).condition := C_None;
  3296. Result := True;
  3297. end;
  3298. A_SETcc:
  3299. begin
  3300. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3301. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3302. taicpu(hp3).opcode := A_MOV;
  3303. taicpu(hp3).ops := 2;
  3304. taicpu(hp3).condition := C_None;
  3305. taicpu(hp3).opsize := S_B;
  3306. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3307. taicpu(hp3).loadconst(0, 1);
  3308. Result := True;
  3309. end;
  3310. else
  3311. InternalError(2021090701);
  3312. end;
  3313. end
  3314. 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
  3315. begin
  3316. { Condition is always false }
  3317. case taicpu(hp3).opcode of
  3318. A_Jcc:
  3319. begin
  3320. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3321. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3322. RemoveInstruction(hp3);
  3323. Result := True;
  3324. { Since hp3 was deleted, hp2 must not be updated }
  3325. Continue;
  3326. end;
  3327. A_CMOVcc:
  3328. begin
  3329. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3330. RemoveInstruction(hp3);
  3331. Result := True;
  3332. { Since hp3 was deleted, hp2 must not be updated }
  3333. Continue;
  3334. end;
  3335. A_SETcc:
  3336. begin
  3337. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3338. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3339. taicpu(hp3).opcode := A_MOV;
  3340. taicpu(hp3).ops := 2;
  3341. taicpu(hp3).condition := C_None;
  3342. taicpu(hp3).opsize := S_B;
  3343. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3344. taicpu(hp3).loadconst(0, 0);
  3345. Result := True;
  3346. end;
  3347. else
  3348. InternalError(2021090702);
  3349. end;
  3350. end
  3351. else
  3352. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3353. DoOptimisation := False;
  3354. end;
  3355. hp2 := hp3;
  3356. end;
  3357. { Flags are still in use - don't optimise }
  3358. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3359. DoOptimisation := False;
  3360. end
  3361. else
  3362. DoOptimisation := False;
  3363. end;
  3364. if DoOptimisation then
  3365. begin
  3366. {$ifdef x86_64}
  3367. { OR only supports 32-bit sign-extended constants for 64-bit
  3368. instructions, so compensate for this if the constant is
  3369. encoded as a value greater than or equal to 2^31 }
  3370. if (taicpu(hp1).opsize = S_Q) and
  3371. (taicpu(hp1).oper[0]^.typ = top_const) and
  3372. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3373. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3374. {$endif x86_64}
  3375. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3376. taicpu(hp1).opcode := A_MOV;
  3377. RemoveCurrentP(p, hp1);
  3378. Result := True;
  3379. Exit;
  3380. end;
  3381. end;
  3382. { Next instruction is also a MOV ? }
  3383. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3384. begin
  3385. if MatchOpType(taicpu(p), top_const, top_ref) and
  3386. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3387. TryConstMerge(p, hp1) then
  3388. begin
  3389. Result := True;
  3390. { In case we have four byte writes in a row, check for 2 more
  3391. right now so we don't have to wait for another iteration of
  3392. pass 1
  3393. }
  3394. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3395. case taicpu(p).opsize of
  3396. S_W:
  3397. begin
  3398. if GetNextInstruction(p, hp1) and
  3399. MatchInstruction(hp1, A_MOV, [S_B]) and
  3400. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3401. GetNextInstruction(hp1, hp2) and
  3402. MatchInstruction(hp2, A_MOV, [S_B]) and
  3403. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3404. { Try to merge the two bytes }
  3405. TryConstMerge(hp1, hp2) then
  3406. { Now try to merge the two words (hp2 will get deleted) }
  3407. TryConstMerge(p, hp1);
  3408. end;
  3409. S_L:
  3410. begin
  3411. { Though this only really benefits x86_64 and not i386, it
  3412. gets a potential optimisation done faster and hence
  3413. reduces the number of times OptPass1MOV is entered }
  3414. if GetNextInstruction(p, hp1) and
  3415. MatchInstruction(hp1, A_MOV, [S_W]) and
  3416. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3417. GetNextInstruction(hp1, hp2) and
  3418. MatchInstruction(hp2, A_MOV, [S_W]) and
  3419. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3420. { Try to merge the two words }
  3421. TryConstMerge(hp1, hp2) then
  3422. { This will always fail on i386, so don't bother
  3423. calling it unless we're doing x86_64 }
  3424. {$ifdef x86_64}
  3425. { Now try to merge the two longwords (hp2 will get deleted) }
  3426. TryConstMerge(p, hp1)
  3427. {$endif x86_64}
  3428. ;
  3429. end;
  3430. else
  3431. ;
  3432. end;
  3433. Exit;
  3434. end;
  3435. if (taicpu(p).oper[1]^.typ = top_reg) and
  3436. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3437. begin
  3438. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3439. TransferUsedRegs(TmpUsedRegs);
  3440. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3441. { we have
  3442. mov x, %treg
  3443. mov %treg, y
  3444. }
  3445. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3446. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3447. { we've got
  3448. mov x, %treg
  3449. mov %treg, y
  3450. with %treg is not used after }
  3451. case taicpu(p).oper[0]^.typ Of
  3452. { top_reg is covered by DeepMOVOpt }
  3453. top_const:
  3454. begin
  3455. { change
  3456. mov const, %treg
  3457. mov %treg, y
  3458. to
  3459. mov const, y
  3460. }
  3461. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3462. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3463. begin
  3464. if taicpu(hp1).oper[1]^.typ=top_reg then
  3465. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3466. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3467. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3468. RemoveInstruction(hp1);
  3469. Result:=true;
  3470. Exit;
  3471. end;
  3472. end;
  3473. top_ref:
  3474. case taicpu(hp1).oper[1]^.typ of
  3475. top_reg:
  3476. begin
  3477. { change
  3478. mov mem, %treg
  3479. mov %treg, %reg
  3480. to
  3481. mov mem, %reg"
  3482. }
  3483. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3484. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3485. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3486. RemoveInstruction(hp1);
  3487. Result:=true;
  3488. Exit;
  3489. end;
  3490. top_ref:
  3491. begin
  3492. {$ifdef x86_64}
  3493. { Look for the following to simplify:
  3494. mov x(mem1), %reg
  3495. mov %reg, y(mem2)
  3496. mov x+8(mem1), %reg
  3497. mov %reg, y+8(mem2)
  3498. Change to:
  3499. movdqu x(mem1), %xmmreg
  3500. movdqu %xmmreg, y(mem2)
  3501. ...but only as long as the memory blocks don't overlap
  3502. }
  3503. SourceRef := taicpu(p).oper[0]^.ref^;
  3504. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3505. if (taicpu(p).opsize = S_Q) and
  3506. GetNextInstruction(hp1, hp2) and
  3507. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3508. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3509. begin
  3510. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3511. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3512. Inc(SourceRef.offset, 8);
  3513. if UseAVX then
  3514. begin
  3515. MovAligned := A_VMOVDQA;
  3516. MovUnaligned := A_VMOVDQU;
  3517. end
  3518. else
  3519. begin
  3520. MovAligned := A_MOVDQA;
  3521. MovUnaligned := A_MOVDQU;
  3522. end;
  3523. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3524. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3525. begin
  3526. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3527. Inc(TargetRef.offset, 8);
  3528. if GetNextInstruction(hp2, hp3) and
  3529. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3530. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3531. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3532. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3533. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3534. begin
  3535. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3536. if NewMMReg <> NR_NO then
  3537. begin
  3538. { Remember that the offsets are 8 ahead }
  3539. if ((SourceRef.offset mod 16) = 8) and
  3540. (
  3541. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3542. (SourceRef.base = current_procinfo.framepointer) or
  3543. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3544. ) then
  3545. taicpu(p).opcode := MovAligned
  3546. else
  3547. taicpu(p).opcode := MovUnaligned;
  3548. taicpu(p).opsize := S_XMM;
  3549. taicpu(p).oper[1]^.reg := NewMMReg;
  3550. if ((TargetRef.offset mod 16) = 8) and
  3551. (
  3552. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3553. (TargetRef.base = current_procinfo.framepointer) or
  3554. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3555. ) then
  3556. taicpu(hp1).opcode := MovAligned
  3557. else
  3558. taicpu(hp1).opcode := MovUnaligned;
  3559. taicpu(hp1).opsize := S_XMM;
  3560. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3561. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3562. RemoveInstruction(hp2);
  3563. RemoveInstruction(hp3);
  3564. Result := True;
  3565. Exit;
  3566. end;
  3567. end;
  3568. end
  3569. else
  3570. begin
  3571. { See if the next references are 8 less rather than 8 greater }
  3572. Dec(SourceRef.offset, 16); { -8 the other way }
  3573. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3574. begin
  3575. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3576. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3577. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3578. GetNextInstruction(hp2, hp3) and
  3579. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3580. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3581. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3582. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3583. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3584. begin
  3585. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3586. if NewMMReg <> NR_NO then
  3587. begin
  3588. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3589. if ((SourceRef.offset mod 16) = 0) and
  3590. (
  3591. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3592. (SourceRef.base = current_procinfo.framepointer) or
  3593. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3594. ) then
  3595. taicpu(hp2).opcode := MovAligned
  3596. else
  3597. taicpu(hp2).opcode := MovUnaligned;
  3598. taicpu(hp2).opsize := S_XMM;
  3599. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3600. if ((TargetRef.offset mod 16) = 0) and
  3601. (
  3602. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3603. (TargetRef.base = current_procinfo.framepointer) or
  3604. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3605. ) then
  3606. taicpu(hp3).opcode := MovAligned
  3607. else
  3608. taicpu(hp3).opcode := MovUnaligned;
  3609. taicpu(hp3).opsize := S_XMM;
  3610. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3611. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3612. RemoveInstruction(hp1);
  3613. RemoveCurrentP(p, hp2);
  3614. Result := True;
  3615. Exit;
  3616. end;
  3617. end;
  3618. end;
  3619. end;
  3620. end;
  3621. {$endif x86_64}
  3622. end;
  3623. else
  3624. { The write target should be a reg or a ref }
  3625. InternalError(2021091601);
  3626. end;
  3627. else
  3628. ;
  3629. end
  3630. else
  3631. { %treg is used afterwards, but all eventualities
  3632. other than the first MOV instruction being a constant
  3633. are covered by DeepMOVOpt, so only check for that }
  3634. if (taicpu(p).oper[0]^.typ = top_const) and
  3635. (
  3636. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3637. not (cs_opt_size in current_settings.optimizerswitches) or
  3638. (taicpu(hp1).opsize = S_B)
  3639. ) and
  3640. (
  3641. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3642. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3643. ) then
  3644. begin
  3645. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3646. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3647. end;
  3648. end;
  3649. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3650. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3651. { mov reg1, mem1 or mov mem1, reg1
  3652. mov mem2, reg2 mov reg2, mem2}
  3653. begin
  3654. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3655. { mov reg1, mem1 or mov mem1, reg1
  3656. mov mem2, reg1 mov reg2, mem1}
  3657. begin
  3658. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3659. { Removes the second statement from
  3660. mov reg1, mem1/reg2
  3661. mov mem1/reg2, reg1 }
  3662. begin
  3663. if taicpu(p).oper[0]^.typ=top_reg then
  3664. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3665. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3666. RemoveInstruction(hp1);
  3667. Result:=true;
  3668. exit;
  3669. end
  3670. else
  3671. begin
  3672. TransferUsedRegs(TmpUsedRegs);
  3673. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3674. if (taicpu(p).oper[1]^.typ = top_ref) and
  3675. { mov reg1, mem1
  3676. mov mem2, reg1 }
  3677. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3678. GetNextInstruction(hp1, hp2) and
  3679. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3680. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3681. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3682. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3683. { change to
  3684. mov reg1, mem1 mov reg1, mem1
  3685. mov mem2, reg1 cmp reg1, mem2
  3686. cmp mem1, reg1
  3687. }
  3688. begin
  3689. RemoveInstruction(hp2);
  3690. taicpu(hp1).opcode := A_CMP;
  3691. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3692. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3693. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3694. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3695. end;
  3696. end;
  3697. end
  3698. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3699. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3700. begin
  3701. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3702. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3703. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3704. end
  3705. else
  3706. begin
  3707. TransferUsedRegs(TmpUsedRegs);
  3708. if GetNextInstruction(hp1, hp2) and
  3709. MatchOpType(taicpu(p),top_ref,top_reg) and
  3710. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3711. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3712. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3713. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3714. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3715. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3716. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3717. { mov mem1, %reg1
  3718. mov %reg1, mem2
  3719. mov mem2, reg2
  3720. to:
  3721. mov mem1, reg2
  3722. mov reg2, mem2}
  3723. begin
  3724. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3725. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3726. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3727. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3728. RemoveInstruction(hp2);
  3729. Result := True;
  3730. end
  3731. {$ifdef i386}
  3732. { this is enabled for i386 only, as the rules to create the reg sets below
  3733. are too complicated for x86-64, so this makes this code too error prone
  3734. on x86-64
  3735. }
  3736. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3737. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3738. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3739. { mov mem1, reg1 mov mem1, reg1
  3740. mov reg1, mem2 mov reg1, mem2
  3741. mov mem2, reg2 mov mem2, reg1
  3742. to: to:
  3743. mov mem1, reg1 mov mem1, reg1
  3744. mov mem1, reg2 mov reg1, mem2
  3745. mov reg1, mem2
  3746. or (if mem1 depends on reg1
  3747. and/or if mem2 depends on reg2)
  3748. to:
  3749. mov mem1, reg1
  3750. mov reg1, mem2
  3751. mov reg1, reg2
  3752. }
  3753. begin
  3754. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3755. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3756. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3757. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3758. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3759. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3760. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3761. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3762. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3763. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3764. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3765. end
  3766. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3767. begin
  3768. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3769. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3770. end
  3771. else
  3772. begin
  3773. RemoveInstruction(hp2);
  3774. end
  3775. {$endif i386}
  3776. ;
  3777. end;
  3778. end
  3779. { movl [mem1],reg1
  3780. movl [mem1],reg2
  3781. to
  3782. movl [mem1],reg1
  3783. movl reg1,reg2
  3784. }
  3785. else if not CheckMovMov2MovMov2(p, hp1) and
  3786. { movl const1,[mem1]
  3787. movl [mem1],reg1
  3788. to
  3789. movl const1,reg1
  3790. movl reg1,[mem1]
  3791. }
  3792. MatchOpType(Taicpu(p),top_const,top_ref) and
  3793. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3794. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3795. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3796. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3797. begin
  3798. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3799. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3800. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3801. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3802. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3803. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3804. Result:=true;
  3805. exit;
  3806. end;
  3807. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3808. { Change:
  3809. movl %reg1,%reg2
  3810. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3811. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3812. To:
  3813. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3814. movl x(%reg1),%reg1
  3815. movl %reg1,%regX
  3816. }
  3817. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3818. begin
  3819. p_SourceReg := taicpu(p).oper[0]^.reg;
  3820. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3821. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3822. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3823. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3824. GetNextInstruction(hp1, hp2) and
  3825. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3826. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3827. begin
  3828. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3829. if RegInRef(p_TargetReg, SourceRef) and
  3830. { If %reg1 also appears in the second reference, then it will
  3831. not refer to the same memory block as the first reference }
  3832. not RegInRef(p_SourceReg, SourceRef) then
  3833. begin
  3834. { Check to see if the references match if %reg2 is changed to %reg1 }
  3835. if SourceRef.base = p_TargetReg then
  3836. SourceRef.base := p_SourceReg;
  3837. if SourceRef.index = p_TargetReg then
  3838. SourceRef.index := p_SourceReg;
  3839. { RefsEqual also checks to ensure both references are non-volatile }
  3840. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3841. begin
  3842. taicpu(hp2).loadreg(0, p_SourceReg);
  3843. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3844. Result := True;
  3845. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3846. begin
  3847. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3848. RemoveCurrentP(p, hp1);
  3849. Exit;
  3850. end
  3851. else
  3852. begin
  3853. { Check to see if %reg2 is no longer in use }
  3854. TransferUsedRegs(TmpUsedRegs);
  3855. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3856. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3857. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3858. begin
  3859. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3860. RemoveCurrentP(p, hp1);
  3861. Exit;
  3862. end;
  3863. end;
  3864. { If we reach this point, p and hp1 weren't actually modified,
  3865. so we can do a bit more work on this pass }
  3866. end;
  3867. end;
  3868. end;
  3869. end;
  3870. end;
  3871. {$ifdef x86_64}
  3872. { Change:
  3873. movl %reg1l,%reg2l
  3874. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3875. To:
  3876. movl %reg1l,%reg2l
  3877. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3878. If %reg1 = %reg3, convert to:
  3879. movl %reg1l,%reg2l
  3880. andl %reg1l,%reg1l
  3881. }
  3882. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3883. MatchOpType(taicpu(p), top_reg, top_reg) and
  3884. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3885. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3886. begin
  3887. TransferUsedRegs(TmpUsedRegs);
  3888. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3889. taicpu(hp1).opsize := S_L;
  3890. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3891. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3892. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3893. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3894. begin
  3895. { %reg1 = %reg3 }
  3896. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3897. taicpu(hp1).opcode := A_AND;
  3898. end
  3899. else
  3900. begin
  3901. { %reg1 <> %reg3 }
  3902. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3903. end;
  3904. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3905. begin
  3906. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3907. RemoveCurrentP(p, hp1);
  3908. Result := True;
  3909. Exit;
  3910. end
  3911. else
  3912. begin
  3913. { Initial instruction wasn't actually changed }
  3914. Include(OptsToCheck, aoc_ForceNewIteration);
  3915. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3916. appears below since %reg1 has technically changed }
  3917. if taicpu(hp1).opcode = A_AND then
  3918. Exit;
  3919. end;
  3920. end;
  3921. {$endif x86_64}
  3922. { search further than the next instruction for a mov (as long as it's not a jump) }
  3923. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3924. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3925. (taicpu(p).oper[1]^.typ = top_reg) and
  3926. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3927. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3928. begin
  3929. { we work with hp2 here, so hp1 can be still used later on when
  3930. checking for GetNextInstruction_p }
  3931. hp3 := hp1;
  3932. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3933. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3934. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3935. TransferUsedRegs(TmpUsedRegs);
  3936. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3937. if NotFirstIteration then
  3938. JumpTracking := TLinkedList.Create
  3939. else
  3940. JumpTracking := nil;
  3941. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3942. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3943. (hp2.typ=ait_instruction) do
  3944. begin
  3945. case taicpu(hp2).opcode of
  3946. A_POP:
  3947. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3948. begin
  3949. if not CrossJump and
  3950. not RegUsedBetween(p_TargetReg, p, hp2) then
  3951. begin
  3952. { We can remove the original MOV since the register
  3953. wasn't used between it and its popping from the stack }
  3954. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3955. RemoveCurrentp(p, hp1);
  3956. Result := True;
  3957. JumpTracking.Free;
  3958. Exit;
  3959. end;
  3960. { Can't go any further }
  3961. Break;
  3962. end;
  3963. A_MOV:
  3964. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3965. ((taicpu(p).oper[0]^.typ=top_const) or
  3966. ((taicpu(p).oper[0]^.typ=top_reg) and
  3967. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3968. )
  3969. ) then
  3970. begin
  3971. { we have
  3972. mov x, %treg
  3973. mov %treg, y
  3974. }
  3975. { We don't need to call UpdateUsedRegs for every instruction between
  3976. p and hp2 because the register we're concerned about will not
  3977. become deallocated (otherwise GetNextInstructionUsingReg would
  3978. have stopped at an earlier instruction). [Kit] }
  3979. TempRegUsed :=
  3980. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3981. RegReadByInstruction(p_TargetReg, hp3) or
  3982. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3983. case taicpu(p).oper[0]^.typ Of
  3984. top_reg:
  3985. begin
  3986. { change
  3987. mov %reg, %treg
  3988. mov %treg, y
  3989. to
  3990. mov %reg, y
  3991. }
  3992. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3993. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3994. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3995. begin
  3996. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3997. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3998. if TempRegUsed then
  3999. begin
  4000. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4001. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4002. { Set the start of the next GetNextInstructionUsingRegCond search
  4003. to start at the entry right before hp2 (which is about to be removed) }
  4004. hp3 := tai(hp2.Previous);
  4005. RemoveInstruction(hp2);
  4006. Include(OptsToCheck, aoc_ForceNewIteration);
  4007. { See if there's more we can optimise }
  4008. Continue;
  4009. end
  4010. else
  4011. begin
  4012. RemoveInstruction(hp2);
  4013. { We can remove the original MOV too }
  4014. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4015. RemoveCurrentP(p, hp1);
  4016. Result:=true;
  4017. JumpTracking.Free;
  4018. Exit;
  4019. end;
  4020. end
  4021. else
  4022. begin
  4023. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4024. taicpu(hp2).loadReg(0, p_SourceReg);
  4025. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4026. { Check to see if the register also appears in the reference }
  4027. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4028. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4029. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4030. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4031. begin
  4032. { Don't remove the first instruction if the temporary register is in use }
  4033. if not TempRegUsed then
  4034. begin
  4035. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4036. RemoveCurrentP(p, hp1);
  4037. Result:=true;
  4038. JumpTracking.Free;
  4039. Exit;
  4040. end;
  4041. { No need to set Result to True here. If there's another instruction later
  4042. on that can be optimised, it will be detected when the main Pass 1 loop
  4043. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4044. hp3 := hp2;
  4045. Continue;
  4046. end;
  4047. end;
  4048. end;
  4049. top_const:
  4050. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4051. begin
  4052. { change
  4053. mov const, %treg
  4054. mov %treg, y
  4055. to
  4056. mov const, y
  4057. }
  4058. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4059. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4060. begin
  4061. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4062. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4063. if TempRegUsed then
  4064. begin
  4065. { Don't remove the first instruction if the temporary register is in use }
  4066. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4067. { No need to set Result to True. If there's another instruction later on
  4068. that can be optimised, it will be detected when the main Pass 1 loop
  4069. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4070. end
  4071. else
  4072. begin
  4073. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4074. RemoveCurrentP(p, hp1);
  4075. Result:=true;
  4076. Exit;
  4077. end;
  4078. end;
  4079. end;
  4080. else
  4081. Internalerror(2019103001);
  4082. end;
  4083. end
  4084. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4085. begin
  4086. if not CrossJump and
  4087. not RegUsedBetween(p_TargetReg, p, hp2) and
  4088. not RegReadByInstruction(p_TargetReg, hp2) then
  4089. begin
  4090. { Register is not used before it is overwritten }
  4091. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4092. RemoveCurrentp(p, hp1);
  4093. Result := True;
  4094. Exit;
  4095. end;
  4096. if (taicpu(p).oper[0]^.typ = top_const) and
  4097. (taicpu(hp2).oper[0]^.typ = top_const) then
  4098. begin
  4099. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4100. begin
  4101. { Same value - register hasn't changed }
  4102. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4103. RemoveInstruction(hp2);
  4104. Include(OptsToCheck, aoc_ForceNewIteration);
  4105. { See if there's more we can optimise }
  4106. Continue;
  4107. end;
  4108. end;
  4109. {$ifdef x86_64}
  4110. end
  4111. { Change:
  4112. movl %reg1l,%reg2l
  4113. ...
  4114. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4115. To:
  4116. movl %reg1l,%reg2l
  4117. ...
  4118. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4119. If %reg1 = %reg3, convert to:
  4120. movl %reg1l,%reg2l
  4121. ...
  4122. andl %reg1l,%reg1l
  4123. }
  4124. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4125. (taicpu(p).oper[0]^.typ = top_reg) and
  4126. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4127. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4128. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4129. begin
  4130. TempRegUsed :=
  4131. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4132. RegReadByInstruction(p_TargetReg, hp3) or
  4133. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4134. taicpu(hp2).opsize := S_L;
  4135. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4136. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4137. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4138. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4139. begin
  4140. { %reg1 = %reg3 }
  4141. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4142. taicpu(hp2).opcode := A_AND;
  4143. end
  4144. else
  4145. begin
  4146. { %reg1 <> %reg3 }
  4147. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4148. end;
  4149. if not TempRegUsed then
  4150. begin
  4151. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4152. RemoveCurrentP(p, hp1);
  4153. Result := True;
  4154. Exit;
  4155. end
  4156. else
  4157. begin
  4158. { Initial instruction wasn't actually changed }
  4159. Include(OptsToCheck, aoc_ForceNewIteration);
  4160. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4161. appears below since %reg1 has technically changed }
  4162. if taicpu(hp2).opcode = A_AND then
  4163. Break;
  4164. end;
  4165. {$endif x86_64}
  4166. end
  4167. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4168. GetNextInstruction(hp2, hp4) and
  4169. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4170. { Optimise the following first:
  4171. movl [mem1],reg1
  4172. movl [mem1],reg2
  4173. to
  4174. movl [mem1],reg1
  4175. movl reg1,reg2
  4176. If [mem1] contains the target register and reg1 is the
  4177. the source register, this optimisation will get missed
  4178. and produce less efficient code later on.
  4179. }
  4180. if CheckMovMov2MovMov2(hp2, hp4) then
  4181. { Initial instruction wasn't actually changed }
  4182. Include(OptsToCheck, aoc_ForceNewIteration);
  4183. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4184. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4185. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4186. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4187. begin
  4188. {
  4189. Change from:
  4190. mov ###, %reg
  4191. ...
  4192. movs/z %reg,%reg (Same register, just different sizes)
  4193. To:
  4194. movs/z ###, %reg (Longer version)
  4195. ...
  4196. (remove)
  4197. }
  4198. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4199. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4200. { Keep the first instruction as mov if ### is a constant }
  4201. if taicpu(p).oper[0]^.typ = top_const then
  4202. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4203. else
  4204. begin
  4205. taicpu(p).opcode := taicpu(hp2).opcode;
  4206. taicpu(p).opsize := taicpu(hp2).opsize;
  4207. end;
  4208. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4209. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4210. RemoveInstruction(hp2);
  4211. Result := True;
  4212. JumpTracking.Free;
  4213. Exit;
  4214. end;
  4215. else
  4216. { Move down to the if-block below };
  4217. end;
  4218. { Also catches MOV/S/Z instructions that aren't modified }
  4219. if taicpu(p).oper[0]^.typ = top_reg then
  4220. begin
  4221. p_SourceReg := taicpu(p).oper[0]^.reg;
  4222. if
  4223. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4224. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4225. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4226. begin
  4227. Result := True;
  4228. { Just in case something didn't get modified (e.g. an
  4229. implicit register). Also, if it does read from this
  4230. register, then there's no longer an advantage to
  4231. changing the register on subsequent instructions.}
  4232. if not RegReadByInstruction(p_TargetReg, hp2) then
  4233. begin
  4234. { If a conditional jump was crossed, do not delete
  4235. the original MOV no matter what }
  4236. if not CrossJump and
  4237. { RegEndOfLife returns True if the register is
  4238. deallocated before the next instruction or has
  4239. been loaded with a new value }
  4240. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4241. begin
  4242. { We can remove the original MOV }
  4243. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4244. RemoveCurrentp(p, hp1);
  4245. JumpTracking.Free;
  4246. Result := True;
  4247. Exit;
  4248. end;
  4249. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4250. begin
  4251. { See if there's more we can optimise }
  4252. hp3 := hp2;
  4253. Continue;
  4254. end;
  4255. end;
  4256. end;
  4257. end;
  4258. { Break out of the while loop under normal circumstances }
  4259. Break;
  4260. end;
  4261. JumpTracking.Free;
  4262. end;
  4263. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4264. (taicpu(p).oper[1]^.typ = top_reg) and
  4265. (taicpu(p).opsize = S_L) and
  4266. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4267. (hp2.typ = ait_instruction) and
  4268. (taicpu(hp2).opcode = A_AND) and
  4269. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4270. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4271. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4272. ) then
  4273. begin
  4274. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4275. begin
  4276. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4277. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4278. begin
  4279. { Optimize out:
  4280. mov x, %reg
  4281. and ffffffffh, %reg
  4282. }
  4283. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4284. RemoveInstruction(hp2);
  4285. Result:=true;
  4286. exit;
  4287. end;
  4288. end;
  4289. end;
  4290. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4291. x >= RetOffset) as it doesn't do anything (it writes either to a
  4292. parameter or to the temporary storage room for the function
  4293. result)
  4294. }
  4295. if IsExitCode(hp1) and
  4296. (taicpu(p).oper[1]^.typ = top_ref) and
  4297. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4298. (
  4299. (
  4300. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4301. not (
  4302. assigned(current_procinfo.procdef.funcretsym) and
  4303. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4304. )
  4305. ) or
  4306. { Also discard writes to the stack that are below the base pointer,
  4307. as this is temporary storage rather than a function result on the
  4308. stack, say. }
  4309. (
  4310. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4311. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4312. )
  4313. ) then
  4314. begin
  4315. RemoveCurrentp(p, hp1);
  4316. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4317. RemoveLastDeallocForFuncRes(p);
  4318. Result:=true;
  4319. exit;
  4320. end;
  4321. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4322. begin
  4323. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4324. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4325. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4326. begin
  4327. { change
  4328. mov reg1, mem1
  4329. test/cmp x, mem1
  4330. to
  4331. mov reg1, mem1
  4332. test/cmp x, reg1
  4333. }
  4334. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4335. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4336. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4337. Result := True;
  4338. Exit;
  4339. end;
  4340. if DoMovCmpMemOpt(p, hp1) then
  4341. begin
  4342. Result := True;
  4343. Exit;
  4344. end;
  4345. end;
  4346. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4347. { If the flags register is in use, don't change the instruction to an
  4348. ADD otherwise this will scramble the flags. [Kit] }
  4349. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4350. begin
  4351. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4352. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4353. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4354. ) or
  4355. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4356. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4357. )
  4358. ) then
  4359. { mov reg1,ref
  4360. lea reg2,[reg1,reg2]
  4361. to
  4362. add reg2,ref}
  4363. begin
  4364. TransferUsedRegs(TmpUsedRegs);
  4365. { reg1 may not be used afterwards }
  4366. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4367. begin
  4368. Taicpu(hp1).opcode:=A_ADD;
  4369. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4370. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4371. RemoveCurrentp(p, hp1);
  4372. result:=true;
  4373. exit;
  4374. end;
  4375. end;
  4376. { If the LEA instruction can be converted into an arithmetic instruction,
  4377. it may be possible to then fold it in the next optimisation, otherwise
  4378. there's nothing more that can be optimised here. }
  4379. if not ConvertLEA(taicpu(hp1)) then
  4380. Exit;
  4381. end;
  4382. if (taicpu(p).oper[1]^.typ = top_reg) and
  4383. (hp1.typ = ait_instruction) and
  4384. GetNextInstruction(hp1, hp2) and
  4385. MatchInstruction(hp2,A_MOV,[]) and
  4386. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4387. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4388. (
  4389. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4390. {$ifdef x86_64}
  4391. or
  4392. (
  4393. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4394. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4395. )
  4396. {$endif x86_64}
  4397. ) then
  4398. begin
  4399. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4400. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4401. { change movsX/movzX reg/ref, reg2
  4402. add/sub/or/... reg3/$const, reg2
  4403. mov reg2 reg/ref
  4404. dealloc reg2
  4405. to
  4406. add/sub/or/... reg3/$const, reg/ref }
  4407. begin
  4408. TransferUsedRegs(TmpUsedRegs);
  4409. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4410. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4411. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4412. begin
  4413. { by example:
  4414. movswl %si,%eax movswl %si,%eax p
  4415. decl %eax addl %edx,%eax hp1
  4416. movw %ax,%si movw %ax,%si hp2
  4417. ->
  4418. movswl %si,%eax movswl %si,%eax p
  4419. decw %eax addw %edx,%eax hp1
  4420. movw %ax,%si movw %ax,%si hp2
  4421. }
  4422. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4423. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4424. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4425. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4426. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4427. {
  4428. ->
  4429. movswl %si,%eax movswl %si,%eax p
  4430. decw %si addw %dx,%si hp1
  4431. movw %ax,%si movw %ax,%si hp2
  4432. }
  4433. case taicpu(hp1).ops of
  4434. 1:
  4435. begin
  4436. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4437. if taicpu(hp1).oper[0]^.typ=top_reg then
  4438. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4439. end;
  4440. 2:
  4441. begin
  4442. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4443. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4444. (taicpu(hp1).opcode<>A_SHL) and
  4445. (taicpu(hp1).opcode<>A_SHR) and
  4446. (taicpu(hp1).opcode<>A_SAR) then
  4447. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4448. end;
  4449. else
  4450. internalerror(2008042701);
  4451. end;
  4452. {
  4453. ->
  4454. decw %si addw %dx,%si p
  4455. }
  4456. RemoveInstruction(hp2);
  4457. RemoveCurrentP(p, hp1);
  4458. Result:=True;
  4459. Exit;
  4460. end;
  4461. end;
  4462. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4463. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4464. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4465. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4466. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4467. )
  4468. {$ifdef i386}
  4469. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4470. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4471. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4472. {$endif i386}
  4473. then
  4474. { change movsX/movzX reg/ref, reg2
  4475. add/sub/or/... regX/$const, reg2
  4476. mov reg2, reg3
  4477. dealloc reg2
  4478. to
  4479. movsX/movzX reg/ref, reg3
  4480. add/sub/or/... reg3/$const, reg3
  4481. }
  4482. begin
  4483. TransferUsedRegs(TmpUsedRegs);
  4484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4485. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4486. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4487. begin
  4488. { by example:
  4489. movswl %si,%eax movswl %si,%eax p
  4490. decl %eax addl %edx,%eax hp1
  4491. movw %ax,%si movw %ax,%si hp2
  4492. ->
  4493. movswl %si,%eax movswl %si,%eax p
  4494. decw %eax addw %edx,%eax hp1
  4495. movw %ax,%si movw %ax,%si hp2
  4496. }
  4497. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4498. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4499. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4500. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4501. { limit size of constants as well to avoid assembler errors, but
  4502. check opsize to avoid overflow when left shifting the 1 }
  4503. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4504. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4505. {$ifdef x86_64}
  4506. { Be careful of, for example:
  4507. movl %reg1,%reg2
  4508. addl %reg3,%reg2
  4509. movq %reg2,%reg4
  4510. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4511. }
  4512. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4513. begin
  4514. taicpu(hp2).changeopsize(S_L);
  4515. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4516. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4517. end;
  4518. {$endif x86_64}
  4519. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4520. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4521. if taicpu(p).oper[0]^.typ=top_reg then
  4522. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4523. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4524. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4525. {
  4526. ->
  4527. movswl %si,%eax movswl %si,%eax p
  4528. decw %si addw %dx,%si hp1
  4529. movw %ax,%si movw %ax,%si hp2
  4530. }
  4531. case taicpu(hp1).ops of
  4532. 1:
  4533. begin
  4534. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4535. if taicpu(hp1).oper[0]^.typ=top_reg then
  4536. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4537. end;
  4538. 2:
  4539. begin
  4540. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4541. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4542. (taicpu(hp1).opcode<>A_SHL) and
  4543. (taicpu(hp1).opcode<>A_SHR) and
  4544. (taicpu(hp1).opcode<>A_SAR) then
  4545. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4546. end;
  4547. else
  4548. internalerror(2018111801);
  4549. end;
  4550. {
  4551. ->
  4552. decw %si addw %dx,%si p
  4553. }
  4554. RemoveInstruction(hp2);
  4555. end;
  4556. end;
  4557. end;
  4558. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4559. GetNextInstruction(hp1, hp2) and
  4560. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4561. MatchOperand(Taicpu(p).oper[0]^,0) and
  4562. (Taicpu(p).oper[1]^.typ = top_reg) and
  4563. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4564. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4565. { mov reg1,0
  4566. bts reg1,operand1 --> mov reg1,operand2
  4567. or reg1,operand2 bts reg1,operand1}
  4568. begin
  4569. Taicpu(hp2).opcode:=A_MOV;
  4570. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4571. asml.remove(hp1);
  4572. insertllitem(hp2,hp2.next,hp1);
  4573. RemoveCurrentp(p, hp1);
  4574. Result:=true;
  4575. exit;
  4576. end;
  4577. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4578. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4579. GetNextInstruction(hp1, hp2) and
  4580. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4581. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4582. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4583. { change
  4584. mov reg1,reg2
  4585. sub reg3,reg2
  4586. cmp reg3,reg1
  4587. into
  4588. mov reg1,reg2
  4589. sub reg3,reg2
  4590. }
  4591. begin
  4592. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4593. RemoveInstruction(hp2);
  4594. Result:=true;
  4595. exit;
  4596. end;
  4597. {
  4598. mov ref,reg0
  4599. <op> reg0,reg1
  4600. dealloc reg0
  4601. to
  4602. <op> ref,reg1
  4603. }
  4604. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4605. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4606. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4607. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4608. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4609. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4610. begin
  4611. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4612. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4613. RemoveCurrentp(p, hp1);
  4614. Result:=true;
  4615. exit;
  4616. end;
  4617. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4618. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4619. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4620. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4621. begin
  4622. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4623. {$ifdef x86_64}
  4624. { Convert:
  4625. movq x(ref),%reg64
  4626. shrq y,%reg64
  4627. To:
  4628. movl x+4(ref),%reg32
  4629. shrl y-32,%reg32 (Remove if y = 32)
  4630. }
  4631. if (taicpu(p).opsize = S_Q) and
  4632. (taicpu(hp1).opcode = A_SHR) and
  4633. (taicpu(hp1).oper[0]^.val >= 32) then
  4634. begin
  4635. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4636. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4637. { Convert to 32-bit }
  4638. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4639. taicpu(p).opsize := S_L;
  4640. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4641. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4642. if (taicpu(hp1).oper[0]^.val = 32) then
  4643. begin
  4644. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4645. RemoveInstruction(hp1);
  4646. end
  4647. else
  4648. begin
  4649. { This will potentially open up more arithmetic operations since
  4650. the peephole optimizer now has a big hint that only the lower
  4651. 32 bits are currently in use (and opcodes are smaller in size) }
  4652. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4653. taicpu(hp1).opsize := S_L;
  4654. Dec(taicpu(hp1).oper[0]^.val, 32);
  4655. DebugMsg(SPeepholeOptimization + PreMessage +
  4656. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4657. end;
  4658. Result := True;
  4659. Exit;
  4660. end;
  4661. {$endif x86_64}
  4662. { Convert:
  4663. movl x(ref),%reg
  4664. shrl $24,%reg
  4665. To:
  4666. movzbl x+3(ref),%reg
  4667. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4668. Also accept sar instead of shr, but convert to movsx instead of movzx
  4669. }
  4670. if taicpu(hp1).opcode = A_SHR then
  4671. MovUnaligned := A_MOVZX
  4672. else
  4673. MovUnaligned := A_MOVSX;
  4674. NewSize := S_NO;
  4675. NewOffset := 0;
  4676. case taicpu(p).opsize of
  4677. S_B:
  4678. { No valid combinations };
  4679. S_W:
  4680. if (taicpu(hp1).oper[0]^.val = 8) then
  4681. begin
  4682. NewSize := S_BW;
  4683. NewOffset := 1;
  4684. end;
  4685. S_L:
  4686. case taicpu(hp1).oper[0]^.val of
  4687. 16:
  4688. begin
  4689. NewSize := S_WL;
  4690. NewOffset := 2;
  4691. end;
  4692. 24:
  4693. begin
  4694. NewSize := S_BL;
  4695. NewOffset := 3;
  4696. end;
  4697. else
  4698. ;
  4699. end;
  4700. {$ifdef x86_64}
  4701. S_Q:
  4702. case taicpu(hp1).oper[0]^.val of
  4703. 32:
  4704. begin
  4705. if taicpu(hp1).opcode = A_SAR then
  4706. begin
  4707. { 32-bit to 64-bit is a distinct instruction }
  4708. MovUnaligned := A_MOVSXD;
  4709. NewSize := S_LQ;
  4710. NewOffset := 4;
  4711. end
  4712. else
  4713. { Should have been handled by MovShr2Mov above }
  4714. InternalError(2022081811);
  4715. end;
  4716. 48:
  4717. begin
  4718. NewSize := S_WQ;
  4719. NewOffset := 6;
  4720. end;
  4721. 56:
  4722. begin
  4723. NewSize := S_BQ;
  4724. NewOffset := 7;
  4725. end;
  4726. else
  4727. ;
  4728. end;
  4729. {$endif x86_64}
  4730. else
  4731. InternalError(2022081810);
  4732. end;
  4733. if (NewSize <> S_NO) and
  4734. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4735. begin
  4736. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4737. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4738. debug_op2str(MovUnaligned);
  4739. {$ifdef x86_64}
  4740. if MovUnaligned <> A_MOVSXD then
  4741. { Don't add size suffix for MOVSXD }
  4742. {$endif x86_64}
  4743. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4744. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4745. taicpu(p).opcode := MovUnaligned;
  4746. taicpu(p).opsize := NewSize;
  4747. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4748. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4749. RemoveInstruction(hp1);
  4750. Result := True;
  4751. Exit;
  4752. end;
  4753. end;
  4754. { Backward optimisation shared with OptPass2MOV }
  4755. if FuncMov2Func(p, hp1) then
  4756. begin
  4757. Result := True;
  4758. Exit;
  4759. end;
  4760. end;
  4761. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4762. var
  4763. hp1 : tai;
  4764. begin
  4765. Result:=false;
  4766. if taicpu(p).ops <> 2 then
  4767. exit;
  4768. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4769. GetNextInstruction(p,hp1) then
  4770. begin
  4771. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4772. (taicpu(hp1).ops = 2) then
  4773. begin
  4774. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4775. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4776. { movXX reg1, mem1 or movXX mem1, reg1
  4777. movXX mem2, reg2 movXX reg2, mem2}
  4778. begin
  4779. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4780. { movXX reg1, mem1 or movXX mem1, reg1
  4781. movXX mem2, reg1 movXX reg2, mem1}
  4782. begin
  4783. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4784. begin
  4785. { Removes the second statement from
  4786. movXX reg1, mem1/reg2
  4787. movXX mem1/reg2, reg1
  4788. }
  4789. if taicpu(p).oper[0]^.typ=top_reg then
  4790. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4791. { Removes the second statement from
  4792. movXX mem1/reg1, reg2
  4793. movXX reg2, mem1/reg1
  4794. }
  4795. if (taicpu(p).oper[1]^.typ=top_reg) and
  4796. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4797. begin
  4798. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4799. RemoveInstruction(hp1);
  4800. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4801. Result:=true;
  4802. exit;
  4803. end
  4804. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4805. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4806. begin
  4807. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4808. RemoveInstruction(hp1);
  4809. Result:=true;
  4810. exit;
  4811. end;
  4812. end
  4813. end;
  4814. end;
  4815. end;
  4816. end;
  4817. end;
  4818. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4819. var
  4820. hp1 : tai;
  4821. begin
  4822. result:=false;
  4823. { replace
  4824. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4825. MovX %mreg2,%mreg1
  4826. dealloc %mreg2
  4827. by
  4828. <Op>X %mreg2,%mreg1
  4829. ?
  4830. }
  4831. if GetNextInstruction(p,hp1) and
  4832. { we mix single and double opperations here because we assume that the compiler
  4833. generates vmovapd only after double operations and vmovaps only after single operations }
  4834. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4835. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4836. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4837. (taicpu(p).oper[0]^.typ=top_reg) then
  4838. begin
  4839. TransferUsedRegs(TmpUsedRegs);
  4840. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4841. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4842. begin
  4843. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4844. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4845. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4846. RemoveInstruction(hp1);
  4847. result:=true;
  4848. end;
  4849. end;
  4850. end;
  4851. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4852. var
  4853. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4854. JumpLabel, JumpLabel_dist: TAsmLabel;
  4855. FirstValue, SecondValue: TCGInt;
  4856. function OptimizeJump(var InputP: tai): Boolean;
  4857. var
  4858. TempBool: Boolean;
  4859. begin
  4860. Result := False;
  4861. TempBool := True;
  4862. if DoJumpOptimizations(InputP, TempBool) or
  4863. not TempBool then
  4864. begin
  4865. Result := True;
  4866. if Assigned(InputP) then
  4867. begin
  4868. { CollapseZeroDistJump will be set to the label or an align
  4869. before it after the jump if it optimises, whether or not
  4870. the label is live or dead }
  4871. if (InputP.typ = ait_align) or
  4872. (
  4873. (InputP.typ = ait_label) and
  4874. not (tai_label(InputP).labsym.is_used)
  4875. ) then
  4876. GetNextInstruction(InputP, InputP);
  4877. end;
  4878. Exit;
  4879. end;
  4880. end;
  4881. begin
  4882. Result := False;
  4883. if (taicpu(p).oper[0]^.typ = top_const) and
  4884. (taicpu(p).oper[0]^.val <> -1) then
  4885. begin
  4886. { Convert unsigned maximum constants to -1 to aid optimisation }
  4887. case taicpu(p).opsize of
  4888. S_B:
  4889. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4890. begin
  4891. taicpu(p).oper[0]^.val := -1;
  4892. Result := True;
  4893. Exit;
  4894. end;
  4895. S_W:
  4896. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4897. begin
  4898. taicpu(p).oper[0]^.val := -1;
  4899. Result := True;
  4900. Exit;
  4901. end;
  4902. S_L:
  4903. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4904. begin
  4905. taicpu(p).oper[0]^.val := -1;
  4906. Result := True;
  4907. Exit;
  4908. end;
  4909. {$ifdef x86_64}
  4910. S_Q:
  4911. { Storing anything greater than $7FFFFFFF is not possible so do
  4912. nothing };
  4913. {$endif x86_64}
  4914. else
  4915. InternalError(2021121001);
  4916. end;
  4917. end;
  4918. if GetNextInstruction(p, hp1) and
  4919. TrySwapMovCmp(p, hp1) then
  4920. begin
  4921. Result := True;
  4922. Exit;
  4923. end;
  4924. p_label := nil;
  4925. JumpLabel := nil;
  4926. if MatchInstruction(hp1, A_Jcc, []) then
  4927. begin
  4928. if OptimizeJump(hp1) then
  4929. begin
  4930. Result := True;
  4931. if Assigned(hp1) then
  4932. begin
  4933. { CollapseZeroDistJump will be set to the label or an align
  4934. before it after the jump if it optimises, whether or not
  4935. the label is live or dead }
  4936. if (hp1.typ = ait_align) or
  4937. (
  4938. (hp1.typ = ait_label) and
  4939. not (tai_label(hp1).labsym.is_used)
  4940. ) then
  4941. GetNextInstruction(hp1, hp1);
  4942. end;
  4943. TransferUsedRegs(TmpUsedRegs);
  4944. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4945. if not Assigned(hp1) or
  4946. (
  4947. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4948. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4949. ) then
  4950. begin
  4951. { No more conditional jumps; conditional statement is no longer required }
  4952. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4953. RemoveCurrentP(p);
  4954. end;
  4955. Exit;
  4956. end;
  4957. if IsJumpToLabel(taicpu(hp1)) then
  4958. begin
  4959. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4960. if Assigned(JumpLabel) then
  4961. p_label := getlabelwithsym(JumpLabel);
  4962. end;
  4963. end;
  4964. { Search for:
  4965. test $x,(reg/ref)
  4966. jne @lbl1
  4967. test $y,(reg/ref) (same register or reference)
  4968. jne @lbl1
  4969. Change to:
  4970. test $(x or y),(reg/ref)
  4971. jne @lbl1
  4972. (Note, this doesn't work with je instead of jne)
  4973. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4974. Also search for:
  4975. test $x,(reg/ref)
  4976. je @lbl1
  4977. ...
  4978. test $y,(reg/ref)
  4979. je/jne @lbl2
  4980. If (x or y) = x, then the second jump is deterministic
  4981. }
  4982. if (
  4983. (
  4984. (taicpu(p).oper[0]^.typ = top_const) or
  4985. (
  4986. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4987. (taicpu(p).oper[0]^.typ = top_reg) and
  4988. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4989. )
  4990. ) and
  4991. MatchInstruction(hp1, A_JCC, [])
  4992. ) then
  4993. begin
  4994. if (taicpu(p).oper[0]^.typ = top_reg) and
  4995. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4996. FirstValue := -1
  4997. else
  4998. FirstValue := taicpu(p).oper[0]^.val;
  4999. { If we have several test/jne's in a row, it might be the case that
  5000. the second label doesn't go to the same location, but the one
  5001. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5002. so accommodate for this with a while loop.
  5003. }
  5004. hp1_last := hp1;
  5005. while (
  5006. (
  5007. (taicpu(p).oper[1]^.typ = top_reg) and
  5008. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5009. ) or GetNextInstruction(hp1_last, p_dist)
  5010. ) and (p_dist.typ = ait_instruction) do
  5011. begin
  5012. if (
  5013. (
  5014. (taicpu(p_dist).opcode = A_TEST) and
  5015. (
  5016. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5017. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5018. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5019. )
  5020. ) or
  5021. (
  5022. { cmp 0,%reg = test %reg,%reg }
  5023. (taicpu(p_dist).opcode = A_CMP) and
  5024. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5025. )
  5026. ) and
  5027. { Make sure the destination operands are actually the same }
  5028. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5029. GetNextInstruction(p_dist, hp1_dist) and
  5030. MatchInstruction(hp1_dist, A_JCC, []) then
  5031. begin
  5032. if OptimizeJump(hp1_dist) then
  5033. begin
  5034. Result := True;
  5035. Exit;
  5036. end;
  5037. if
  5038. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5039. (
  5040. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5041. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5042. ) then
  5043. SecondValue := -1
  5044. else
  5045. SecondValue := taicpu(p_dist).oper[0]^.val;
  5046. { If both of the TEST constants are identical, delete the
  5047. second TEST that is unnecessary (be careful though, just
  5048. in case the flags are modified in between) }
  5049. if (FirstValue = SecondValue) then
  5050. begin
  5051. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5052. begin
  5053. { Since the second jump's condition is a subset of the first, we
  5054. know it will never branch because the first jump dominates it.
  5055. Get it out of the way now rather than wait for the jump
  5056. optimisations for a speed boost. }
  5057. if IsJumpToLabel(taicpu(hp1_dist)) then
  5058. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5059. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5060. RemoveInstruction(hp1_dist);
  5061. Result := True;
  5062. end
  5063. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5064. begin
  5065. { If the inverse of the first condition is a subset of the second,
  5066. the second one will definitely branch if the first one doesn't }
  5067. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5068. { We can remove the TEST instruction too }
  5069. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5070. RemoveInstruction(p_dist);
  5071. MakeUnconditional(taicpu(hp1_dist));
  5072. RemoveDeadCodeAfterJump(hp1_dist);
  5073. { Since the jump is now unconditional, we can't
  5074. continue any further with this particular
  5075. optimisation. The original TEST is still intact
  5076. though, so there might be something else we can
  5077. do }
  5078. Include(OptsToCheck, aoc_ForceNewIteration);
  5079. Break;
  5080. end;
  5081. if Result or
  5082. { If a jump wasn't removed or made unconditional, only
  5083. remove the identical TEST instruction if the flags
  5084. weren't modified }
  5085. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5086. begin
  5087. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5088. RemoveInstruction(p_dist);
  5089. { If the jump was removed or made unconditional, we
  5090. don't need to allocate NR_DEFAULTFLAGS over the
  5091. entire range }
  5092. if not Result then
  5093. begin
  5094. { Mark the flags as 'in use' over the entire range }
  5095. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5096. { Speed gain - continue search from the Jcc instruction }
  5097. hp1_last := hp1_dist;
  5098. { Only the TEST instruction was removed, and the
  5099. original was unchanged, so we can safely do
  5100. another iteration of the while loop }
  5101. Include(OptsToCheck, aoc_ForceNewIteration);
  5102. Continue;
  5103. end;
  5104. Exit;
  5105. end;
  5106. end;
  5107. hp1_last := nil;
  5108. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5109. (
  5110. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5111. { Always adjacent under -O2 and under }
  5112. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5113. (
  5114. GetNextInstruction(hp1, hp1_last) and
  5115. (hp1_last = p_dist)
  5116. )
  5117. ) and
  5118. (
  5119. (
  5120. { Test the following variant:
  5121. test $x,(reg/ref)
  5122. jne @lbl1
  5123. test $y,(reg/ref)
  5124. je @lbl2
  5125. @lbl1:
  5126. Becomes:
  5127. test $(x or y),(reg/ref)
  5128. je @lbl2
  5129. @lbl1: (may become a dead label)
  5130. }
  5131. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5132. GetNextInstruction(hp1_dist, hp1_last) and
  5133. (hp1_last = p_label)
  5134. ) or
  5135. (
  5136. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5137. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5138. then the second jump will never branch, so it can also be
  5139. removed regardless of where it goes }
  5140. (
  5141. (FirstValue = -1) or
  5142. (SecondValue = -1) or
  5143. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5144. )
  5145. )
  5146. ) then
  5147. begin
  5148. { Same jump location... can be a register since nothing's changed }
  5149. { If any of the entries are equivalent to test %reg,%reg, then the
  5150. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5151. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5152. if (hp1_last = p_label) then
  5153. begin
  5154. { Variant }
  5155. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5156. RemoveInstruction(p_dist);
  5157. if Assigned(JumpLabel) then
  5158. JumpLabel.decrefs;
  5159. RemoveInstruction(hp1);
  5160. end
  5161. else
  5162. begin
  5163. { Only remove the second test if no jumps or other conditional instructions follow }
  5164. TransferUsedRegs(TmpUsedRegs);
  5165. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5166. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5167. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5168. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5169. begin
  5170. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5171. RemoveInstruction(p_dist);
  5172. { Remove the first jump, not the second, to keep
  5173. any register deallocations between the second
  5174. TEST/JNE pair in the same place. Aids future
  5175. optimisation. }
  5176. if Assigned(JumpLabel) then
  5177. JumpLabel.decrefs;
  5178. RemoveInstruction(hp1);
  5179. end
  5180. else
  5181. begin
  5182. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5183. if IsJumpToLabel(taicpu(hp1_dist)) then
  5184. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5185. { Remove second jump in this instance }
  5186. RemoveInstruction(hp1_dist);
  5187. end;
  5188. end;
  5189. Result := True;
  5190. Exit;
  5191. end;
  5192. end;
  5193. if { If -O2 and under, it may stop on any old instruction }
  5194. (cs_opt_level3 in current_settings.optimizerswitches) and
  5195. (taicpu(p).oper[1]^.typ = top_reg) and
  5196. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5197. begin
  5198. hp1_last := p_dist;
  5199. Continue;
  5200. end;
  5201. Break;
  5202. end;
  5203. end;
  5204. { Search for:
  5205. test %reg,%reg
  5206. j(c1) @lbl1
  5207. ...
  5208. @lbl:
  5209. test %reg,%reg (same register)
  5210. j(c2) @lbl2
  5211. If c2 is a subset of c1, change to:
  5212. test %reg,%reg
  5213. j(c1) @lbl2
  5214. (@lbl1 may become a dead label as a result)
  5215. }
  5216. if (taicpu(p).oper[1]^.typ = top_reg) and
  5217. (taicpu(p).oper[0]^.typ = top_reg) and
  5218. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5219. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5220. Assigned(p_label) and
  5221. GetNextInstruction(p_label, p_dist) and
  5222. MatchInstruction(p_dist, A_TEST, []) and
  5223. { It's fine if the second test uses smaller sub-registers }
  5224. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5225. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5226. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5227. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5228. GetNextInstruction(p_dist, hp1_dist) and
  5229. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5230. begin
  5231. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5232. if JumpLabel = JumpLabel_dist then
  5233. { This is an infinite loop }
  5234. Exit;
  5235. { Best optimisation when the first condition is a subset (or equal) of the second }
  5236. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5237. begin
  5238. { Any registers used here will already be allocated }
  5239. if Assigned(JumpLabel) then
  5240. JumpLabel.DecRefs;
  5241. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5242. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5243. Result := True;
  5244. Exit;
  5245. end;
  5246. end;
  5247. end;
  5248. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5249. var
  5250. hp1, hp2: tai;
  5251. ActiveReg: TRegister;
  5252. OldOffset: asizeint;
  5253. ThisConst: TCGInt;
  5254. function RegDeallocated: Boolean;
  5255. begin
  5256. TransferUsedRegs(TmpUsedRegs);
  5257. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5258. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5259. end;
  5260. begin
  5261. result:=false;
  5262. hp1 := nil;
  5263. { replace
  5264. addX const,%reg1
  5265. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5266. dealloc %reg1
  5267. by
  5268. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5269. }
  5270. if MatchOpType(taicpu(p),top_const,top_reg) then
  5271. begin
  5272. ActiveReg := taicpu(p).oper[1]^.reg;
  5273. { Ensures the entire register was updated }
  5274. if (taicpu(p).opsize >= S_L) and
  5275. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5276. MatchInstruction(hp1,A_LEA,[]) and
  5277. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5278. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5279. (
  5280. { Cover the case where the register in the reference is also the destination register }
  5281. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5282. (
  5283. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5284. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5285. RegDeallocated
  5286. )
  5287. ) then
  5288. begin
  5289. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5290. {$push}
  5291. {$R-}{$Q-}
  5292. { Explicitly disable overflow checking for these offset calculation
  5293. as those do not matter for the final result }
  5294. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5295. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5296. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5297. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5298. {$pop}
  5299. {$ifdef x86_64}
  5300. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5301. begin
  5302. { Overflow; abort }
  5303. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5304. end
  5305. else
  5306. {$endif x86_64}
  5307. begin
  5308. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5309. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5310. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5311. RemoveCurrentP(p, hp1)
  5312. else
  5313. RemoveCurrentP(p);
  5314. result:=true;
  5315. Exit;
  5316. end;
  5317. end;
  5318. if (
  5319. { Save calling GetNextInstructionUsingReg again }
  5320. Assigned(hp1) or
  5321. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5322. ) and
  5323. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5324. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5325. begin
  5326. if taicpu(hp1).oper[0]^.typ = top_const then
  5327. begin
  5328. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5329. if taicpu(hp1).opcode = A_ADD then
  5330. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5331. else
  5332. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5333. Result := True;
  5334. { Handle any overflows }
  5335. case taicpu(p).opsize of
  5336. S_B:
  5337. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5338. S_W:
  5339. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5340. S_L:
  5341. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5342. {$ifdef x86_64}
  5343. S_Q:
  5344. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5345. { Overflow; abort }
  5346. Result := False
  5347. else
  5348. taicpu(p).oper[0]^.val := ThisConst;
  5349. {$endif x86_64}
  5350. else
  5351. InternalError(2021102610);
  5352. end;
  5353. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5354. if Result then
  5355. begin
  5356. if (taicpu(p).oper[0]^.val < 0) and
  5357. (
  5358. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5359. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5360. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5361. ) then
  5362. begin
  5363. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5364. taicpu(p).opcode := A_SUB;
  5365. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5366. end
  5367. else
  5368. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5369. RemoveInstruction(hp1);
  5370. end;
  5371. end
  5372. else
  5373. begin
  5374. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5375. TransferUsedRegs(TmpUsedRegs);
  5376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5377. hp2 := p;
  5378. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5379. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5380. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5381. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5382. begin
  5383. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5384. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5385. Asml.Remove(p);
  5386. Asml.InsertAfter(p, hp1);
  5387. p := hp1;
  5388. Result := True;
  5389. Exit;
  5390. end;
  5391. end;
  5392. end;
  5393. if DoArithCombineOpt(p) then
  5394. Result:=true;
  5395. end;
  5396. end;
  5397. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5398. var
  5399. hp1, hp2: tai;
  5400. ref: Integer;
  5401. saveref: treference;
  5402. offsetcalc: Int64;
  5403. TempReg: TRegister;
  5404. Multiple: TCGInt;
  5405. Adjacent, IntermediateRegDiscarded: Boolean;
  5406. begin
  5407. Result:=false;
  5408. { play save and throw an error if LEA uses a seg register prefix,
  5409. this is most likely an error somewhere else }
  5410. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5411. internalerror(2022022001);
  5412. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5413. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5414. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5415. (
  5416. { do not mess with leas accessing the stack pointer
  5417. unless it's a null operation }
  5418. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5419. (
  5420. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5421. (taicpu(p).oper[0]^.ref^.offset = 0)
  5422. )
  5423. ) and
  5424. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5425. begin
  5426. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5427. begin
  5428. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5429. begin
  5430. taicpu(p).opcode := A_MOV;
  5431. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5432. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5433. end
  5434. else
  5435. begin
  5436. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5437. RemoveCurrentP(p);
  5438. end;
  5439. Result:=true;
  5440. exit;
  5441. end
  5442. else if (
  5443. { continue to use lea to adjust the stack pointer,
  5444. it is the recommended way, but only if not optimizing for size }
  5445. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5446. (cs_opt_size in current_settings.optimizerswitches)
  5447. ) and
  5448. { If the flags register is in use, don't change the instruction
  5449. to an ADD otherwise this will scramble the flags. [Kit] }
  5450. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5451. ConvertLEA(taicpu(p)) then
  5452. begin
  5453. Result:=true;
  5454. exit;
  5455. end;
  5456. end;
  5457. { Don't optimise if the stack or frame pointer is the destination register }
  5458. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5459. Exit;
  5460. if GetNextInstruction(p,hp1) and
  5461. (hp1.typ=ait_instruction) then
  5462. begin
  5463. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5464. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5465. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5466. begin
  5467. TransferUsedRegs(TmpUsedRegs);
  5468. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5469. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5470. begin
  5471. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5472. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5473. RemoveInstruction(hp1);
  5474. result:=true;
  5475. exit;
  5476. end;
  5477. end;
  5478. { changes
  5479. lea <ref1>, reg1
  5480. <op> ...,<ref. with reg1>,...
  5481. to
  5482. <op> ...,<ref1>,... }
  5483. { find a reference which uses reg1 }
  5484. 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
  5485. ref:=0
  5486. 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
  5487. ref:=1
  5488. else
  5489. ref:=-1;
  5490. if (ref<>-1) and
  5491. { reg1 must be either the base or the index }
  5492. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5493. begin
  5494. { reg1 can be removed from the reference }
  5495. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5496. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5497. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5498. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5499. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5500. else
  5501. Internalerror(2019111201);
  5502. { check if the can insert all data of the lea into the second instruction }
  5503. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5504. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5505. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5506. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5507. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5508. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5509. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5510. {$ifdef x86_64}
  5511. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5512. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5513. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5514. )
  5515. {$endif x86_64}
  5516. then
  5517. begin
  5518. { reg1 might not used by the second instruction after it is remove from the reference }
  5519. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5520. begin
  5521. TransferUsedRegs(TmpUsedRegs);
  5522. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5523. { reg1 is not updated so it might not be used afterwards }
  5524. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5525. begin
  5526. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5527. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5528. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5529. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5530. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5531. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5532. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5533. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5534. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5535. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5536. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5537. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5538. RemoveCurrentP(p, hp1);
  5539. result:=true;
  5540. exit;
  5541. end
  5542. end;
  5543. end;
  5544. { recover }
  5545. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5546. end;
  5547. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5548. if Adjacent or
  5549. { Check further ahead (up to 2 instructions ahead for -O2) }
  5550. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5551. begin
  5552. { Check common LEA/LEA conditions }
  5553. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5554. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5555. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5556. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5557. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5558. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5559. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5560. (
  5561. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5562. calling it (since it calls GetNextInstruction) }
  5563. Adjacent or
  5564. (
  5565. (
  5566. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5567. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5568. ) and (
  5569. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5570. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5571. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5572. )
  5573. )
  5574. ) then
  5575. begin
  5576. TransferUsedRegs(TmpUsedRegs);
  5577. hp2 := p;
  5578. repeat
  5579. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5580. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5581. IntermediateRegDiscarded :=
  5582. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5583. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5584. { changes
  5585. lea offset1(regX,scale), reg1
  5586. lea offset2(reg1,reg1), reg2
  5587. to
  5588. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5589. and
  5590. lea offset1(regX,scale1), reg1
  5591. lea offset2(reg1,scale2), reg2
  5592. to
  5593. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5594. and
  5595. lea offset1(regX,scale1), reg1
  5596. lea offset2(reg3,reg1,scale2), reg2
  5597. to
  5598. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5599. ... so long as the final scale does not exceed 8
  5600. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5601. }
  5602. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5603. (
  5604. { Don't optimise if size is a concern and the intermediate register remains in use }
  5605. IntermediateRegDiscarded or
  5606. not (cs_opt_size in current_settings.optimizerswitches)
  5607. ) and
  5608. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5609. (
  5610. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5611. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5612. ) and (
  5613. (
  5614. { lea (reg1,scale2), reg2 variant }
  5615. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5616. (
  5617. Adjacent or
  5618. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5619. ) and
  5620. (
  5621. (
  5622. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5623. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5624. ) or (
  5625. { lea (regX,regX), reg1 variant }
  5626. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5627. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5628. )
  5629. )
  5630. ) or (
  5631. { lea (reg1,reg1), reg1 variant }
  5632. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5633. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5634. )
  5635. ) then
  5636. begin
  5637. { Make everything homogeneous to make calculations easier }
  5638. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5639. begin
  5640. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5641. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5642. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5643. else
  5644. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5645. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5646. end;
  5647. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5648. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5649. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5650. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5651. begin
  5652. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5653. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5654. begin
  5655. { Put the register to change in the index register }
  5656. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5657. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5658. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5659. end;
  5660. { Change lea (reg,reg) to lea(,reg,2) }
  5661. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5662. begin
  5663. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5664. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5665. end;
  5666. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5667. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5668. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5669. { Just to prevent miscalculations }
  5670. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5671. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5672. else
  5673. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5674. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5675. if IntermediateRegDiscarded then
  5676. begin
  5677. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5678. RemoveCurrentP(p);
  5679. end
  5680. else
  5681. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5682. result:=true;
  5683. exit;
  5684. end;
  5685. end;
  5686. { changes
  5687. lea offset1(regX), reg1
  5688. lea offset2(reg1), reg2
  5689. to
  5690. lea offset1+offset2(regX), reg2 }
  5691. if (
  5692. { Don't optimise if size is a concern and the intermediate register remains in use }
  5693. IntermediateRegDiscarded or
  5694. not (cs_opt_size in current_settings.optimizerswitches)
  5695. ) and
  5696. (
  5697. (
  5698. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5699. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5700. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5701. ) or (
  5702. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5703. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5704. (
  5705. (
  5706. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5707. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5708. ) or (
  5709. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5710. (
  5711. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5712. (
  5713. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5714. (
  5715. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5716. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5717. )
  5718. )
  5719. )
  5720. )
  5721. )
  5722. )
  5723. ) then
  5724. begin
  5725. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5726. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5727. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5728. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5729. begin
  5730. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5731. begin
  5732. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5733. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5734. { if the register is used as index and base, we have to increase for base as well
  5735. and adapt base }
  5736. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5737. begin
  5738. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5739. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5740. end;
  5741. end
  5742. else
  5743. begin
  5744. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5745. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5746. end;
  5747. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5748. begin
  5749. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5750. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5751. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5752. { Catch the situation where the base = index
  5753. and treat this as *2. The scalefactor of
  5754. p will be 0 or 1 due to the conditional
  5755. checks above. Fixes i40647 }
  5756. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5757. else
  5758. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5759. end;
  5760. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5761. if IntermediateRegDiscarded then
  5762. begin
  5763. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5764. RemoveCurrentP(p);
  5765. end
  5766. else
  5767. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5768. result:=true;
  5769. exit;
  5770. end;
  5771. end;
  5772. end;
  5773. { Change:
  5774. leal/q $x(%reg1),%reg2
  5775. ...
  5776. shll/q $y,%reg2
  5777. To:
  5778. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5779. }
  5780. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5781. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5782. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5783. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5784. (taicpu(hp1).oper[0]^.val <= 3) then
  5785. begin
  5786. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5787. TransferUsedRegs(TmpUsedRegs);
  5788. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5789. if
  5790. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5791. (this works even if scalefactor is zero) }
  5792. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5793. { Ensure offset doesn't go out of bounds }
  5794. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5795. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5796. (
  5797. (
  5798. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5799. (
  5800. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5801. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5802. (
  5803. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5804. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5805. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5806. )
  5807. )
  5808. ) or (
  5809. (
  5810. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5811. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5812. ) and
  5813. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5814. )
  5815. ) then
  5816. begin
  5817. repeat
  5818. with taicpu(p).oper[0]^.ref^ do
  5819. begin
  5820. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5821. if index = base then
  5822. begin
  5823. if Multiple > 4 then
  5824. { Optimisation will no longer work because resultant
  5825. scale factor will exceed 8 }
  5826. Break;
  5827. base := NR_NO;
  5828. scalefactor := 2;
  5829. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5830. end
  5831. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5832. begin
  5833. { Scale factor only works on the index register }
  5834. index := base;
  5835. base := NR_NO;
  5836. end;
  5837. { For safety }
  5838. if scalefactor <= 1 then
  5839. begin
  5840. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5841. scalefactor := Multiple;
  5842. end
  5843. else
  5844. begin
  5845. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5846. scalefactor := scalefactor * Multiple;
  5847. end;
  5848. offset := offset * Multiple;
  5849. end;
  5850. RemoveInstruction(hp1);
  5851. Result := True;
  5852. Exit;
  5853. { This repeat..until loop exists for the benefit of Break }
  5854. until True;
  5855. end;
  5856. end;
  5857. end;
  5858. end;
  5859. end;
  5860. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5861. var
  5862. hp1 : tai;
  5863. SubInstr: Boolean;
  5864. ThisConst: TCGInt;
  5865. const
  5866. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5867. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5868. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5869. begin
  5870. Result := False;
  5871. if taicpu(p).oper[0]^.typ <> top_const then
  5872. { Should have been confirmed before calling }
  5873. InternalError(2021102601);
  5874. SubInstr := (taicpu(p).opcode = A_SUB);
  5875. if GetLastInstruction(p, hp1) and
  5876. (hp1.typ = ait_instruction) and
  5877. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5878. begin
  5879. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5880. { Bad size }
  5881. InternalError(2022042001);
  5882. case taicpu(hp1).opcode Of
  5883. A_INC:
  5884. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5885. begin
  5886. if SubInstr then
  5887. ThisConst := taicpu(p).oper[0]^.val - 1
  5888. else
  5889. ThisConst := taicpu(p).oper[0]^.val + 1;
  5890. end
  5891. else
  5892. Exit;
  5893. A_DEC:
  5894. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5895. begin
  5896. if SubInstr then
  5897. ThisConst := taicpu(p).oper[0]^.val + 1
  5898. else
  5899. ThisConst := taicpu(p).oper[0]^.val - 1;
  5900. end
  5901. else
  5902. Exit;
  5903. A_SUB:
  5904. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5905. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5906. begin
  5907. if SubInstr then
  5908. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5909. else
  5910. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5911. end
  5912. else
  5913. Exit;
  5914. A_ADD:
  5915. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5916. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5917. begin
  5918. if SubInstr then
  5919. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5920. else
  5921. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5922. end
  5923. else
  5924. Exit;
  5925. else
  5926. Exit;
  5927. end;
  5928. { Check that the values are in range }
  5929. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5930. { Overflow; abort }
  5931. Exit;
  5932. if (ThisConst = 0) then
  5933. begin
  5934. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5935. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5936. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5937. RemoveInstruction(hp1);
  5938. hp1 := tai(p.next);
  5939. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5940. if not GetLastInstruction(hp1, p) then
  5941. p := hp1;
  5942. end
  5943. else
  5944. begin
  5945. if taicpu(hp1).opercnt=1 then
  5946. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5947. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5948. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5949. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5950. else
  5951. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5952. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5953. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5954. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5955. RemoveInstruction(hp1);
  5956. taicpu(p).loadconst(0, ThisConst);
  5957. end;
  5958. Result := True;
  5959. end;
  5960. end;
  5961. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5962. begin
  5963. Result := False;
  5964. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5965. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5966. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5967. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5968. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5969. (
  5970. (
  5971. (taicpu(hp1).opcode = A_TEST)
  5972. ) or (
  5973. (taicpu(hp1).opcode = A_CMP) and
  5974. { A sanity check more than anything }
  5975. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5976. )
  5977. ) then
  5978. begin
  5979. { change
  5980. mov mem, %reg
  5981. ...
  5982. cmp/test x, %reg / test %reg,%reg
  5983. (reg deallocated)
  5984. to
  5985. cmp/test x, mem / cmp 0, mem
  5986. }
  5987. TransferUsedRegs(TmpUsedRegs);
  5988. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5989. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5990. begin
  5991. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5992. if (taicpu(hp1).opcode = A_TEST) and
  5993. (
  5994. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5995. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5996. ) then
  5997. begin
  5998. taicpu(hp1).opcode := A_CMP;
  5999. taicpu(hp1).loadconst(0, 0);
  6000. end;
  6001. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6002. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6003. RemoveCurrentP(p);
  6004. if (p <> hp1) then
  6005. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6006. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6007. { Make sure the flags are allocated across the CMP instruction }
  6008. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6009. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6010. Result := True;
  6011. Exit;
  6012. end;
  6013. end;
  6014. end;
  6015. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6016. var
  6017. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6018. ThisReg, SecondReg: TRegister;
  6019. JumpLoc: TAsmLabel;
  6020. NewSize: TOpSize;
  6021. begin
  6022. Result := False;
  6023. {
  6024. Convert:
  6025. j<c> .L1
  6026. .L2:
  6027. mov 1,reg
  6028. jmp .L3 (or ret, although it might not be a RET yet)
  6029. .L1:
  6030. mov 0,reg
  6031. jmp .L3 (or ret)
  6032. ( As long as .L3 <> .L1 or .L2)
  6033. To:
  6034. mov 0,reg
  6035. set<not(c)> reg
  6036. jmp .L3 (or ret)
  6037. .L2:
  6038. mov 1,reg
  6039. jmp .L3 (or ret)
  6040. .L1:
  6041. mov 0,reg
  6042. jmp .L3 (or ret)
  6043. }
  6044. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6045. Exit;
  6046. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6047. if GetNextInstruction(hp_label, hp2) and
  6048. MatchInstruction(hp2,A_MOV,[]) and
  6049. (taicpu(hp2).oper[0]^.typ = top_const) and
  6050. (
  6051. (
  6052. (taicpu(hp2).oper[1]^.typ = top_reg)
  6053. {$ifdef i386}
  6054. { Under i386, ESI, EDI, EBP and ESP
  6055. don't have an 8-bit representation }
  6056. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6057. {$endif i386}
  6058. ) or (
  6059. {$ifdef i386}
  6060. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6061. {$endif i386}
  6062. (taicpu(hp2).opsize = S_B)
  6063. )
  6064. ) and
  6065. GetNextInstruction(hp2, hp3) and
  6066. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6067. (
  6068. (taicpu(hp3).opcode=A_RET) or
  6069. (
  6070. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6071. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6072. )
  6073. ) and
  6074. GetNextInstruction(hp3, hp4) and
  6075. (hp4.typ=ait_label) and
  6076. (tai_label(hp4).labsym=JumpLoc) and
  6077. (
  6078. not (cs_opt_size in current_settings.optimizerswitches) or
  6079. { If the initial jump is the label's only reference, then it will
  6080. become a dead label if the other conditions are met and hence
  6081. remove at least 2 instructions, including a jump }
  6082. (JumpLoc.getrefs = 1)
  6083. ) and
  6084. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6085. that will be optimised out }
  6086. GetNextInstruction(hp4, hp5) and
  6087. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6088. (taicpu(hp5).oper[0]^.typ = top_const) and
  6089. (
  6090. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6091. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6092. ) and
  6093. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6094. GetNextInstruction(hp5,hp6) and
  6095. (
  6096. (hp6.typ<>ait_label) or
  6097. SkipLabels(hp6, hp6)
  6098. ) and
  6099. (hp6.typ=ait_instruction) then
  6100. begin
  6101. { First, let's look at the two jumps that are hp3 and hp6 }
  6102. if not
  6103. (
  6104. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6105. (
  6106. (taicpu(hp6).opcode=A_RET) or
  6107. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6108. )
  6109. ) then
  6110. { If condition is False, then the JMP/RET instructions matched conventionally }
  6111. begin
  6112. { See if one of the jumps can be instantly converted into a RET }
  6113. if (taicpu(hp3).opcode=A_JMP) then
  6114. begin
  6115. { Reuse hp5 }
  6116. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6117. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6118. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6119. Exit;
  6120. if MatchInstruction(hp5, A_RET, []) then
  6121. begin
  6122. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6123. ConvertJumpToRET(hp3, hp5);
  6124. Result := True;
  6125. end
  6126. else
  6127. Exit;
  6128. end;
  6129. if (taicpu(hp6).opcode=A_JMP) then
  6130. begin
  6131. { Reuse hp5 }
  6132. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6133. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6134. Exit;
  6135. if MatchInstruction(hp5, A_RET, []) then
  6136. begin
  6137. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6138. ConvertJumpToRET(hp6, hp5);
  6139. Result := True;
  6140. end
  6141. else
  6142. Exit;
  6143. end;
  6144. if not
  6145. (
  6146. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6147. (
  6148. (taicpu(hp6).opcode=A_RET) or
  6149. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6150. )
  6151. ) then
  6152. { Still doesn't match }
  6153. Exit;
  6154. end;
  6155. if (taicpu(hp2).oper[0]^.val = 1) then
  6156. begin
  6157. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6158. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6159. end
  6160. else
  6161. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6162. if taicpu(hp2).opsize=S_B then
  6163. begin
  6164. if taicpu(hp2).oper[1]^.typ = top_reg then
  6165. begin
  6166. SecondReg := taicpu(hp2).oper[1]^.reg;
  6167. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6168. end
  6169. else
  6170. begin
  6171. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6172. SecondReg := NR_NO;
  6173. end;
  6174. hp_pos := p;
  6175. hp_allocstart := hp4;
  6176. end
  6177. else
  6178. begin
  6179. { Will be a register because the size can't be S_B otherwise }
  6180. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6181. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6182. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6183. if (cs_opt_size in current_settings.optimizerswitches) then
  6184. begin
  6185. { Favour using MOVZX when optimising for size }
  6186. case taicpu(hp2).opsize of
  6187. S_W:
  6188. NewSize := S_BW;
  6189. S_L:
  6190. NewSize := S_BL;
  6191. {$ifdef x86_64}
  6192. S_Q:
  6193. begin
  6194. NewSize := S_BL;
  6195. { Will implicitly zero-extend to 64-bit }
  6196. setsubreg(SecondReg, R_SUBD);
  6197. end;
  6198. {$endif x86_64}
  6199. else
  6200. InternalError(2022101301);
  6201. end;
  6202. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6203. { Inserting it right before p will guarantee that the flags are also tracked }
  6204. Asml.InsertBefore(hp5, p);
  6205. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6206. hp_pos := hp5;
  6207. hp_allocstart := hp4;
  6208. end
  6209. else
  6210. begin
  6211. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6212. { Inserting it right before p will guarantee that the flags are also tracked }
  6213. Asml.InsertBefore(hp5, p);
  6214. hp_pos := p;
  6215. hp_allocstart := hp5;
  6216. end;
  6217. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6218. end;
  6219. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6220. taicpu(hp4).condition := taicpu(p).condition;
  6221. asml.InsertBefore(hp4, hp_pos);
  6222. if taicpu(hp3).is_jmp then
  6223. begin
  6224. JumpLoc.decrefs;
  6225. MakeUnconditional(taicpu(p));
  6226. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6227. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6228. end
  6229. else
  6230. ConvertJumpToRET(p, hp3);
  6231. if SecondReg <> NR_NO then
  6232. { Ensure the destination register is allocated over this region }
  6233. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6234. if (JumpLoc.getrefs = 0) then
  6235. RemoveDeadCodeAfterJump(hp3);
  6236. Result:=true;
  6237. exit;
  6238. end;
  6239. end;
  6240. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6241. var
  6242. hp1, hp2: tai;
  6243. ActiveReg: TRegister;
  6244. OldOffset: asizeint;
  6245. ThisConst: TCGInt;
  6246. function RegDeallocated: Boolean;
  6247. begin
  6248. TransferUsedRegs(TmpUsedRegs);
  6249. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6250. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6251. end;
  6252. begin
  6253. Result:=false;
  6254. hp1 := nil;
  6255. { replace
  6256. subX const,%reg1
  6257. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6258. dealloc %reg1
  6259. by
  6260. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6261. }
  6262. if MatchOpType(taicpu(p),top_const,top_reg) then
  6263. begin
  6264. ActiveReg := taicpu(p).oper[1]^.reg;
  6265. { Ensures the entire register was updated }
  6266. if (taicpu(p).opsize >= S_L) and
  6267. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6268. MatchInstruction(hp1,A_LEA,[]) and
  6269. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6270. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6271. (
  6272. { Cover the case where the register in the reference is also the destination register }
  6273. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6274. (
  6275. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6276. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6277. RegDeallocated
  6278. )
  6279. ) then
  6280. begin
  6281. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6282. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6283. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6284. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6285. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6286. {$ifdef x86_64}
  6287. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6288. begin
  6289. { Overflow; abort }
  6290. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6291. end
  6292. else
  6293. {$endif x86_64}
  6294. begin
  6295. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6296. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6297. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6298. RemoveCurrentP(p, hp1)
  6299. else
  6300. RemoveCurrentP(p);
  6301. result:=true;
  6302. Exit;
  6303. end;
  6304. end;
  6305. if (
  6306. { Save calling GetNextInstructionUsingReg again }
  6307. Assigned(hp1) or
  6308. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6309. ) and
  6310. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6311. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6312. begin
  6313. if taicpu(hp1).oper[0]^.typ = top_const then
  6314. begin
  6315. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6316. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6317. Result := True;
  6318. { Handle any overflows }
  6319. case taicpu(p).opsize of
  6320. S_B:
  6321. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6322. S_W:
  6323. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6324. S_L:
  6325. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6326. {$ifdef x86_64}
  6327. S_Q:
  6328. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6329. { Overflow; abort }
  6330. Result := False
  6331. else
  6332. taicpu(p).oper[0]^.val := ThisConst;
  6333. {$endif x86_64}
  6334. else
  6335. InternalError(2021102611);
  6336. end;
  6337. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6338. if Result then
  6339. begin
  6340. if (taicpu(p).oper[0]^.val < 0) and
  6341. (
  6342. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6343. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6344. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6345. ) then
  6346. begin
  6347. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6348. taicpu(p).opcode := A_SUB;
  6349. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6350. end
  6351. else
  6352. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6353. RemoveInstruction(hp1);
  6354. end;
  6355. end
  6356. else
  6357. begin
  6358. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6359. TransferUsedRegs(TmpUsedRegs);
  6360. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6361. hp2 := p;
  6362. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6363. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6364. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6365. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6366. begin
  6367. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6368. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6369. Asml.Remove(p);
  6370. Asml.InsertAfter(p, hp1);
  6371. p := hp1;
  6372. Result := True;
  6373. Exit;
  6374. end;
  6375. end;
  6376. end;
  6377. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6378. { * change "sub/add const1, reg" or "dec reg" followed by
  6379. "sub const2, reg" to one "sub ..., reg" }
  6380. {$ifdef i386}
  6381. if (taicpu(p).oper[0]^.val = 2) and
  6382. (ActiveReg = NR_ESP) and
  6383. { Don't do the sub/push optimization if the sub }
  6384. { comes from setting up the stack frame (JM) }
  6385. (not(GetLastInstruction(p,hp1)) or
  6386. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6387. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6388. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6389. begin
  6390. hp1 := tai(p.next);
  6391. while Assigned(hp1) and
  6392. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6393. not RegReadByInstruction(NR_ESP,hp1) and
  6394. not RegModifiedByInstruction(NR_ESP,hp1) do
  6395. hp1 := tai(hp1.next);
  6396. if Assigned(hp1) and
  6397. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6398. begin
  6399. taicpu(hp1).changeopsize(S_L);
  6400. if taicpu(hp1).oper[0]^.typ=top_reg then
  6401. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6402. hp1 := tai(p.next);
  6403. RemoveCurrentp(p, hp1);
  6404. Result:=true;
  6405. exit;
  6406. end;
  6407. end;
  6408. {$endif i386}
  6409. if DoArithCombineOpt(p) then
  6410. Result:=true;
  6411. end;
  6412. end;
  6413. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6414. var
  6415. TmpBool1,TmpBool2 : Boolean;
  6416. tmpref : treference;
  6417. hp1,hp2: tai;
  6418. mask, shiftval: tcgint;
  6419. begin
  6420. Result:=false;
  6421. { All these optimisations work on "shl/sal const,%reg" }
  6422. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6423. Exit;
  6424. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6425. (taicpu(p).oper[0]^.val <= 3) then
  6426. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6427. begin
  6428. { should we check the next instruction? }
  6429. TmpBool1 := True;
  6430. { have we found an add/sub which could be
  6431. integrated in the lea? }
  6432. TmpBool2 := False;
  6433. reference_reset(tmpref,2,[]);
  6434. TmpRef.index := taicpu(p).oper[1]^.reg;
  6435. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6436. while TmpBool1 and
  6437. GetNextInstruction(p, hp1) and
  6438. (tai(hp1).typ = ait_instruction) and
  6439. ((((taicpu(hp1).opcode = A_ADD) or
  6440. (taicpu(hp1).opcode = A_SUB)) and
  6441. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6442. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6443. (((taicpu(hp1).opcode = A_INC) or
  6444. (taicpu(hp1).opcode = A_DEC)) and
  6445. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6446. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6447. ((taicpu(hp1).opcode = A_LEA) and
  6448. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6449. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6450. (not GetNextInstruction(hp1,hp2) or
  6451. not instrReadsFlags(hp2)) Do
  6452. begin
  6453. TmpBool1 := False;
  6454. if taicpu(hp1).opcode=A_LEA then
  6455. begin
  6456. if (TmpRef.base = NR_NO) and
  6457. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6458. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6459. { Segment register isn't a concern here }
  6460. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6461. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6462. begin
  6463. TmpBool1 := True;
  6464. TmpBool2 := True;
  6465. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6466. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6467. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6468. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6469. RemoveInstruction(hp1);
  6470. end
  6471. end
  6472. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6473. begin
  6474. TmpBool1 := True;
  6475. TmpBool2 := True;
  6476. case taicpu(hp1).opcode of
  6477. A_ADD:
  6478. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6479. A_SUB:
  6480. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6481. else
  6482. internalerror(2019050536);
  6483. end;
  6484. RemoveInstruction(hp1);
  6485. end
  6486. else
  6487. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6488. (((taicpu(hp1).opcode = A_ADD) and
  6489. (TmpRef.base = NR_NO)) or
  6490. (taicpu(hp1).opcode = A_INC) or
  6491. (taicpu(hp1).opcode = A_DEC)) then
  6492. begin
  6493. TmpBool1 := True;
  6494. TmpBool2 := True;
  6495. case taicpu(hp1).opcode of
  6496. A_ADD:
  6497. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6498. A_INC:
  6499. inc(TmpRef.offset);
  6500. A_DEC:
  6501. dec(TmpRef.offset);
  6502. else
  6503. internalerror(2019050535);
  6504. end;
  6505. RemoveInstruction(hp1);
  6506. end;
  6507. end;
  6508. if TmpBool2
  6509. {$ifndef x86_64}
  6510. or
  6511. ((current_settings.optimizecputype < cpu_Pentium2) and
  6512. (taicpu(p).oper[0]^.val <= 3) and
  6513. not(cs_opt_size in current_settings.optimizerswitches))
  6514. {$endif x86_64}
  6515. then
  6516. begin
  6517. if not(TmpBool2) and
  6518. (taicpu(p).oper[0]^.val=1) then
  6519. begin
  6520. taicpu(p).opcode := A_ADD;
  6521. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6522. end
  6523. else
  6524. begin
  6525. taicpu(p).opcode := A_LEA;
  6526. taicpu(p).loadref(0, TmpRef);
  6527. end;
  6528. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6529. Result := True;
  6530. end;
  6531. end
  6532. {$ifndef x86_64}
  6533. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6534. begin
  6535. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6536. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6537. (unlike shl, which is only Tairable in the U pipe) }
  6538. if taicpu(p).oper[0]^.val=1 then
  6539. begin
  6540. taicpu(p).opcode := A_ADD;
  6541. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6542. Result := True;
  6543. end
  6544. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6545. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6546. else if (taicpu(p).opsize = S_L) and
  6547. (taicpu(p).oper[0]^.val<= 3) then
  6548. begin
  6549. reference_reset(tmpref,2,[]);
  6550. TmpRef.index := taicpu(p).oper[1]^.reg;
  6551. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6552. taicpu(p).opcode := A_LEA;
  6553. taicpu(p).loadref(0, TmpRef);
  6554. Result := True;
  6555. end;
  6556. end
  6557. {$endif x86_64}
  6558. else if
  6559. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6560. (
  6561. (
  6562. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6563. SetAndTest(hp1, hp2)
  6564. {$ifdef x86_64}
  6565. ) or
  6566. (
  6567. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6568. GetNextInstruction(hp1, hp2) and
  6569. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6570. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6571. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6572. {$endif x86_64}
  6573. )
  6574. ) and
  6575. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6576. begin
  6577. { Change:
  6578. shl x, %reg1
  6579. mov -(1<<x), %reg2
  6580. and %reg2, %reg1
  6581. Or:
  6582. shl x, %reg1
  6583. and -(1<<x), %reg1
  6584. To just:
  6585. shl x, %reg1
  6586. Since the and operation only zeroes bits that are already zero from the shl operation
  6587. }
  6588. case taicpu(p).oper[0]^.val of
  6589. 8:
  6590. mask:=$FFFFFFFFFFFFFF00;
  6591. 16:
  6592. mask:=$FFFFFFFFFFFF0000;
  6593. 32:
  6594. mask:=$FFFFFFFF00000000;
  6595. 63:
  6596. { Constant pre-calculated to prevent overflow errors with Int64 }
  6597. mask:=$8000000000000000;
  6598. else
  6599. begin
  6600. if taicpu(p).oper[0]^.val >= 64 then
  6601. { Shouldn't happen realistically, since the register
  6602. is guaranteed to be set to zero at this point }
  6603. mask := 0
  6604. else
  6605. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6606. end;
  6607. end;
  6608. if taicpu(hp1).oper[0]^.val = mask then
  6609. begin
  6610. { Everything checks out, perform the optimisation, as long as
  6611. the FLAGS register isn't being used}
  6612. TransferUsedRegs(TmpUsedRegs);
  6613. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6614. {$ifdef x86_64}
  6615. if (hp1 <> hp2) then
  6616. begin
  6617. { "shl/mov/and" version }
  6618. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6619. { Don't do the optimisation if the FLAGS register is in use }
  6620. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6621. begin
  6622. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6623. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6624. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6625. begin
  6626. RemoveInstruction(hp1);
  6627. Result := True;
  6628. end;
  6629. { Only set Result to True if the 'mov' instruction was removed }
  6630. RemoveInstruction(hp2);
  6631. end;
  6632. end
  6633. else
  6634. {$endif x86_64}
  6635. begin
  6636. { "shl/and" version }
  6637. { Don't do the optimisation if the FLAGS register is in use }
  6638. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6639. begin
  6640. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6641. RemoveInstruction(hp1);
  6642. Result := True;
  6643. end;
  6644. end;
  6645. Exit;
  6646. end
  6647. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6648. begin
  6649. { Even if the mask doesn't allow for its removal, we might be
  6650. able to optimise the mask for the "shl/and" version, which
  6651. may permit other peephole optimisations }
  6652. {$ifdef DEBUG_AOPTCPU}
  6653. mask := taicpu(hp1).oper[0]^.val and mask;
  6654. if taicpu(hp1).oper[0]^.val <> mask then
  6655. begin
  6656. DebugMsg(
  6657. SPeepholeOptimization +
  6658. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6659. ' to $' + debug_tostr(mask) +
  6660. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6661. taicpu(hp1).oper[0]^.val := mask;
  6662. end;
  6663. {$else DEBUG_AOPTCPU}
  6664. { If debugging is off, just set the operand even if it's the same }
  6665. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6666. {$endif DEBUG_AOPTCPU}
  6667. end;
  6668. end;
  6669. {
  6670. change
  6671. shl/sal const,reg
  6672. <op> ...(...,reg,1),...
  6673. into
  6674. <op> ...(...,reg,1 shl const),...
  6675. if const in 1..3
  6676. }
  6677. if MatchOpType(taicpu(p), top_const, top_reg) and
  6678. (taicpu(p).oper[0]^.val in [1..3]) and
  6679. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6680. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6681. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6682. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6683. MatchOpType(taicpu(hp1),top_ref))
  6684. ) and
  6685. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6686. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6687. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6688. begin
  6689. TransferUsedRegs(TmpUsedRegs);
  6690. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6691. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6692. begin
  6693. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6694. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6695. RemoveCurrentP(p);
  6696. Result:=true;
  6697. exit;
  6698. end;
  6699. end;
  6700. if MatchOpType(taicpu(p), top_const, top_reg) and
  6701. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6702. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6703. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6704. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6705. begin
  6706. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6707. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6708. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6709. {$ifdef x86_64}
  6710. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6711. {$endif x86_64}
  6712. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6713. begin
  6714. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6715. taicpu(hp1).opcode:=A_MOV;
  6716. taicpu(hp1).oper[0]^.val:=0;
  6717. end
  6718. else
  6719. begin
  6720. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6721. taicpu(hp1).oper[0]^.val:=shiftval;
  6722. end;
  6723. RemoveCurrentP(p);
  6724. Result:=true;
  6725. exit;
  6726. end;
  6727. end;
  6728. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6729. begin
  6730. case shr_size of
  6731. S_B:
  6732. { No valid combinations }
  6733. Result := False;
  6734. S_W:
  6735. Result := (Shift >= 8) and (movz_size = S_BW);
  6736. S_L:
  6737. Result :=
  6738. (Shift >= 24) { Any opsize is valid for this shift } or
  6739. ((Shift >= 16) and (movz_size = S_WL));
  6740. {$ifdef x86_64}
  6741. S_Q:
  6742. Result :=
  6743. (Shift >= 56) { Any opsize is valid for this shift } or
  6744. ((Shift >= 48) and (movz_size = S_WL));
  6745. {$endif x86_64}
  6746. else
  6747. InternalError(2022081510);
  6748. end;
  6749. end;
  6750. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6751. var
  6752. hp1, hp2: tai;
  6753. Shift: TCGInt;
  6754. LimitSize: Topsize;
  6755. DoNotMerge: Boolean;
  6756. begin
  6757. Result := False;
  6758. { All these optimisations work on "shr const,%reg" }
  6759. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6760. Exit;
  6761. DoNotMerge := False;
  6762. Shift := taicpu(p).oper[0]^.val;
  6763. LimitSize := taicpu(p).opsize;
  6764. hp1 := p;
  6765. repeat
  6766. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6767. Exit;
  6768. case taicpu(hp1).opcode of
  6769. A_TEST, A_CMP, A_Jcc:
  6770. { Skip over conditional jumps and relevant comparisons }
  6771. Continue;
  6772. A_MOVZX:
  6773. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6774. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6775. begin
  6776. { Since the original register is being read as is, subsequent
  6777. SHRs must not be merged at this point }
  6778. DoNotMerge := True;
  6779. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6780. begin
  6781. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6782. begin
  6783. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6784. taicpu(hp1).opcode := A_MOV;
  6785. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6786. case taicpu(hp1).opsize of
  6787. S_BW:
  6788. taicpu(hp1).opsize := S_W;
  6789. S_BL, S_WL:
  6790. taicpu(hp1).opsize := S_L;
  6791. else
  6792. InternalError(2022081503);
  6793. end;
  6794. { p itself hasn't changed, so no need to set Result to True }
  6795. Include(OptsToCheck, aoc_ForceNewIteration);
  6796. { See if there's anything afterwards that can be
  6797. optimised, since the input register hasn't changed }
  6798. Continue;
  6799. end;
  6800. { NOTE: If the MOVZX instruction reads and writes the same
  6801. register, defer this to the post-peephole optimisation stage }
  6802. Exit;
  6803. end;
  6804. end;
  6805. A_SHL, A_SAL, A_SHR:
  6806. if (taicpu(hp1).opsize <= LimitSize) and
  6807. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6808. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6809. begin
  6810. { Make sure the sizes don't exceed the register size limit
  6811. (measured by the shift value falling below the limit) }
  6812. if taicpu(hp1).opsize < LimitSize then
  6813. LimitSize := taicpu(hp1).opsize;
  6814. if taicpu(hp1).opcode = A_SHR then
  6815. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6816. else
  6817. begin
  6818. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6819. DoNotMerge := True;
  6820. end;
  6821. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6822. Exit;
  6823. { Since we've established that the combined shift is within
  6824. limits, we can actually combine the adjacent SHR
  6825. instructions even if they're different sizes }
  6826. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6827. begin
  6828. hp2 := tai(hp1.Previous);
  6829. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6830. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6831. RemoveInstruction(hp1);
  6832. hp1 := hp2;
  6833. { Though p has changed, only the constant has, and its
  6834. effects can still be detected on the next iteration of
  6835. the repeat..until loop }
  6836. Include(OptsToCheck, aoc_ForceNewIteration);
  6837. end;
  6838. { Move onto the next instruction }
  6839. Continue;
  6840. end;
  6841. else
  6842. ;
  6843. end;
  6844. Break;
  6845. until False;
  6846. end;
  6847. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6848. var
  6849. CurrentRef: TReference;
  6850. FullReg: TRegister;
  6851. hp1, hp2: tai;
  6852. begin
  6853. Result := False;
  6854. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6855. Exit;
  6856. { We assume you've checked if the operand is actually a reference by
  6857. this point. If it isn't, you'll most likely get an access violation }
  6858. CurrentRef := first_mov.oper[1]^.ref^;
  6859. { Memory must be aligned }
  6860. if (CurrentRef.offset mod 4) <> 0 then
  6861. Exit;
  6862. Inc(CurrentRef.offset);
  6863. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6864. if MatchOperand(second_mov.oper[0]^, 0) and
  6865. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6866. GetNextInstruction(second_mov, hp1) and
  6867. (hp1.typ = ait_instruction) and
  6868. (taicpu(hp1).opcode = A_MOV) and
  6869. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6870. (taicpu(hp1).oper[0]^.val = 0) then
  6871. begin
  6872. Inc(CurrentRef.offset);
  6873. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6874. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6875. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6876. begin
  6877. case taicpu(hp1).opsize of
  6878. S_B:
  6879. if GetNextInstruction(hp1, hp2) and
  6880. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6881. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6882. (taicpu(hp2).oper[0]^.val = 0) then
  6883. begin
  6884. Inc(CurrentRef.offset);
  6885. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6886. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6887. (taicpu(hp2).opsize = S_B) then
  6888. begin
  6889. RemoveInstruction(hp1);
  6890. RemoveInstruction(hp2);
  6891. first_mov.opsize := S_L;
  6892. if first_mov.oper[0]^.typ = top_reg then
  6893. begin
  6894. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6895. { Reuse second_mov as a MOVZX instruction }
  6896. second_mov.opcode := A_MOVZX;
  6897. second_mov.opsize := S_BL;
  6898. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6899. second_mov.loadreg(1, FullReg);
  6900. first_mov.oper[0]^.reg := FullReg;
  6901. asml.Remove(second_mov);
  6902. asml.InsertBefore(second_mov, first_mov);
  6903. end
  6904. else
  6905. { It's a value }
  6906. begin
  6907. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6908. RemoveInstruction(second_mov);
  6909. end;
  6910. Result := True;
  6911. Exit;
  6912. end;
  6913. end;
  6914. S_W:
  6915. begin
  6916. RemoveInstruction(hp1);
  6917. first_mov.opsize := S_L;
  6918. if first_mov.oper[0]^.typ = top_reg then
  6919. begin
  6920. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6921. { Reuse second_mov as a MOVZX instruction }
  6922. second_mov.opcode := A_MOVZX;
  6923. second_mov.opsize := S_BL;
  6924. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6925. second_mov.loadreg(1, FullReg);
  6926. first_mov.oper[0]^.reg := FullReg;
  6927. asml.Remove(second_mov);
  6928. asml.InsertBefore(second_mov, first_mov);
  6929. end
  6930. else
  6931. { It's a value }
  6932. begin
  6933. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6934. RemoveInstruction(second_mov);
  6935. end;
  6936. Result := True;
  6937. Exit;
  6938. end;
  6939. else
  6940. ;
  6941. end;
  6942. end;
  6943. end;
  6944. end;
  6945. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6946. { returns true if a "continue" should be done after this optimization }
  6947. var
  6948. hp1, hp2, hp3: tai;
  6949. begin
  6950. Result := false;
  6951. hp3 := nil;
  6952. if MatchOpType(taicpu(p),top_ref) and
  6953. GetNextInstruction(p, hp1) and
  6954. (hp1.typ = ait_instruction) and
  6955. (((taicpu(hp1).opcode = A_FLD) and
  6956. (taicpu(p).opcode = A_FSTP)) or
  6957. ((taicpu(p).opcode = A_FISTP) and
  6958. (taicpu(hp1).opcode = A_FILD))) and
  6959. MatchOpType(taicpu(hp1),top_ref) and
  6960. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6961. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6962. begin
  6963. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6964. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6965. GetNextInstruction(hp1, hp2) and
  6966. (((hp2.typ = ait_instruction) and
  6967. IsExitCode(hp2) and
  6968. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6969. not(assigned(current_procinfo.procdef.funcretsym) and
  6970. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6971. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6972. { fstp <temp>
  6973. fld <temp>
  6974. <dealloc> <temp>
  6975. }
  6976. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6977. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6978. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6979. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6980. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6981. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6982. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6983. )
  6984. )
  6985. ) then
  6986. begin
  6987. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6988. RemoveInstruction(hp1);
  6989. RemoveCurrentP(p, hp2);
  6990. { first case: exit code }
  6991. if hp2.typ = ait_instruction then
  6992. RemoveLastDeallocForFuncRes(p);
  6993. Result := true;
  6994. end
  6995. else
  6996. { we can do this only in fast math mode as fstp is rounding ...
  6997. ... still disabled as it breaks the compiler and/or rtl }
  6998. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6999. { ... or if another fstp equal to the first one follows }
  7000. GetNextInstruction(hp1,hp2) and
  7001. (hp2.typ = ait_instruction) and
  7002. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7003. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7004. begin
  7005. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7006. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7007. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7008. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7009. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7010. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7011. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7012. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7013. ) then
  7014. begin
  7015. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7016. RemoveCurrentP(p,hp2);
  7017. RemoveInstruction(hp1);
  7018. Result := true;
  7019. end
  7020. else if { fst can't store an extended/comp value }
  7021. (taicpu(p).opsize <> S_FX) and
  7022. (taicpu(p).opsize <> S_IQ) then
  7023. begin
  7024. if (taicpu(p).opcode = A_FSTP) then
  7025. taicpu(p).opcode := A_FST
  7026. else
  7027. taicpu(p).opcode := A_FIST;
  7028. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7029. RemoveInstruction(hp1);
  7030. Result := true;
  7031. end;
  7032. end;
  7033. end;
  7034. end;
  7035. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7036. var
  7037. hp1, hp2, hp3: tai;
  7038. begin
  7039. result:=false;
  7040. if MatchOpType(taicpu(p),top_reg) and
  7041. GetNextInstruction(p, hp1) and
  7042. (hp1.typ = Ait_Instruction) and
  7043. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7044. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7045. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7046. { change to
  7047. fld reg fxxx reg,st
  7048. fxxxp st, st1 (hp1)
  7049. Remark: non commutative operations must be reversed!
  7050. }
  7051. begin
  7052. case taicpu(hp1).opcode Of
  7053. A_FMULP,A_FADDP,
  7054. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7055. begin
  7056. case taicpu(hp1).opcode Of
  7057. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7058. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7059. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7060. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7061. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7062. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7063. else
  7064. internalerror(2019050534);
  7065. end;
  7066. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7067. taicpu(hp1).oper[1]^.reg := NR_ST;
  7068. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7069. RemoveCurrentP(p, hp1);
  7070. Result:=true;
  7071. exit;
  7072. end;
  7073. else
  7074. ;
  7075. end;
  7076. end
  7077. else
  7078. if MatchOpType(taicpu(p),top_ref) and
  7079. GetNextInstruction(p, hp2) and
  7080. (hp2.typ = Ait_Instruction) and
  7081. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7082. (taicpu(p).opsize in [S_FS, S_FL]) and
  7083. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7084. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7085. if GetLastInstruction(p, hp1) and
  7086. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7087. MatchOpType(taicpu(hp1),top_ref) and
  7088. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7089. if ((taicpu(hp2).opcode = A_FMULP) or
  7090. (taicpu(hp2).opcode = A_FADDP)) then
  7091. { change to
  7092. fld/fst mem1 (hp1) fld/fst mem1
  7093. fld mem1 (p) fadd/
  7094. faddp/ fmul st, st
  7095. fmulp st, st1 (hp2) }
  7096. begin
  7097. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7098. RemoveCurrentP(p, hp1);
  7099. if (taicpu(hp2).opcode = A_FADDP) then
  7100. taicpu(hp2).opcode := A_FADD
  7101. else
  7102. taicpu(hp2).opcode := A_FMUL;
  7103. taicpu(hp2).oper[1]^.reg := NR_ST;
  7104. end
  7105. else
  7106. { change to
  7107. fld/fst mem1 (hp1) fld/fst mem1
  7108. fld mem1 (p) fld st
  7109. }
  7110. begin
  7111. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7112. taicpu(p).changeopsize(S_FL);
  7113. taicpu(p).loadreg(0,NR_ST);
  7114. end
  7115. else
  7116. begin
  7117. case taicpu(hp2).opcode Of
  7118. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7119. { change to
  7120. fld/fst mem1 (hp1) fld/fst mem1
  7121. fld mem2 (p) fxxx mem2
  7122. fxxxp st, st1 (hp2) }
  7123. begin
  7124. case taicpu(hp2).opcode Of
  7125. A_FADDP: taicpu(p).opcode := A_FADD;
  7126. A_FMULP: taicpu(p).opcode := A_FMUL;
  7127. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7128. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7129. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7130. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7131. else
  7132. internalerror(2019050533);
  7133. end;
  7134. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7135. RemoveInstruction(hp2);
  7136. end
  7137. else
  7138. ;
  7139. end
  7140. end
  7141. end;
  7142. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7143. begin
  7144. Result := condition_in(cond1, cond2) or
  7145. { Not strictly subsets due to the actual flags checked, but because we're
  7146. comparing integers, E is a subset of AE and GE and their aliases }
  7147. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7148. end;
  7149. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7150. var
  7151. v: TCGInt;
  7152. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7153. FirstMatch, TempBool: Boolean;
  7154. NewReg: TRegister;
  7155. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7156. begin
  7157. Result:=false;
  7158. { All these optimisations need a next instruction }
  7159. if not GetNextInstruction(p, hp1) then
  7160. Exit;
  7161. true_hp1 := hp1;
  7162. { Search for:
  7163. cmp ###,###
  7164. j(c1) @lbl1
  7165. ...
  7166. @lbl:
  7167. cmp ###,### (same comparison as above)
  7168. j(c2) @lbl2
  7169. If c1 is a subset of c2, change to:
  7170. cmp ###,###
  7171. j(c1) @lbl2
  7172. (@lbl1 may become a dead label as a result)
  7173. }
  7174. { Also handle cases where there are multiple jumps in a row }
  7175. p_jump := hp1;
  7176. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7177. begin
  7178. Prefetch(p_jump.Next);
  7179. if IsJumpToLabel(taicpu(p_jump)) then
  7180. begin
  7181. { Do jump optimisations first in case the condition becomes
  7182. unnecessary }
  7183. TempBool := True;
  7184. if DoJumpOptimizations(p_jump, TempBool) or
  7185. not TempBool then
  7186. begin
  7187. if Assigned(p_jump) then
  7188. begin
  7189. { CollapseZeroDistJump will be set to the label or an align
  7190. before it after the jump if it optimises, whether or not
  7191. the label is live or dead }
  7192. if (p_jump.typ = ait_align) or
  7193. (
  7194. (p_jump.typ = ait_label) and
  7195. not (tai_label(p_jump).labsym.is_used)
  7196. ) then
  7197. GetNextInstruction(p_jump, p_jump);
  7198. end;
  7199. TransferUsedRegs(TmpUsedRegs);
  7200. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7201. if not Assigned(p_jump) or
  7202. (
  7203. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7204. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7205. ) then
  7206. begin
  7207. { No more conditional jumps; conditional statement is no longer required }
  7208. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7209. RemoveCurrentP(p);
  7210. Result := True;
  7211. Exit;
  7212. end;
  7213. hp1 := p_jump;
  7214. Include(OptsToCheck, aoc_ForceNewIteration);
  7215. Continue;
  7216. end;
  7217. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7218. if GetNextInstruction(p_jump, hp2) and
  7219. (
  7220. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7221. not TempBool
  7222. ) then
  7223. begin
  7224. hp1 := p_jump;
  7225. Include(OptsToCheck, aoc_ForceNewIteration);
  7226. Continue;
  7227. end;
  7228. p_label := nil;
  7229. if Assigned(JumpLabel) then
  7230. p_label := getlabelwithsym(JumpLabel);
  7231. if Assigned(p_label) and
  7232. GetNextInstruction(p_label, p_dist) and
  7233. MatchInstruction(p_dist, A_CMP, []) and
  7234. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7235. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7236. GetNextInstruction(p_dist, hp1_dist) and
  7237. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7238. begin
  7239. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7240. if JumpLabel = JumpLabel_dist then
  7241. { This is an infinite loop }
  7242. Exit;
  7243. { Best optimisation when the first condition is a subset (or equal) of the second }
  7244. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7245. begin
  7246. { Any registers used here will already be allocated }
  7247. if Assigned(JumpLabel) then
  7248. JumpLabel.DecRefs;
  7249. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7250. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7251. Include(OptsToCheck, aoc_ForceNewIteration);
  7252. { Don't exit yet. Since p and p_jump haven't actually been
  7253. removed, we can check for more on this iteration }
  7254. end
  7255. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7256. GetNextInstruction(hp1_dist, hp1_label) and
  7257. (hp1_label.typ = ait_label) then
  7258. begin
  7259. JumpLabel_far := tai_label(hp1_label).labsym;
  7260. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7261. { This is an infinite loop }
  7262. Exit;
  7263. if Assigned(JumpLabel_far) then
  7264. begin
  7265. { In this situation, if the first jump branches, the second one will never,
  7266. branch so change the destination label to after the second jump }
  7267. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7268. if Assigned(JumpLabel) then
  7269. JumpLabel.DecRefs;
  7270. JumpLabel_far.IncRefs;
  7271. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7272. Result := True;
  7273. { Don't exit yet. Since p and p_jump haven't actually been
  7274. removed, we can check for more on this iteration }
  7275. Continue;
  7276. end;
  7277. end;
  7278. end;
  7279. end;
  7280. { Search for:
  7281. cmp ###,###
  7282. j(c1) @lbl1
  7283. cmp ###,### (same as first)
  7284. Remove second cmp
  7285. }
  7286. if GetNextInstruction(p_jump, hp2) and
  7287. (
  7288. (
  7289. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7290. (
  7291. (
  7292. MatchOpType(taicpu(p), top_const, top_reg) and
  7293. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7294. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7295. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7296. ) or (
  7297. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7298. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7299. )
  7300. )
  7301. ) or (
  7302. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7303. MatchOperand(taicpu(p).oper[0]^, 0) and
  7304. (taicpu(p).oper[1]^.typ = top_reg) and
  7305. MatchInstruction(hp2, A_TEST, []) and
  7306. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7307. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7308. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7309. )
  7310. ) then
  7311. begin
  7312. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7313. TransferUsedRegs(TmpUsedRegs);
  7314. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7315. RemoveInstruction(hp2);
  7316. Result := True;
  7317. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7318. end
  7319. else
  7320. begin
  7321. { hp2 is the next instruction, so save time and just set p_jump
  7322. to it instead of calling GetNextInstruction below }
  7323. p_jump := hp2;
  7324. Continue;
  7325. end;
  7326. GetNextInstruction(p_jump, p_jump);
  7327. end;
  7328. if (
  7329. { Don't call GetNextInstruction again if we already have it }
  7330. (true_hp1 = p_jump) or
  7331. GetNextInstruction(p, hp1)
  7332. ) and
  7333. MatchInstruction(hp1, A_Jcc, []) and
  7334. IsJumpToLabel(taicpu(hp1)) and
  7335. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7336. GetNextInstruction(hp1, hp2) then
  7337. begin
  7338. {
  7339. cmp x, y (or "cmp y, x")
  7340. je @lbl
  7341. mov x, y
  7342. @lbl:
  7343. (x and y can be constants, registers or references)
  7344. Change to:
  7345. mov x, y (x and y will always be equal in the end)
  7346. @lbl: (may beceome a dead label)
  7347. Also:
  7348. cmp x, y (or "cmp y, x")
  7349. jne @lbl
  7350. mov x, y
  7351. @lbl:
  7352. (x and y can be constants, registers or references)
  7353. Change to:
  7354. Absolutely nothing! (Except @lbl if it's still live)
  7355. }
  7356. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7357. (
  7358. (
  7359. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7360. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7361. ) or (
  7362. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7363. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7364. )
  7365. ) and
  7366. GetNextInstruction(hp2, hp1_label) and
  7367. (hp1_label.typ = ait_label) and
  7368. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7369. begin
  7370. tai_label(hp1_label).labsym.DecRefs;
  7371. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7372. begin
  7373. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7374. RemoveInstruction(hp2);
  7375. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7376. end
  7377. else
  7378. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7379. RemoveInstruction(hp1);
  7380. RemoveCurrentp(p, hp2);
  7381. Result := True;
  7382. Exit;
  7383. end;
  7384. {
  7385. Try to optimise the following:
  7386. cmp $x,### ($x and $y can be registers or constants)
  7387. je @lbl1 (only reference)
  7388. cmp $y,### (### are identical)
  7389. @Lbl:
  7390. sete %reg1
  7391. Change to:
  7392. cmp $x,###
  7393. sete %reg2 (allocate new %reg2)
  7394. cmp $y,###
  7395. sete %reg1
  7396. orb %reg2,%reg1
  7397. (dealloc %reg2)
  7398. This adds an instruction (so don't perform under -Os), but it removes
  7399. a conditional branch.
  7400. }
  7401. if not (cs_opt_size in current_settings.optimizerswitches) and
  7402. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7403. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7404. { The first operand of CMP instructions can only be a register or
  7405. immediate anyway, so no need to check }
  7406. GetNextInstruction(hp2, p_label) and
  7407. (p_label.typ = ait_label) and
  7408. (tai_label(p_label).labsym.getrefs = 1) and
  7409. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7410. GetNextInstruction(p_label, p_dist) and
  7411. MatchInstruction(p_dist, A_SETcc, []) and
  7412. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7413. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7414. begin
  7415. TransferUsedRegs(TmpUsedRegs);
  7416. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7417. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7418. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7419. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7420. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7421. { Get the instruction after the SETcc instruction so we can
  7422. allocate a new register over the entire range }
  7423. GetNextInstruction(p_dist, hp1_dist) then
  7424. begin
  7425. { Register can appear in p if it's not used afterwards, so only
  7426. allocate between hp1 and hp1_dist }
  7427. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7428. if NewReg <> NR_NO then
  7429. begin
  7430. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7431. { Change the jump instruction into a SETcc instruction }
  7432. taicpu(hp1).opcode := A_SETcc;
  7433. taicpu(hp1).opsize := S_B;
  7434. taicpu(hp1).loadreg(0, NewReg);
  7435. { This is now a dead label }
  7436. tai_label(p_label).labsym.decrefs;
  7437. { Prefer adding before the next instruction so the FLAGS
  7438. register is deallicated first }
  7439. AsmL.InsertBefore(
  7440. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7441. hp1_dist
  7442. );
  7443. Result := True;
  7444. { Don't exit yet, as p wasn't changed and hp1, while
  7445. modified, is still intact and might be optimised by the
  7446. SETcc optimisation below }
  7447. end;
  7448. end;
  7449. end;
  7450. end;
  7451. if (taicpu(p).oper[0]^.typ = top_const) and
  7452. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7453. begin
  7454. if (taicpu(p).oper[0]^.val = 0) and
  7455. (taicpu(p).oper[1]^.typ = top_reg) then
  7456. begin
  7457. hp2 := p;
  7458. FirstMatch := True;
  7459. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7460. anything meaningful once it's converted to "test %reg,%reg";
  7461. additionally, some jumps will always (or never) branch, so
  7462. evaluate every jump immediately following the
  7463. comparison, optimising the conditions if possible.
  7464. Similarly with SETcc... those that are always set to 0 or 1
  7465. are changed to MOV instructions }
  7466. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7467. (
  7468. GetNextInstruction(hp2, hp1) and
  7469. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7470. ) do
  7471. begin
  7472. Prefetch(hp1.Next);
  7473. FirstMatch := False;
  7474. case taicpu(hp1).condition of
  7475. C_B, C_C, C_NAE, C_O:
  7476. { For B/NAE:
  7477. Will never branch since an unsigned integer can never be below zero
  7478. For C/O:
  7479. Result cannot overflow because 0 is being subtracted
  7480. }
  7481. begin
  7482. if taicpu(hp1).opcode = A_Jcc then
  7483. begin
  7484. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7485. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7486. RemoveInstruction(hp1);
  7487. { Since hp1 was deleted, hp2 must not be updated }
  7488. Continue;
  7489. end
  7490. else
  7491. begin
  7492. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7493. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7494. taicpu(hp1).opcode := A_MOV;
  7495. taicpu(hp1).ops := 2;
  7496. taicpu(hp1).condition := C_None;
  7497. taicpu(hp1).opsize := S_B;
  7498. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7499. taicpu(hp1).loadconst(0, 0);
  7500. end;
  7501. end;
  7502. C_BE, C_NA:
  7503. begin
  7504. { Will only branch if equal to zero }
  7505. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7506. taicpu(hp1).condition := C_E;
  7507. end;
  7508. C_A, C_NBE:
  7509. begin
  7510. { Will only branch if not equal to zero }
  7511. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7512. taicpu(hp1).condition := C_NE;
  7513. end;
  7514. C_AE, C_NB, C_NC, C_NO:
  7515. begin
  7516. { Will always branch }
  7517. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7518. if taicpu(hp1).opcode = A_Jcc then
  7519. begin
  7520. MakeUnconditional(taicpu(hp1));
  7521. { Any jumps/set that follow will now be dead code }
  7522. RemoveDeadCodeAfterJump(taicpu(hp1));
  7523. Break;
  7524. end
  7525. else
  7526. begin
  7527. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7528. taicpu(hp1).opcode := A_MOV;
  7529. taicpu(hp1).ops := 2;
  7530. taicpu(hp1).condition := C_None;
  7531. taicpu(hp1).opsize := S_B;
  7532. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7533. taicpu(hp1).loadconst(0, 1);
  7534. end;
  7535. end;
  7536. C_None:
  7537. InternalError(2020012201);
  7538. C_P, C_PE, C_NP, C_PO:
  7539. { We can't handle parity checks and they should never be generated
  7540. after a general-purpose CMP (it's used in some floating-point
  7541. comparisons that don't use CMP) }
  7542. InternalError(2020012202);
  7543. else
  7544. { Zero/Equality, Sign, their complements and all of the
  7545. signed comparisons do not need to be converted };
  7546. end;
  7547. hp2 := hp1;
  7548. end;
  7549. { Convert the instruction to a TEST }
  7550. taicpu(p).opcode := A_TEST;
  7551. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7552. Result := True;
  7553. Exit;
  7554. end
  7555. else
  7556. begin
  7557. TransferUsedRegs(TmpUsedRegs);
  7558. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7559. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7560. begin
  7561. if (taicpu(p).oper[0]^.val = 1) and
  7562. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7563. begin
  7564. { Convert; To:
  7565. cmp $1,r/m cmp $0,r/m
  7566. jl @lbl jle @lbl
  7567. (Also do inverted conditions)
  7568. }
  7569. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7570. taicpu(p).oper[0]^.val := 0;
  7571. if taicpu(hp1).condition in [C_L, C_NGE] then
  7572. taicpu(hp1).condition := C_LE
  7573. else
  7574. taicpu(hp1).condition := C_NLE;
  7575. { If the instruction is now "cmp $0,%reg", convert it to a
  7576. TEST (and effectively do the work of the "cmp $0,%reg" in
  7577. the block above)
  7578. }
  7579. if (taicpu(p).oper[1]^.typ = top_reg) then
  7580. begin
  7581. taicpu(p).opcode := A_TEST;
  7582. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7583. end;
  7584. Result := True;
  7585. Exit;
  7586. end
  7587. else if (taicpu(p).oper[1]^.typ = top_reg)
  7588. {$ifdef x86_64}
  7589. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7590. {$endif x86_64}
  7591. then
  7592. begin
  7593. { cmp register,$8000 neg register
  7594. je target --> jo target
  7595. .... only if register is deallocated before jump.}
  7596. case Taicpu(p).opsize of
  7597. S_B: v:=$80;
  7598. S_W: v:=$8000;
  7599. S_L: v:=qword($80000000);
  7600. else
  7601. internalerror(2013112905);
  7602. end;
  7603. if (taicpu(p).oper[0]^.val=v) and
  7604. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7605. begin
  7606. TransferUsedRegs(TmpUsedRegs);
  7607. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7608. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7609. begin
  7610. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7611. Taicpu(p).opcode:=A_NEG;
  7612. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7613. Taicpu(p).clearop(1);
  7614. Taicpu(p).ops:=1;
  7615. if Taicpu(hp1).condition=C_E then
  7616. Taicpu(hp1).condition:=C_O
  7617. else
  7618. Taicpu(hp1).condition:=C_NO;
  7619. Result:=true;
  7620. exit;
  7621. end;
  7622. end;
  7623. end;
  7624. end;
  7625. end;
  7626. end;
  7627. if TrySwapMovCmp(p, hp1) then
  7628. begin
  7629. Result := True;
  7630. Exit;
  7631. end;
  7632. end;
  7633. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7634. var
  7635. hp1: tai;
  7636. begin
  7637. {
  7638. remove the second (v)pxor from
  7639. pxor reg,reg
  7640. ...
  7641. pxor reg,reg
  7642. }
  7643. Result:=false;
  7644. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7645. MatchOpType(taicpu(p),top_reg,top_reg) and
  7646. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7647. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7648. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7649. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7650. begin
  7651. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7652. RemoveInstruction(hp1);
  7653. Result:=true;
  7654. Exit;
  7655. end
  7656. {
  7657. replace
  7658. pxor reg1,reg1
  7659. movapd/s reg1,reg2
  7660. dealloc reg1
  7661. by
  7662. pxor reg2,reg2
  7663. }
  7664. else if GetNextInstruction(p,hp1) and
  7665. { we mix single and double opperations here because we assume that the compiler
  7666. generates vmovapd only after double operations and vmovaps only after single operations }
  7667. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7668. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7669. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7670. (taicpu(p).oper[0]^.typ=top_reg) then
  7671. begin
  7672. TransferUsedRegs(TmpUsedRegs);
  7673. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7674. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7675. begin
  7676. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7677. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7678. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7679. RemoveInstruction(hp1);
  7680. result:=true;
  7681. end;
  7682. end;
  7683. end;
  7684. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7685. var
  7686. hp1: tai;
  7687. begin
  7688. {
  7689. remove the second (v)pxor from
  7690. (v)pxor reg,reg
  7691. ...
  7692. (v)pxor reg,reg
  7693. }
  7694. Result:=false;
  7695. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7696. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7697. begin
  7698. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7699. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7700. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7701. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7702. begin
  7703. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7704. RemoveInstruction(hp1);
  7705. Result:=true;
  7706. Exit;
  7707. end;
  7708. {$ifdef x86_64}
  7709. {
  7710. replace
  7711. vpxor reg1,reg1,reg1
  7712. vmov reg,mem
  7713. by
  7714. movq $0,mem
  7715. }
  7716. if GetNextInstruction(p,hp1) and
  7717. MatchInstruction(hp1,A_VMOVSD,[]) and
  7718. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7719. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7720. begin
  7721. TransferUsedRegs(TmpUsedRegs);
  7722. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7723. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7724. begin
  7725. taicpu(hp1).loadconst(0,0);
  7726. taicpu(hp1).opcode:=A_MOV;
  7727. taicpu(hp1).opsize:=S_Q;
  7728. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7729. RemoveCurrentP(p);
  7730. result:=true;
  7731. Exit;
  7732. end;
  7733. end;
  7734. {$endif x86_64}
  7735. end
  7736. {
  7737. replace
  7738. vpxor reg1,reg1,reg2
  7739. by
  7740. vpxor reg2,reg2,reg2
  7741. to avoid unncessary data dependencies
  7742. }
  7743. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7744. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7745. begin
  7746. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7747. { avoid unncessary data dependency }
  7748. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7749. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7750. result:=true;
  7751. exit;
  7752. end;
  7753. Result:=OptPass1VOP(p);
  7754. end;
  7755. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7756. var
  7757. hp1 : tai;
  7758. begin
  7759. result:=false;
  7760. { replace
  7761. IMul const,%mreg1,%mreg2
  7762. Mov %reg2,%mreg3
  7763. dealloc %mreg3
  7764. by
  7765. Imul const,%mreg1,%mreg23
  7766. }
  7767. if (taicpu(p).ops=3) and
  7768. GetNextInstruction(p,hp1) and
  7769. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7770. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7771. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7772. begin
  7773. TransferUsedRegs(TmpUsedRegs);
  7774. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7775. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7776. begin
  7777. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7778. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7779. RemoveInstruction(hp1);
  7780. result:=true;
  7781. end;
  7782. end;
  7783. end;
  7784. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7785. var
  7786. hp1 : tai;
  7787. begin
  7788. result:=false;
  7789. { replace
  7790. IMul %reg0,%reg1,%reg2
  7791. Mov %reg2,%reg3
  7792. dealloc %reg2
  7793. by
  7794. Imul %reg0,%reg1,%reg3
  7795. }
  7796. if GetNextInstruction(p,hp1) and
  7797. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7798. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7799. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7800. begin
  7801. TransferUsedRegs(TmpUsedRegs);
  7802. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7803. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7804. begin
  7805. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7806. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7807. RemoveInstruction(hp1);
  7808. result:=true;
  7809. end;
  7810. end;
  7811. end;
  7812. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7813. var
  7814. hp1: tai;
  7815. begin
  7816. Result:=false;
  7817. { get rid of
  7818. (v)cvtss2sd reg0,<reg1,>reg2
  7819. (v)cvtss2sd reg2,<reg2,>reg0
  7820. }
  7821. if GetNextInstruction(p,hp1) and
  7822. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7823. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7824. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7825. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7826. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7827. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7828. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7829. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7830. )
  7831. ) then
  7832. begin
  7833. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7834. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7835. begin
  7836. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7837. RemoveCurrentP(p);
  7838. RemoveInstruction(hp1);
  7839. end
  7840. else
  7841. begin
  7842. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7843. if taicpu(hp1).opcode=A_CVTSD2SS then
  7844. begin
  7845. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7846. taicpu(p).opcode:=A_MOVAPS;
  7847. end
  7848. else
  7849. begin
  7850. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7851. taicpu(p).opcode:=A_VMOVAPS;
  7852. end;
  7853. taicpu(p).ops:=2;
  7854. RemoveInstruction(hp1);
  7855. end;
  7856. Result:=true;
  7857. Exit;
  7858. end;
  7859. end;
  7860. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7861. var
  7862. hp1, hp2, hp3, hp4, hp5: tai;
  7863. ThisReg: TRegister;
  7864. begin
  7865. Result := False;
  7866. if not GetNextInstruction(p,hp1) then
  7867. Exit;
  7868. {
  7869. convert
  7870. j<c> .L1
  7871. mov 1,reg
  7872. jmp .L2
  7873. .L1
  7874. mov 0,reg
  7875. .L2
  7876. into
  7877. mov 0,reg
  7878. set<not(c)> reg
  7879. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7880. would destroy the flag contents
  7881. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7882. executed at the same time as a previous comparison.
  7883. set<not(c)> reg
  7884. movzx reg, reg
  7885. }
  7886. if MatchInstruction(hp1,A_MOV,[]) and
  7887. (taicpu(hp1).oper[0]^.typ = top_const) and
  7888. (
  7889. (
  7890. (taicpu(hp1).oper[1]^.typ = top_reg)
  7891. {$ifdef i386}
  7892. { Under i386, ESI, EDI, EBP and ESP
  7893. don't have an 8-bit representation }
  7894. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7895. {$endif i386}
  7896. ) or (
  7897. {$ifdef i386}
  7898. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7899. {$endif i386}
  7900. (taicpu(hp1).opsize = S_B)
  7901. )
  7902. ) and
  7903. GetNextInstruction(hp1,hp2) and
  7904. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7905. GetNextInstruction(hp2,hp3) and
  7906. (hp3.typ=ait_label) and
  7907. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7908. GetNextInstruction(hp3,hp4) and
  7909. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7910. (taicpu(hp4).oper[0]^.typ = top_const) and
  7911. (
  7912. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7913. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7914. ) and
  7915. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7916. GetNextInstruction(hp4,hp5) and
  7917. (hp5.typ=ait_label) and
  7918. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7919. begin
  7920. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7921. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7922. tai_label(hp3).labsym.DecRefs;
  7923. { If this isn't the only reference to the middle label, we can
  7924. still make a saving - only that the first jump and everything
  7925. that follows will remain. }
  7926. if (tai_label(hp3).labsym.getrefs = 0) then
  7927. begin
  7928. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7929. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7930. else
  7931. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7932. { remove jump, first label and second MOV (also catching any aligns) }
  7933. repeat
  7934. if not GetNextInstruction(hp2, hp3) then
  7935. InternalError(2021040810);
  7936. RemoveInstruction(hp2);
  7937. hp2 := hp3;
  7938. until hp2 = hp5;
  7939. { Don't decrement reference count before the removal loop
  7940. above, otherwise GetNextInstruction won't stop on the
  7941. the label }
  7942. tai_label(hp5).labsym.DecRefs;
  7943. end
  7944. else
  7945. begin
  7946. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7947. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7948. else
  7949. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7950. end;
  7951. taicpu(p).opcode:=A_SETcc;
  7952. taicpu(p).opsize:=S_B;
  7953. taicpu(p).is_jmp:=False;
  7954. if taicpu(hp1).opsize=S_B then
  7955. begin
  7956. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7957. if taicpu(hp1).oper[1]^.typ = top_reg then
  7958. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7959. RemoveInstruction(hp1);
  7960. end
  7961. else
  7962. begin
  7963. { Will be a register because the size can't be S_B otherwise }
  7964. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7965. taicpu(p).loadreg(0, ThisReg);
  7966. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7967. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7968. begin
  7969. case taicpu(hp1).opsize of
  7970. S_W:
  7971. taicpu(hp1).opsize := S_BW;
  7972. S_L:
  7973. taicpu(hp1).opsize := S_BL;
  7974. {$ifdef x86_64}
  7975. S_Q:
  7976. begin
  7977. taicpu(hp1).opsize := S_BL;
  7978. { Change the destination register to 32-bit }
  7979. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7980. end;
  7981. {$endif x86_64}
  7982. else
  7983. InternalError(2021040820);
  7984. end;
  7985. taicpu(hp1).opcode := A_MOVZX;
  7986. taicpu(hp1).loadreg(0, ThisReg);
  7987. end
  7988. else
  7989. begin
  7990. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7991. { hp1 is already a MOV instruction with the correct register }
  7992. taicpu(hp1).loadconst(0, 0);
  7993. { Inserting it right before p will guarantee that the flags are also tracked }
  7994. asml.Remove(hp1);
  7995. asml.InsertBefore(hp1, p);
  7996. end;
  7997. end;
  7998. Result:=true;
  7999. exit;
  8000. end
  8001. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8002. Result := TryJccStcClcOpt(p, hp1)
  8003. else if (hp1.typ = ait_label) then
  8004. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8005. end;
  8006. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8007. var
  8008. hp1, hp2, hp3: tai;
  8009. SourceRef, TargetRef: TReference;
  8010. CurrentReg: TRegister;
  8011. begin
  8012. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8013. if not UseAVX then
  8014. InternalError(2021100501);
  8015. Result := False;
  8016. { Look for the following to simplify:
  8017. vmovdqa/u x(mem1), %xmmreg
  8018. vmovdqa/u %xmmreg, y(mem2)
  8019. vmovdqa/u x+16(mem1), %xmmreg
  8020. vmovdqa/u %xmmreg, y+16(mem2)
  8021. Change to:
  8022. vmovdqa/u x(mem1), %ymmreg
  8023. vmovdqa/u %ymmreg, y(mem2)
  8024. vpxor %ymmreg, %ymmreg, %ymmreg
  8025. ( The VPXOR instruction is to zero the upper half, thus removing the
  8026. need to call the potentially expensive VZEROUPPER instruction. Other
  8027. peephole optimisations can remove VPXOR if it's unnecessary )
  8028. }
  8029. TransferUsedRegs(TmpUsedRegs);
  8030. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8031. { NOTE: In the optimisations below, if the references dictate that an
  8032. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8033. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8034. if (taicpu(p).opsize = S_XMM) and
  8035. MatchOpType(taicpu(p), top_ref, top_reg) and
  8036. GetNextInstruction(p, hp1) and
  8037. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8038. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8039. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8040. begin
  8041. SourceRef := taicpu(p).oper[0]^.ref^;
  8042. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8043. if GetNextInstruction(hp1, hp2) and
  8044. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8045. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8046. begin
  8047. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8048. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8049. Inc(SourceRef.offset, 16);
  8050. { Reuse the register in the first block move }
  8051. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8052. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8053. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8054. begin
  8055. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8056. Inc(TargetRef.offset, 16);
  8057. if GetNextInstruction(hp2, hp3) and
  8058. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8059. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8060. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8061. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8062. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8063. begin
  8064. { Update the register tracking to the new size }
  8065. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8066. { Remember that the offsets are 16 ahead }
  8067. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8068. if not (
  8069. ((SourceRef.offset mod 32) = 16) and
  8070. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8071. ) then
  8072. taicpu(p).opcode := A_VMOVDQU;
  8073. taicpu(p).opsize := S_YMM;
  8074. taicpu(p).oper[1]^.reg := CurrentReg;
  8075. if not (
  8076. ((TargetRef.offset mod 32) = 16) and
  8077. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8078. ) then
  8079. taicpu(hp1).opcode := A_VMOVDQU;
  8080. taicpu(hp1).opsize := S_YMM;
  8081. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8082. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8083. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8084. if (pi_uses_ymm in current_procinfo.flags) then
  8085. RemoveInstruction(hp2)
  8086. else
  8087. begin
  8088. taicpu(hp2).opcode := A_VPXOR;
  8089. taicpu(hp2).opsize := S_YMM;
  8090. taicpu(hp2).loadreg(0, CurrentReg);
  8091. taicpu(hp2).loadreg(1, CurrentReg);
  8092. taicpu(hp2).loadreg(2, CurrentReg);
  8093. taicpu(hp2).ops := 3;
  8094. end;
  8095. RemoveInstruction(hp3);
  8096. Result := True;
  8097. Exit;
  8098. end;
  8099. end
  8100. else
  8101. begin
  8102. { See if the next references are 16 less rather than 16 greater }
  8103. Dec(SourceRef.offset, 32); { -16 the other way }
  8104. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8105. begin
  8106. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8107. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8108. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8109. GetNextInstruction(hp2, hp3) and
  8110. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8111. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8112. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8113. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8114. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8115. begin
  8116. { Update the register tracking to the new size }
  8117. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8118. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8119. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8120. if not(
  8121. ((SourceRef.offset mod 32) = 0) and
  8122. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8123. ) then
  8124. taicpu(hp2).opcode := A_VMOVDQU;
  8125. taicpu(hp2).opsize := S_YMM;
  8126. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8127. if not (
  8128. ((TargetRef.offset mod 32) = 0) and
  8129. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8130. ) then
  8131. taicpu(hp3).opcode := A_VMOVDQU;
  8132. taicpu(hp3).opsize := S_YMM;
  8133. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8134. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8135. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8136. if (pi_uses_ymm in current_procinfo.flags) then
  8137. RemoveInstruction(hp1)
  8138. else
  8139. begin
  8140. taicpu(hp1).opcode := A_VPXOR;
  8141. taicpu(hp1).opsize := S_YMM;
  8142. taicpu(hp1).loadreg(0, CurrentReg);
  8143. taicpu(hp1).loadreg(1, CurrentReg);
  8144. taicpu(hp1).loadreg(2, CurrentReg);
  8145. taicpu(hp1).ops := 3;
  8146. Asml.Remove(hp1);
  8147. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8148. end;
  8149. RemoveCurrentP(p, hp2);
  8150. Result := True;
  8151. Exit;
  8152. end;
  8153. end;
  8154. end;
  8155. end;
  8156. end;
  8157. end;
  8158. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8159. var
  8160. hp2, hp3, first_assignment: tai;
  8161. IncCount, OperIdx: Integer;
  8162. OrigLabel: TAsmLabel;
  8163. begin
  8164. Count := 0;
  8165. Result := False;
  8166. first_assignment := nil;
  8167. if (LoopCount >= 20) then
  8168. begin
  8169. { Guard against infinite loops }
  8170. Exit;
  8171. end;
  8172. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8173. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8174. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8175. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8176. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8177. Exit;
  8178. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8179. {
  8180. change
  8181. jmp .L1
  8182. ...
  8183. .L1:
  8184. mov ##, ## ( multiple movs possible )
  8185. jmp/ret
  8186. into
  8187. mov ##, ##
  8188. jmp/ret
  8189. }
  8190. if not Assigned(hp1) then
  8191. begin
  8192. hp1 := GetLabelWithSym(OrigLabel);
  8193. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8194. Exit;
  8195. end;
  8196. hp2 := hp1;
  8197. while Assigned(hp2) do
  8198. begin
  8199. if Assigned(hp2) and (hp2.typ = ait_label) then
  8200. SkipLabels(hp2,hp2);
  8201. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8202. Break;
  8203. case taicpu(hp2).opcode of
  8204. A_MOVSD:
  8205. begin
  8206. if taicpu(hp2).ops = 0 then
  8207. { Wrong MOVSD }
  8208. Break;
  8209. Inc(Count);
  8210. if Count >= 5 then
  8211. { Too many to be worthwhile }
  8212. Break;
  8213. GetNextInstruction(hp2, hp2);
  8214. Continue;
  8215. end;
  8216. A_MOV,
  8217. A_MOVD,
  8218. A_MOVQ,
  8219. A_MOVSX,
  8220. {$ifdef x86_64}
  8221. A_MOVSXD,
  8222. {$endif x86_64}
  8223. A_MOVZX,
  8224. A_MOVAPS,
  8225. A_MOVUPS,
  8226. A_MOVSS,
  8227. A_MOVAPD,
  8228. A_MOVUPD,
  8229. A_MOVDQA,
  8230. A_MOVDQU,
  8231. A_VMOVSS,
  8232. A_VMOVAPS,
  8233. A_VMOVUPS,
  8234. A_VMOVSD,
  8235. A_VMOVAPD,
  8236. A_VMOVUPD,
  8237. A_VMOVDQA,
  8238. A_VMOVDQU:
  8239. begin
  8240. Inc(Count);
  8241. if Count >= 5 then
  8242. { Too many to be worthwhile }
  8243. Break;
  8244. GetNextInstruction(hp2, hp2);
  8245. Continue;
  8246. end;
  8247. A_JMP:
  8248. begin
  8249. { Guard against infinite loops }
  8250. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8251. Exit;
  8252. { Analyse this jump first in case it also duplicates assignments }
  8253. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8254. begin
  8255. { Something did change! }
  8256. Result := True;
  8257. Inc(Count, IncCount);
  8258. if Count >= 5 then
  8259. begin
  8260. { Too many to be worthwhile }
  8261. Exit;
  8262. end;
  8263. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8264. Break;
  8265. end;
  8266. Result := True;
  8267. Break;
  8268. end;
  8269. A_RET:
  8270. begin
  8271. Result := True;
  8272. Break;
  8273. end;
  8274. else
  8275. Break;
  8276. end;
  8277. end;
  8278. if Result then
  8279. begin
  8280. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8281. if Count = 0 then
  8282. begin
  8283. Result := False;
  8284. Exit;
  8285. end;
  8286. hp3 := p;
  8287. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8288. while True do
  8289. begin
  8290. if Assigned(hp1) and (hp1.typ = ait_label) then
  8291. SkipLabels(hp1,hp1);
  8292. if (hp1.typ <> ait_instruction) then
  8293. InternalError(2021040720);
  8294. case taicpu(hp1).opcode of
  8295. A_JMP:
  8296. begin
  8297. { Change the original jump to the new destination }
  8298. OrigLabel.decrefs;
  8299. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8300. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8301. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8302. if not Assigned(first_assignment) then
  8303. InternalError(2021040810)
  8304. else
  8305. p := first_assignment;
  8306. Exit;
  8307. end;
  8308. A_RET:
  8309. begin
  8310. { Now change the jump into a RET instruction }
  8311. ConvertJumpToRET(p, hp1);
  8312. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8313. if not Assigned(first_assignment) then
  8314. InternalError(2021040811)
  8315. else
  8316. p := first_assignment;
  8317. Exit;
  8318. end;
  8319. else
  8320. begin
  8321. { Duplicate the MOV instruction }
  8322. hp3:=tai(hp1.getcopy);
  8323. if first_assignment = nil then
  8324. first_assignment := hp3;
  8325. asml.InsertBefore(hp3, p);
  8326. { Make sure the compiler knows about any final registers written here }
  8327. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8328. with taicpu(hp3).oper[OperIdx]^ do
  8329. begin
  8330. case typ of
  8331. top_ref:
  8332. begin
  8333. if (ref^.base <> NR_NO) and
  8334. (getsupreg(ref^.base) <> RS_ESP) and
  8335. (getsupreg(ref^.base) <> RS_EBP)
  8336. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8337. then
  8338. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8339. if (ref^.index <> NR_NO) and
  8340. (getsupreg(ref^.index) <> RS_ESP) and
  8341. (getsupreg(ref^.index) <> RS_EBP)
  8342. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8343. (ref^.index <> ref^.base) then
  8344. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8345. end;
  8346. top_reg:
  8347. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8348. else
  8349. ;
  8350. end;
  8351. end;
  8352. end;
  8353. end;
  8354. if not GetNextInstruction(hp1, hp1) then
  8355. { Should have dropped out earlier }
  8356. InternalError(2021040710);
  8357. end;
  8358. end;
  8359. end;
  8360. const
  8361. WriteOp: array[0..3] of set of TInsChange = (
  8362. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8363. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8364. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8365. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8366. RegWriteFlags: array[0..7] of set of TInsChange = (
  8367. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8368. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8369. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8370. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8371. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8372. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8373. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8374. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8375. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8376. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8377. var
  8378. hp2: tai;
  8379. X: Integer;
  8380. begin
  8381. { If we have something like:
  8382. op ###,###
  8383. mov ###,###
  8384. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8385. interfere in regards to what they write to.
  8386. NOTE: p must be a 2-operand instruction
  8387. }
  8388. Result := False;
  8389. if (hp1.typ <> ait_instruction) or
  8390. taicpu(hp1).is_jmp or
  8391. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8392. Exit;
  8393. { NOP is a pipeline fence, likely marking the beginning of the function
  8394. epilogue, so drop out. Similarly, drop out if POP or RET are
  8395. encountered }
  8396. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8397. Exit;
  8398. if (taicpu(hp1).opcode = A_MOVSD) and
  8399. (taicpu(hp1).ops = 0) then
  8400. { Wrong MOVSD }
  8401. Exit;
  8402. { Check for writes to specific registers first }
  8403. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8404. for X := 0 to 7 do
  8405. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8406. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8407. Exit;
  8408. for X := 0 to taicpu(hp1).ops - 1 do
  8409. begin
  8410. { Check to see if this operand writes to something }
  8411. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8412. { And matches something in the CMP/TEST instruction }
  8413. (
  8414. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8415. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8416. (
  8417. { If it's a register, make sure the register written to doesn't
  8418. appear in the cmp instruction as part of a reference }
  8419. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8420. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8421. )
  8422. ) then
  8423. Exit;
  8424. end;
  8425. { Check p to make sure it doesn't write to something that affects hp1 }
  8426. { Check for writes to specific registers first }
  8427. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8428. for X := 0 to 7 do
  8429. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8430. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8431. Exit;
  8432. for X := 0 to taicpu(p).ops - 1 do
  8433. begin
  8434. { Check to see if this operand writes to something }
  8435. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8436. { And matches something in hp1 }
  8437. (taicpu(p).oper[X]^.typ = top_reg) and
  8438. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8439. Exit;
  8440. end;
  8441. { The instruction can be safely moved }
  8442. asml.Remove(hp1);
  8443. { Try to insert after the last instructions where the FLAGS register is not
  8444. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8445. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8446. asml.InsertBefore(hp1, hp2)
  8447. { Failing that, try to insert after the last instructions where the
  8448. FLAGS register is not yet in use }
  8449. else if GetLastInstruction(p, hp2) and
  8450. (
  8451. (hp2.typ <> ait_instruction) or
  8452. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8453. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8454. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8455. ) then
  8456. asml.InsertAfter(hp1, hp2)
  8457. else
  8458. { Note, if p.Previous is nil (even if it should logically never be the
  8459. case), FindRegAllocBackward immediately exits with False and so we
  8460. safely land here (we can't just pass p because FindRegAllocBackward
  8461. immediately exits on an instruction). [Kit] }
  8462. asml.InsertBefore(hp1, p);
  8463. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8464. { We can't trust UsedRegs because we're looking backwards, although we
  8465. know the registers are allocated after p at the very least, so manually
  8466. create tai_regalloc objects if needed }
  8467. for X := 0 to taicpu(hp1).ops - 1 do
  8468. case taicpu(hp1).oper[X]^.typ of
  8469. top_reg:
  8470. begin
  8471. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8472. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8473. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8474. end;
  8475. top_ref:
  8476. begin
  8477. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8478. begin
  8479. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8480. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8481. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8482. end;
  8483. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8484. begin
  8485. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8486. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8487. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8488. end;
  8489. end;
  8490. else
  8491. ;
  8492. end;
  8493. Result := True;
  8494. end;
  8495. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8496. var
  8497. hp2: tai;
  8498. X: Integer;
  8499. begin
  8500. { If we have something like:
  8501. cmp ###,%reg1
  8502. mov 0,%reg2
  8503. And no modified registers are shared, move the instruction to before
  8504. the comparison as this means it can be optimised without worrying
  8505. about the FLAGS register. (CMP/MOV is generated by
  8506. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8507. As long as the second instruction doesn't use the flags or one of the
  8508. registers used by CMP or TEST (also check any references that use the
  8509. registers), then it can be moved prior to the comparison.
  8510. }
  8511. Result := False;
  8512. if not TrySwapMovOp(p, hp1) then
  8513. Exit;
  8514. if taicpu(hp1).opcode = A_LEA then
  8515. { The flags will be overwritten by the CMP/TEST instruction }
  8516. ConvertLEA(taicpu(hp1));
  8517. Result := True;
  8518. { Can we move it one further back? }
  8519. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8520. { Check to see if CMP/TEST is a comparison against zero }
  8521. (
  8522. (
  8523. (taicpu(p).opcode = A_CMP) and
  8524. MatchOperand(taicpu(p).oper[0]^, 0)
  8525. ) or
  8526. (
  8527. (taicpu(p).opcode = A_TEST) and
  8528. (
  8529. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8530. MatchOperand(taicpu(p).oper[0]^, -1)
  8531. )
  8532. )
  8533. ) and
  8534. { These instructions set the zero flag if the result is zero }
  8535. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8536. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8537. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8538. TrySwapMovOp(hp2, hp1);
  8539. end;
  8540. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8541. var
  8542. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8543. JumpLabel: TAsmLabel;
  8544. TmpBool: Boolean;
  8545. begin
  8546. Result := False;
  8547. { Look for:
  8548. stc/clc
  8549. j(c) .L1
  8550. ...
  8551. .L1:
  8552. set(n)cb %reg
  8553. (flags deallocated)
  8554. j(c) .L2
  8555. Change to:
  8556. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8557. j(c) .L2
  8558. }
  8559. p_last := p;
  8560. while GetNextInstruction(p_last, hp1) and
  8561. (hp1.typ = ait_instruction) and
  8562. IsJumpToLabel(taicpu(hp1)) do
  8563. begin
  8564. if DoJumpOptimizations(hp1, TmpBool) then
  8565. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8566. Continue;
  8567. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8568. if not Assigned(JumpLabel) then
  8569. InternalError(2024012801);
  8570. { Optimise the J(c); stc/clc optimisation first since this will
  8571. get missed if the main optimisation takes place }
  8572. if (taicpu(hp1).opcode = A_JCC) then
  8573. begin
  8574. if GetNextInstruction(hp1, hp2) and
  8575. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8576. TryJccStcClcOpt(hp1, hp2) then
  8577. begin
  8578. Result := True;
  8579. Exit;
  8580. end;
  8581. hp2 := nil; { Suppress compiler warning }
  8582. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8583. { Make sure the flags aren't used again }
  8584. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8585. begin
  8586. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8587. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8588. begin
  8589. if (taicpu(p).opcode = A_STC) then
  8590. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8591. else
  8592. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8593. MakeUnconditional(taicpu(hp1));
  8594. { Move the jump to after the flag deallocations }
  8595. Asml.Remove(hp1);
  8596. Asml.InsertAfter(hp1, hp2);
  8597. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8598. Result := True;
  8599. Exit;
  8600. end
  8601. else
  8602. begin
  8603. if (taicpu(p).opcode = A_STC) then
  8604. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8605. else
  8606. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8607. { In this case, the jump is deterministic in that it will never be taken }
  8608. JumpLabel.DecRefs;
  8609. RemoveInstruction(hp1);
  8610. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8611. Result := True;
  8612. Exit;
  8613. end;
  8614. end;
  8615. end;
  8616. hp2 := nil; { Suppress compiler warning }
  8617. if
  8618. { Make sure the carry flag doesn't appear in the jump conditions }
  8619. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8620. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8621. GetNextInstruction(hp2, p_dist) and
  8622. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8623. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8624. begin
  8625. case taicpu(p_dist).opcode of
  8626. A_Jcc:
  8627. begin
  8628. if DoJumpOptimizations(p_dist, TmpBool) then
  8629. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8630. Continue;
  8631. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8632. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8633. begin
  8634. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8635. JumpLabel.decrefs;
  8636. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8637. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8638. Result := True;
  8639. Exit;
  8640. end
  8641. else if GetNextInstruction(p_dist, hp1_dist) and
  8642. (hp1_dist.typ = ait_label) then
  8643. begin
  8644. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8645. JumpLabel.decrefs;
  8646. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8647. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8648. Result := True;
  8649. Exit;
  8650. end;
  8651. end;
  8652. A_SETcc:
  8653. if { Make sure the flags aren't used again }
  8654. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8655. GetNextInstruction(hp2, hp1_dist) and
  8656. (hp1_dist.typ = ait_instruction) and
  8657. IsJumpToLabel(taicpu(hp1_dist)) and
  8658. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8659. { This works if hp1_dist or both are regular JMP instructions }
  8660. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8661. (
  8662. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8663. { Make sure the register isn't still in use, otherwise it
  8664. may get corrupted (fixes #40659) }
  8665. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8666. ) then
  8667. begin
  8668. taicpu(p).allocate_oper(2);
  8669. taicpu(p).ops := 2;
  8670. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8671. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8672. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8673. taicpu(p).opcode := A_MOV;
  8674. taicpu(p).opsize := S_B;
  8675. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8676. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8677. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8678. JumpLabel.decrefs;
  8679. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8680. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8681. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8682. (tai_regalloc(hp2).ratype = ra_alloc) then
  8683. begin
  8684. Asml.Remove(hp2);
  8685. Asml.InsertAfter(hp2, p);
  8686. end;
  8687. Result := True;
  8688. Exit;
  8689. end;
  8690. else
  8691. ;
  8692. end;
  8693. end;
  8694. p_last := hp1;
  8695. end;
  8696. end;
  8697. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8698. var
  8699. hp2, hp3: tai;
  8700. TempBool: Boolean;
  8701. begin
  8702. Result := False;
  8703. {
  8704. j(c) .L1
  8705. stc/clc
  8706. .L1:
  8707. jc/jnc .L2
  8708. (Flags deallocated)
  8709. Change to:
  8710. j)c) .L1
  8711. jmp .L2
  8712. .L1:
  8713. jc/jnc .L2
  8714. Then call DoJumpOptimizations to convert to:
  8715. j(nc) .L2
  8716. .L1: (may become a dead label)
  8717. jc/jnc .L2
  8718. }
  8719. if GetNextInstruction(hp1, hp2) and
  8720. (hp2.typ = ait_label) and
  8721. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8722. GetNextInstruction(hp2, hp3) and
  8723. MatchInstruction(hp3, A_Jcc, []) and
  8724. (
  8725. (
  8726. (taicpu(hp3).condition = C_C) and
  8727. (taicpu(hp1).opcode = A_STC)
  8728. ) or (
  8729. (taicpu(hp3).condition = C_NC) and
  8730. (taicpu(hp1).opcode = A_CLC)
  8731. )
  8732. ) and
  8733. { Make sure the flags aren't used again }
  8734. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8735. begin
  8736. taicpu(hp1).allocate_oper(1);
  8737. taicpu(hp1).ops := 1;
  8738. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8739. taicpu(hp1).opcode := A_JMP;
  8740. taicpu(hp1).is_jmp := True;
  8741. TempBool := True; { Prevent compiler warnings }
  8742. if DoJumpOptimizations(p, TempBool) then
  8743. Result := True
  8744. else
  8745. Include(OptsToCheck, aoc_ForceNewIteration);
  8746. end;
  8747. end;
  8748. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8749. begin
  8750. { This generally only executes under -O3 and above }
  8751. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8752. end;
  8753. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8754. var
  8755. hp1, hp2: tai;
  8756. FoundComparison: Boolean;
  8757. begin
  8758. Result := False;
  8759. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8760. and make a slightly inefficent result on branching-type blocks, notably
  8761. when setting a function result then jumping to the function epilogue.
  8762. In this case, change:
  8763. cmov(c) %reg1,%reg2
  8764. j(c) @lbl
  8765. (%reg2 deallocated)
  8766. To:
  8767. mov %reg11,%reg2
  8768. j(c) @lbl
  8769. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8770. jump because if it's not present, we may end up with a jump that's
  8771. completely unrelated.
  8772. }
  8773. hp1 := p;
  8774. while GetNextInstruction(hp1, hp1) and
  8775. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  8776. if (hp1.typ = ait_instruction) and
  8777. (taicpu(hp1).opcode = A_Jcc) and
  8778. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  8779. begin
  8780. TransferUsedRegs(TmpUsedRegs);
  8781. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  8782. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  8783. (
  8784. { See if we can find a more distant instruction that overwrites
  8785. the destination register }
  8786. (cs_opt_level3 in current_settings.optimizerswitches) and
  8787. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8788. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  8789. ) then
  8790. begin
  8791. if (taicpu(p).oper[0]^.typ = top_reg) then
  8792. begin
  8793. { Search backwards to see if the source register is set to a
  8794. constant }
  8795. FoundComparison := False;
  8796. hp1 := p;
  8797. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  8798. begin
  8799. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  8800. begin
  8801. FoundComparison := True;
  8802. Continue;
  8803. end;
  8804. { Once we find the CMP, TEST or similar instruction, we
  8805. have to stop if we find anything other than a MOV }
  8806. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  8807. Break;
  8808. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  8809. { Destination register was modified }
  8810. Break;
  8811. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  8812. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  8813. begin
  8814. { Found a constant! }
  8815. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  8816. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8817. { The source register is no longer in use }
  8818. RemoveInstruction(hp1);
  8819. Break;
  8820. end;
  8821. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  8822. { Some other instruction has modified the source register }
  8823. Break;
  8824. end;
  8825. end;
  8826. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  8827. taicpu(p).opcode := A_MOV;
  8828. taicpu(p).condition := C_None;
  8829. { Rely on the post peephole stage to put the MOV before the
  8830. CMP/TEST instruction that appears prior }
  8831. Result := True;
  8832. Exit;
  8833. end;
  8834. end;
  8835. end;
  8836. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8837. function IsXCHGAcceptable: Boolean; inline;
  8838. begin
  8839. { Always accept if optimising for size }
  8840. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8841. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8842. than 3, so it becomes a saving compared to three MOVs with two of
  8843. them able to execute simultaneously. [Kit] }
  8844. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8845. end;
  8846. var
  8847. NewRef: TReference;
  8848. hp1, hp2, hp3, hp4: Tai;
  8849. {$ifndef x86_64}
  8850. OperIdx: Integer;
  8851. {$endif x86_64}
  8852. NewInstr : Taicpu;
  8853. NewAligh : Tai_align;
  8854. DestLabel: TAsmLabel;
  8855. TempTracking: TAllUsedRegs;
  8856. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8857. var
  8858. NextInstr: tai;
  8859. begin
  8860. Result := False;
  8861. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8862. if not GetNextInstruction(InputInstr, NextInstr) or
  8863. (
  8864. { The FLAGS register isn't always tracked properly, so do not
  8865. perform this optimisation if a conditional statement follows }
  8866. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8867. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8868. ) then
  8869. begin
  8870. reference_reset(NewRef, 1, []);
  8871. NewRef.base := taicpu(p).oper[0]^.reg;
  8872. NewRef.scalefactor := 1;
  8873. if taicpu(InputInstr).opcode = A_ADD then
  8874. begin
  8875. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8876. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8877. end
  8878. else
  8879. begin
  8880. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8881. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8882. end;
  8883. taicpu(p).opcode := A_LEA;
  8884. taicpu(p).loadref(0, NewRef);
  8885. RemoveInstruction(InputInstr);
  8886. Result := True;
  8887. end;
  8888. end;
  8889. begin
  8890. Result:=false;
  8891. { This optimisation adds an instruction, so only do it for speed }
  8892. if not (cs_opt_size in current_settings.optimizerswitches) and
  8893. MatchOpType(taicpu(p), top_const, top_reg) and
  8894. (taicpu(p).oper[0]^.val = 0) then
  8895. begin
  8896. { To avoid compiler warning }
  8897. DestLabel := nil;
  8898. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8899. InternalError(2021040750);
  8900. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8901. Exit;
  8902. case hp1.typ of
  8903. ait_label:
  8904. begin
  8905. { Change:
  8906. mov $0,%reg mov $0,%reg
  8907. @Lbl1: @Lbl1:
  8908. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8909. je @Lbl2 jne @Lbl2
  8910. To: To:
  8911. mov $0,%reg mov $0,%reg
  8912. jmp @Lbl2 jmp @Lbl3
  8913. (align) (align)
  8914. @Lbl1: @Lbl1:
  8915. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8916. je @Lbl2 je @Lbl2
  8917. @Lbl3: <-- Only if label exists
  8918. (Not if it's optimised for size)
  8919. }
  8920. if not GetNextInstruction(hp1, hp2) then
  8921. Exit;
  8922. if (hp2.typ = ait_instruction) and
  8923. (
  8924. { Register sizes must exactly match }
  8925. (
  8926. (taicpu(hp2).opcode = A_CMP) and
  8927. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8928. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8929. ) or (
  8930. (taicpu(hp2).opcode = A_TEST) and
  8931. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8932. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8933. )
  8934. ) and GetNextInstruction(hp2, hp3) and
  8935. (hp3.typ = ait_instruction) and
  8936. (taicpu(hp3).opcode = A_JCC) and
  8937. (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
  8938. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8939. begin
  8940. { Check condition of jump }
  8941. { Always true? }
  8942. if condition_in(C_E, taicpu(hp3).condition) then
  8943. begin
  8944. { Copy label symbol and obtain matching label entry for the
  8945. conditional jump, as this will be our destination}
  8946. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8947. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8948. Result := True;
  8949. end
  8950. { Always false? }
  8951. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8952. begin
  8953. { This is only worth it if there's a jump to take }
  8954. case hp2.typ of
  8955. ait_instruction:
  8956. begin
  8957. if taicpu(hp2).opcode = A_JMP then
  8958. begin
  8959. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8960. { An unconditional jump follows the conditional jump which will always be false,
  8961. so use this jump's destination for the new jump }
  8962. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8963. Result := True;
  8964. end
  8965. else if taicpu(hp2).opcode = A_JCC then
  8966. begin
  8967. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8968. if condition_in(C_E, taicpu(hp2).condition) then
  8969. begin
  8970. { A second conditional jump follows the conditional jump which will always be false,
  8971. while the second jump is always True, so use this jump's destination for the new jump }
  8972. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8973. Result := True;
  8974. end;
  8975. { Don't risk it if the jump isn't always true (Result remains False) }
  8976. end;
  8977. end;
  8978. else
  8979. { If anything else don't optimise };
  8980. end;
  8981. end;
  8982. if Result then
  8983. begin
  8984. { Just so we have something to insert as a paremeter}
  8985. reference_reset(NewRef, 1, []);
  8986. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8987. { Now actually load the correct parameter (this also
  8988. increases the reference count) }
  8989. NewInstr.loadsymbol(0, DestLabel, 0);
  8990. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8991. begin
  8992. { Get instruction before original label (may not be p under -O3) }
  8993. if not GetLastInstruction(hp1, hp2) then
  8994. { Shouldn't fail here }
  8995. InternalError(2021040701);
  8996. end
  8997. else
  8998. hp2 := p;
  8999. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9000. AsmL.InsertAfter(NewInstr, hp2);
  9001. { Add new alignment field }
  9002. (* AsmL.InsertAfter(
  9003. cai_align.create_max(
  9004. current_settings.alignment.jumpalign,
  9005. current_settings.alignment.jumpalignskipmax
  9006. ),
  9007. NewInstr
  9008. ); *)
  9009. end;
  9010. Exit;
  9011. end;
  9012. end;
  9013. else
  9014. ;
  9015. end;
  9016. end;
  9017. if not GetNextInstruction(p, hp1) then
  9018. Exit;
  9019. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9020. begin
  9021. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9022. begin
  9023. Result := True;
  9024. Exit;
  9025. end;
  9026. { This optimisation is only effective on a second run of Pass 2,
  9027. hence -O3 or above.
  9028. Change:
  9029. mov %reg1,%reg2
  9030. cmp/test (contains %reg1)
  9031. mov x, %reg1
  9032. (another mov or a j(c))
  9033. To:
  9034. mov %reg1,%reg2
  9035. mov x, %reg1
  9036. cmp (%reg1 replaced with %reg2)
  9037. (another mov or a j(c))
  9038. The requirement of an additional MOV or a jump ensures there
  9039. isn't performance loss, since a j(c) will permit macro-fusion
  9040. with the cmp instruction, while another MOV likely means it's
  9041. not all being executed in a single cycle due to parallelisation.
  9042. }
  9043. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9044. MatchOpType(taicpu(p), top_reg, top_reg) and
  9045. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9046. GetNextInstruction(hp1, hp2) and
  9047. MatchInstruction(hp2, A_MOV, []) and
  9048. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9049. { Registers don't have to be the same size in this case }
  9050. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9051. GetNextInstruction(hp2, hp3) and
  9052. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9053. { Make sure the operands in the camparison can be safely replaced }
  9054. (
  9055. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9056. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9057. ) and
  9058. (
  9059. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9060. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9061. ) then
  9062. begin
  9063. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9064. AsmL.Remove(hp2);
  9065. AsmL.InsertAfter(hp2, p);
  9066. Result := True;
  9067. Exit;
  9068. end;
  9069. end;
  9070. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9071. begin
  9072. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9073. further, but we can't just put this jump optimisation in pass 1
  9074. because it tends to perform worse when conditional jumps are
  9075. nearby (e.g. when converting CMOV instructions). [Kit] }
  9076. CopyUsedRegs(TempTracking);
  9077. UpdateUsedRegs(tai(p.Next));
  9078. if OptPass2JMP(hp1) then
  9079. begin
  9080. { Restore register state }
  9081. RestoreUsedRegs(TempTracking);
  9082. ReleaseUsedRegs(TempTracking);
  9083. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9084. OptPass1MOV(p);
  9085. Result := True;
  9086. Exit;
  9087. end;
  9088. { If OptPass2JMP returned False, no optimisations were done to
  9089. the jump and there are no further optimisations that can be done
  9090. to the MOV instruction on this pass other than FuncMov2Func }
  9091. { Restore register state }
  9092. RestoreUsedRegs(TempTracking);
  9093. ReleaseUsedRegs(TempTracking);
  9094. Result := FuncMov2Func(p, hp1);
  9095. Exit;
  9096. end;
  9097. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9098. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9099. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9100. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9101. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9102. begin
  9103. { Change:
  9104. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9105. addl/q $x,%reg2 subl/q $x,%reg2
  9106. To:
  9107. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9108. }
  9109. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9110. { be lazy, checking separately for sub would be slightly better }
  9111. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9112. begin
  9113. TransferUsedRegs(TmpUsedRegs);
  9114. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9115. if TryMovArith2Lea(hp1) then
  9116. begin
  9117. Result := True;
  9118. Exit;
  9119. end
  9120. end
  9121. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9122. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9123. { Same as above, but also adds or subtracts to %reg2 in between.
  9124. It's still valid as long as the flags aren't in use }
  9125. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9126. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9127. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9128. { be lazy, checking separately for sub would be slightly better }
  9129. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9130. begin
  9131. TransferUsedRegs(TmpUsedRegs);
  9132. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9133. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9134. if TryMovArith2Lea(hp2) then
  9135. begin
  9136. Result := True;
  9137. Exit;
  9138. end;
  9139. end;
  9140. end;
  9141. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9142. {$ifdef x86_64}
  9143. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9144. {$else x86_64}
  9145. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9146. {$endif x86_64}
  9147. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9148. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9149. { mov reg1, reg2 mov reg1, reg2
  9150. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9151. begin
  9152. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9153. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9154. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9155. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9156. TransferUsedRegs(TmpUsedRegs);
  9157. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9158. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9159. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9160. then
  9161. begin
  9162. RemoveCurrentP(p, hp1);
  9163. Result:=true;
  9164. end;
  9165. Exit;
  9166. end;
  9167. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9168. IsXCHGAcceptable and
  9169. { XCHG doesn't support 8-bit registers }
  9170. (taicpu(p).opsize <> S_B) and
  9171. MatchInstruction(hp1, A_MOV, []) and
  9172. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9173. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9174. GetNextInstruction(hp1, hp2) and
  9175. MatchInstruction(hp2, A_MOV, []) and
  9176. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9177. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9178. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9179. begin
  9180. { mov %reg1,%reg2
  9181. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9182. mov %reg2,%reg3
  9183. (%reg2 not used afterwards)
  9184. Note that xchg takes 3 cycles to execute, and generally mov's take
  9185. only one cycle apiece, but the first two mov's can be executed in
  9186. parallel, only taking 2 cycles overall. Older processors should
  9187. therefore only optimise for size. [Kit]
  9188. }
  9189. TransferUsedRegs(TmpUsedRegs);
  9190. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9191. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9192. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9193. begin
  9194. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9195. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9196. taicpu(hp1).opcode := A_XCHG;
  9197. RemoveCurrentP(p, hp1);
  9198. RemoveInstruction(hp2);
  9199. Result := True;
  9200. Exit;
  9201. end;
  9202. end;
  9203. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9204. MatchInstruction(hp1, A_SAR, []) then
  9205. begin
  9206. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9207. begin
  9208. { the use of %edx also covers the opsize being S_L }
  9209. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9210. begin
  9211. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9212. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9213. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9214. begin
  9215. { Change:
  9216. movl %eax,%edx
  9217. sarl $31,%edx
  9218. To:
  9219. cltd
  9220. }
  9221. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9222. RemoveInstruction(hp1);
  9223. taicpu(p).opcode := A_CDQ;
  9224. taicpu(p).opsize := S_NO;
  9225. taicpu(p).clearop(1);
  9226. taicpu(p).clearop(0);
  9227. taicpu(p).ops:=0;
  9228. Result := True;
  9229. Exit;
  9230. end
  9231. else if (cs_opt_size in current_settings.optimizerswitches) and
  9232. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9233. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9234. begin
  9235. { Change:
  9236. movl %edx,%eax
  9237. sarl $31,%edx
  9238. To:
  9239. movl %edx,%eax
  9240. cltd
  9241. Note that this creates a dependency between the two instructions,
  9242. so only perform if optimising for size.
  9243. }
  9244. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9245. taicpu(hp1).opcode := A_CDQ;
  9246. taicpu(hp1).opsize := S_NO;
  9247. taicpu(hp1).clearop(1);
  9248. taicpu(hp1).clearop(0);
  9249. taicpu(hp1).ops:=0;
  9250. Include(OptsToCheck, aoc_ForceNewIteration);
  9251. Exit;
  9252. end;
  9253. {$ifndef x86_64}
  9254. end
  9255. { Don't bother if CMOV is supported, because a more optimal
  9256. sequence would have been generated for the Abs() intrinsic }
  9257. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9258. { the use of %eax also covers the opsize being S_L }
  9259. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9260. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9261. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9262. GetNextInstruction(hp1, hp2) and
  9263. MatchInstruction(hp2, A_XOR, [S_L]) and
  9264. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9265. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9266. GetNextInstruction(hp2, hp3) and
  9267. MatchInstruction(hp3, A_SUB, [S_L]) and
  9268. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9269. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9270. begin
  9271. { Change:
  9272. movl %eax,%edx
  9273. sarl $31,%eax
  9274. xorl %eax,%edx
  9275. subl %eax,%edx
  9276. (Instruction that uses %edx)
  9277. (%eax deallocated)
  9278. (%edx deallocated)
  9279. To:
  9280. cltd
  9281. xorl %edx,%eax <-- Note the registers have swapped
  9282. subl %edx,%eax
  9283. (Instruction that uses %eax) <-- %eax rather than %edx
  9284. }
  9285. TransferUsedRegs(TmpUsedRegs);
  9286. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9287. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9288. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9289. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9290. begin
  9291. if GetNextInstruction(hp3, hp4) and
  9292. not RegModifiedByInstruction(NR_EDX, hp4) and
  9293. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9294. begin
  9295. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9296. taicpu(p).opcode := A_CDQ;
  9297. taicpu(p).clearop(1);
  9298. taicpu(p).clearop(0);
  9299. taicpu(p).ops:=0;
  9300. RemoveInstruction(hp1);
  9301. taicpu(hp2).loadreg(0, NR_EDX);
  9302. taicpu(hp2).loadreg(1, NR_EAX);
  9303. taicpu(hp3).loadreg(0, NR_EDX);
  9304. taicpu(hp3).loadreg(1, NR_EAX);
  9305. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9306. { Convert references in the following instruction (hp4) from %edx to %eax }
  9307. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9308. with taicpu(hp4).oper[OperIdx]^ do
  9309. case typ of
  9310. top_reg:
  9311. if getsupreg(reg) = RS_EDX then
  9312. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9313. top_ref:
  9314. begin
  9315. if getsupreg(reg) = RS_EDX then
  9316. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9317. if getsupreg(reg) = RS_EDX then
  9318. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9319. end;
  9320. else
  9321. ;
  9322. end;
  9323. Result := True;
  9324. Exit;
  9325. end;
  9326. end;
  9327. {$else x86_64}
  9328. end;
  9329. end
  9330. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9331. { the use of %rdx also covers the opsize being S_Q }
  9332. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9333. begin
  9334. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9335. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9336. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9337. begin
  9338. { Change:
  9339. movq %rax,%rdx
  9340. sarq $63,%rdx
  9341. To:
  9342. cqto
  9343. }
  9344. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9345. RemoveInstruction(hp1);
  9346. taicpu(p).opcode := A_CQO;
  9347. taicpu(p).opsize := S_NO;
  9348. taicpu(p).clearop(1);
  9349. taicpu(p).clearop(0);
  9350. taicpu(p).ops:=0;
  9351. Result := True;
  9352. Exit;
  9353. end
  9354. else if (cs_opt_size in current_settings.optimizerswitches) and
  9355. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9356. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9357. begin
  9358. { Change:
  9359. movq %rdx,%rax
  9360. sarq $63,%rdx
  9361. To:
  9362. movq %rdx,%rax
  9363. cqto
  9364. Note that this creates a dependency between the two instructions,
  9365. so only perform if optimising for size.
  9366. }
  9367. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9368. taicpu(hp1).opcode := A_CQO;
  9369. taicpu(hp1).opsize := S_NO;
  9370. taicpu(hp1).clearop(1);
  9371. taicpu(hp1).clearop(0);
  9372. taicpu(hp1).ops:=0;
  9373. Include(OptsToCheck, aoc_ForceNewIteration);
  9374. Exit;
  9375. {$endif x86_64}
  9376. end;
  9377. end;
  9378. end;
  9379. if MatchInstruction(hp1, A_MOV, []) and
  9380. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9381. { Though "GetNextInstruction" could be factored out, along with
  9382. the instructions that depend on hp2, it is an expensive call that
  9383. should be delayed for as long as possible, hence we do cheaper
  9384. checks first that are likely to be False. [Kit] }
  9385. begin
  9386. if (
  9387. (
  9388. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9389. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9390. (
  9391. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9392. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9393. )
  9394. ) or
  9395. (
  9396. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9397. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9398. (
  9399. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9400. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9401. )
  9402. )
  9403. ) and
  9404. GetNextInstruction(hp1, hp2) and
  9405. MatchInstruction(hp2, A_SAR, []) and
  9406. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9407. begin
  9408. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9409. begin
  9410. { Change:
  9411. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9412. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9413. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9414. To:
  9415. movl r/m,%eax <- Note the change in register
  9416. cltd
  9417. }
  9418. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9419. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9420. taicpu(p).loadreg(1, NR_EAX);
  9421. taicpu(hp1).opcode := A_CDQ;
  9422. taicpu(hp1).clearop(1);
  9423. taicpu(hp1).clearop(0);
  9424. taicpu(hp1).ops:=0;
  9425. RemoveInstruction(hp2);
  9426. Include(OptsToCheck, aoc_ForceNewIteration);
  9427. (*
  9428. {$ifdef x86_64}
  9429. end
  9430. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9431. { This code sequence does not get generated - however it might become useful
  9432. if and when 128-bit signed integer types make an appearance, so the code
  9433. is kept here for when it is eventually needed. [Kit] }
  9434. (
  9435. (
  9436. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9437. (
  9438. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9439. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9440. )
  9441. ) or
  9442. (
  9443. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9444. (
  9445. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9446. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9447. )
  9448. )
  9449. ) and
  9450. GetNextInstruction(hp1, hp2) and
  9451. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9452. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9453. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9454. begin
  9455. { Change:
  9456. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9457. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9458. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9459. To:
  9460. movq r/m,%rax <- Note the change in register
  9461. cqto
  9462. }
  9463. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9464. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9465. taicpu(p).loadreg(1, NR_RAX);
  9466. taicpu(hp1).opcode := A_CQO;
  9467. taicpu(hp1).clearop(1);
  9468. taicpu(hp1).clearop(0);
  9469. taicpu(hp1).ops:=0;
  9470. RemoveInstruction(hp2);
  9471. Include(OptsToCheck, aoc_ForceNewIteration);
  9472. {$endif x86_64}
  9473. *)
  9474. end;
  9475. end;
  9476. {$ifdef x86_64}
  9477. end;
  9478. if (taicpu(p).opsize = S_L) and
  9479. (taicpu(p).oper[1]^.typ = top_reg) and
  9480. (
  9481. MatchInstruction(hp1, A_MOV,[]) and
  9482. (taicpu(hp1).opsize = S_L) and
  9483. (taicpu(hp1).oper[1]^.typ = top_reg)
  9484. ) and (
  9485. GetNextInstruction(hp1, hp2) and
  9486. (tai(hp2).typ=ait_instruction) and
  9487. (taicpu(hp2).opsize = S_Q) and
  9488. (
  9489. (
  9490. MatchInstruction(hp2, A_ADD,[]) and
  9491. (taicpu(hp2).opsize = S_Q) and
  9492. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9493. (
  9494. (
  9495. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9496. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9497. ) or (
  9498. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9499. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9500. )
  9501. )
  9502. ) or (
  9503. MatchInstruction(hp2, A_LEA,[]) and
  9504. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9505. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9506. (
  9507. (
  9508. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9509. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9510. ) or (
  9511. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9512. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9513. )
  9514. ) and (
  9515. (
  9516. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9517. ) or (
  9518. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9519. )
  9520. )
  9521. )
  9522. )
  9523. ) and (
  9524. GetNextInstruction(hp2, hp3) and
  9525. MatchInstruction(hp3, A_SHR,[]) and
  9526. (taicpu(hp3).opsize = S_Q) and
  9527. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9528. (taicpu(hp3).oper[0]^.val = 1) and
  9529. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9530. ) then
  9531. begin
  9532. { Change movl x, reg1d movl x, reg1d
  9533. movl y, reg2d movl y, reg2d
  9534. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9535. shrq $1, reg1q shrq $1, reg1q
  9536. ( reg1d and reg2d can be switched around in the first two instructions )
  9537. To movl x, reg1d
  9538. addl y, reg1d
  9539. rcrl $1, reg1d
  9540. This corresponds to the common expression (x + y) shr 1, where
  9541. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9542. smaller code, but won't account for x + y causing an overflow). [Kit]
  9543. }
  9544. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9545. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9546. begin
  9547. { Change first MOV command to have the same register as the final output }
  9548. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9549. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9550. Result := True;
  9551. end
  9552. else
  9553. begin
  9554. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9555. Include(OptsToCheck, aoc_ForceNewIteration);
  9556. end;
  9557. { Change second MOV command to an ADD command. This is easier than
  9558. converting the existing command because it means we don't have to
  9559. touch 'y', which might be a complicated reference, and also the
  9560. fact that the third command might either be ADD or LEA. [Kit] }
  9561. taicpu(hp1).opcode := A_ADD;
  9562. { Delete old ADD/LEA instruction }
  9563. RemoveInstruction(hp2);
  9564. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9565. taicpu(hp3).opcode := A_RCR;
  9566. taicpu(hp3).changeopsize(S_L);
  9567. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9568. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9569. called, so FuncMov2Func below is safe to call }
  9570. {$endif x86_64}
  9571. end;
  9572. if FuncMov2Func(p, hp1) then
  9573. begin
  9574. Result := True;
  9575. Exit;
  9576. end;
  9577. end;
  9578. {$push}
  9579. {$q-}{$r-}
  9580. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9581. var
  9582. ThisReg: TRegister;
  9583. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9584. TargetSubReg: TSubRegister;
  9585. hp1, hp2: tai;
  9586. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9587. { Store list of found instructions so we don't have to call
  9588. GetNextInstructionUsingReg multiple times }
  9589. InstrList: array of taicpu;
  9590. InstrMax, Index: Integer;
  9591. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9592. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9593. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9594. WorkingValue: TCgInt;
  9595. PreMessage: string;
  9596. { Data flow analysis }
  9597. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9598. BitwiseOnly, OrXorUsed,
  9599. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9600. function CheckOverflowConditions: Boolean;
  9601. begin
  9602. Result := True;
  9603. if (TestValSignedMax > SignedUpperLimit) then
  9604. UpperSignedOverflow := True;
  9605. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9606. LowerSignedOverflow := True;
  9607. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9608. LowerUnsignedOverflow := True;
  9609. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9610. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9611. begin
  9612. { Absolute overflow }
  9613. Result := False;
  9614. Exit;
  9615. end;
  9616. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9617. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9618. ShiftDownOverflow := True;
  9619. if (TestValMin < 0) or (TestValMax < 0) then
  9620. begin
  9621. LowerUnsignedOverflow := True;
  9622. UpperUnsignedOverflow := True;
  9623. end;
  9624. end;
  9625. function AdjustInitialLoadAndSize: Boolean;
  9626. begin
  9627. Result := False;
  9628. if not p_removed then
  9629. begin
  9630. if TargetSize = MinSize then
  9631. begin
  9632. { Convert the input MOVZX to a MOV }
  9633. if (taicpu(p).oper[0]^.typ = top_reg) and
  9634. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9635. begin
  9636. { Or remove it completely! }
  9637. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9638. RemoveCurrentP(p);
  9639. p_removed := True;
  9640. end
  9641. else
  9642. begin
  9643. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9644. taicpu(p).opcode := A_MOV;
  9645. taicpu(p).oper[1]^.reg := ThisReg;
  9646. taicpu(p).opsize := TargetSize;
  9647. end;
  9648. Result := True;
  9649. end
  9650. else if TargetSize <> MaxSize then
  9651. begin
  9652. case MaxSize of
  9653. S_L:
  9654. if TargetSize = S_W then
  9655. begin
  9656. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9657. taicpu(p).opsize := S_BW;
  9658. taicpu(p).oper[1]^.reg := ThisReg;
  9659. Result := True;
  9660. end
  9661. else
  9662. InternalError(2020112341);
  9663. S_W:
  9664. if TargetSize = S_L then
  9665. begin
  9666. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9667. taicpu(p).opsize := S_BL;
  9668. taicpu(p).oper[1]^.reg := ThisReg;
  9669. Result := True;
  9670. end
  9671. else
  9672. InternalError(2020112342);
  9673. else
  9674. ;
  9675. end;
  9676. end
  9677. else if not hp1_removed and not RegInUse then
  9678. begin
  9679. { If we have something like:
  9680. movzbl (oper),%regd
  9681. add x, %regd
  9682. movzbl %regb, %regd
  9683. We can reduce the register size to the input of the final
  9684. movzbl instruction. Overflows won't have any effect.
  9685. }
  9686. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9687. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9688. begin
  9689. TargetSize := S_B;
  9690. setsubreg(ThisReg, R_SUBL);
  9691. Result := True;
  9692. end
  9693. else if (taicpu(p).opsize = S_WL) and
  9694. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9695. begin
  9696. TargetSize := S_W;
  9697. setsubreg(ThisReg, R_SUBW);
  9698. Result := True;
  9699. end;
  9700. if Result then
  9701. begin
  9702. { Convert the input MOVZX to a MOV }
  9703. if (taicpu(p).oper[0]^.typ = top_reg) and
  9704. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9705. begin
  9706. { Or remove it completely! }
  9707. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9708. RemoveCurrentP(p);
  9709. p_removed := True;
  9710. end
  9711. else
  9712. begin
  9713. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9714. taicpu(p).opcode := A_MOV;
  9715. taicpu(p).oper[1]^.reg := ThisReg;
  9716. taicpu(p).opsize := TargetSize;
  9717. end;
  9718. end;
  9719. end;
  9720. end;
  9721. end;
  9722. procedure AdjustFinalLoad;
  9723. begin
  9724. if not LowerUnsignedOverflow then
  9725. begin
  9726. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9727. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9728. begin
  9729. { Convert the output MOVZX to a MOV }
  9730. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9731. begin
  9732. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9733. if (MinSize = S_B) or
  9734. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9735. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9736. begin
  9737. { Remove it completely! }
  9738. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9739. { Be careful; if p = hp1 and p was also removed, p
  9740. will become a dangling pointer }
  9741. if p = hp1 then
  9742. begin
  9743. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9744. p_removed := True;
  9745. end
  9746. else
  9747. RemoveInstruction(hp1);
  9748. hp1_removed := True;
  9749. end;
  9750. end
  9751. else
  9752. begin
  9753. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9754. taicpu(hp1).opcode := A_MOV;
  9755. taicpu(hp1).oper[0]^.reg := ThisReg;
  9756. taicpu(hp1).opsize := TargetSize;
  9757. end;
  9758. end
  9759. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9760. begin
  9761. { Need to change the size of the output }
  9762. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9763. taicpu(hp1).oper[0]^.reg := ThisReg;
  9764. taicpu(hp1).opsize := S_BL;
  9765. end;
  9766. end;
  9767. end;
  9768. function CompressInstructions: Boolean;
  9769. var
  9770. LocalIndex: Integer;
  9771. begin
  9772. Result := False;
  9773. { The objective here is to try to find a combination that
  9774. removes one of the MOV/Z instructions. }
  9775. if (
  9776. (taicpu(p).oper[0]^.typ <> top_reg) or
  9777. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9778. ) and
  9779. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9780. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9781. begin
  9782. { Make a preference to remove the second MOVZX instruction }
  9783. case taicpu(hp1).opsize of
  9784. S_BL, S_WL:
  9785. begin
  9786. TargetSize := S_L;
  9787. TargetSubReg := R_SUBD;
  9788. end;
  9789. S_BW:
  9790. begin
  9791. TargetSize := S_W;
  9792. TargetSubReg := R_SUBW;
  9793. end;
  9794. else
  9795. InternalError(2020112302);
  9796. end;
  9797. end
  9798. else
  9799. begin
  9800. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9801. begin
  9802. { Exceeded lower bound but not upper bound }
  9803. TargetSize := MaxSize;
  9804. end
  9805. else if not LowerUnsignedOverflow then
  9806. begin
  9807. { Size didn't exceed lower bound }
  9808. TargetSize := MinSize;
  9809. end
  9810. else
  9811. Exit;
  9812. end;
  9813. case TargetSize of
  9814. S_B:
  9815. TargetSubReg := R_SUBL;
  9816. S_W:
  9817. TargetSubReg := R_SUBW;
  9818. S_L:
  9819. TargetSubReg := R_SUBD;
  9820. else
  9821. InternalError(2020112350);
  9822. end;
  9823. { Update the register to its new size }
  9824. setsubreg(ThisReg, TargetSubReg);
  9825. RegInUse := False;
  9826. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9827. begin
  9828. { Check to see if the active register is used afterwards;
  9829. if not, we can change it and make a saving. }
  9830. TransferUsedRegs(TmpUsedRegs);
  9831. { The target register may be marked as in use to cross
  9832. a jump to a distant label, so exclude it }
  9833. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9834. hp2 := p;
  9835. repeat
  9836. { Explicitly check for the excluded register (don't include the first
  9837. instruction as it may be reading from here }
  9838. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9839. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9840. begin
  9841. RegInUse := True;
  9842. Break;
  9843. end;
  9844. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9845. if not GetNextInstruction(hp2, hp2) then
  9846. InternalError(2020112340);
  9847. until (hp2 = hp1);
  9848. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9849. { We might still be able to get away with this }
  9850. RegInUse := not
  9851. (
  9852. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9853. (hp2.typ = ait_instruction) and
  9854. (
  9855. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9856. instruction that doesn't actually contain ThisReg }
  9857. (cs_opt_level3 in current_settings.optimizerswitches) or
  9858. RegInInstruction(ThisReg, hp2)
  9859. ) and
  9860. RegLoadedWithNewValue(ThisReg, hp2)
  9861. );
  9862. if not RegInUse then
  9863. begin
  9864. { Force the register size to the same as this instruction so it can be removed}
  9865. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9866. begin
  9867. TargetSize := S_L;
  9868. TargetSubReg := R_SUBD;
  9869. end
  9870. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9871. begin
  9872. TargetSize := S_W;
  9873. TargetSubReg := R_SUBW;
  9874. end;
  9875. ThisReg := taicpu(hp1).oper[1]^.reg;
  9876. setsubreg(ThisReg, TargetSubReg);
  9877. RegChanged := True;
  9878. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9879. TransferUsedRegs(TmpUsedRegs);
  9880. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9881. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9882. if p = hp1 then
  9883. begin
  9884. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9885. p_removed := True;
  9886. end
  9887. else
  9888. RemoveInstruction(hp1);
  9889. hp1_removed := True;
  9890. { Instruction will become "mov %reg,%reg" }
  9891. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9892. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9893. begin
  9894. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9895. RemoveCurrentP(p);
  9896. p_removed := True;
  9897. end
  9898. else
  9899. taicpu(p).oper[1]^.reg := ThisReg;
  9900. Result := True;
  9901. end
  9902. else
  9903. begin
  9904. if TargetSize <> MaxSize then
  9905. begin
  9906. { Since the register is in use, we have to force it to
  9907. MaxSize otherwise part of it may become undefined later on }
  9908. TargetSize := MaxSize;
  9909. case TargetSize of
  9910. S_B:
  9911. TargetSubReg := R_SUBL;
  9912. S_W:
  9913. TargetSubReg := R_SUBW;
  9914. S_L:
  9915. TargetSubReg := R_SUBD;
  9916. else
  9917. InternalError(2020112351);
  9918. end;
  9919. setsubreg(ThisReg, TargetSubReg);
  9920. end;
  9921. AdjustFinalLoad;
  9922. end;
  9923. end
  9924. else
  9925. AdjustFinalLoad;
  9926. Result := AdjustInitialLoadAndSize or Result;
  9927. { Now go through every instruction we found and change the
  9928. size. If TargetSize = MaxSize, then almost no changes are
  9929. needed and Result can remain False if it hasn't been set
  9930. yet.
  9931. If RegChanged is True, then the register requires changing
  9932. and so the point about TargetSize = MaxSize doesn't apply. }
  9933. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9934. begin
  9935. for LocalIndex := 0 to InstrMax do
  9936. begin
  9937. { If p_removed is true, then the original MOV/Z was removed
  9938. and removing the AND instruction may not be safe if it
  9939. appears first }
  9940. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9941. InternalError(2020112310);
  9942. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9943. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9944. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9945. InstrList[LocalIndex].opsize := TargetSize;
  9946. end;
  9947. Result := True;
  9948. end;
  9949. end;
  9950. begin
  9951. Result := False;
  9952. p_removed := False;
  9953. hp1_removed := False;
  9954. ThisReg := taicpu(p).oper[1]^.reg;
  9955. { Check for:
  9956. movs/z ###,%ecx (or %cx or %rcx)
  9957. ...
  9958. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9959. (dealloc %ecx)
  9960. Change to:
  9961. mov ###,%cl (if ### = %cl, then remove completely)
  9962. ...
  9963. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9964. }
  9965. if (getsupreg(ThisReg) = RS_ECX) and
  9966. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9967. (hp1.typ = ait_instruction) and
  9968. (
  9969. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9970. instruction that doesn't actually contain ECX }
  9971. (cs_opt_level3 in current_settings.optimizerswitches) or
  9972. RegInInstruction(NR_ECX, hp1) or
  9973. (
  9974. { It's common for the shift/rotate's read/write register to be
  9975. initialised in between, so under -O2 and under, search ahead
  9976. one more instruction
  9977. }
  9978. GetNextInstruction(hp1, hp1) and
  9979. (hp1.typ = ait_instruction) and
  9980. RegInInstruction(NR_ECX, hp1)
  9981. )
  9982. ) and
  9983. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9984. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9985. begin
  9986. TransferUsedRegs(TmpUsedRegs);
  9987. hp2 := p;
  9988. repeat
  9989. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9990. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9991. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9992. begin
  9993. case taicpu(p).opsize of
  9994. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9995. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9996. begin
  9997. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9998. RemoveCurrentP(p);
  9999. end
  10000. else
  10001. begin
  10002. taicpu(p).opcode := A_MOV;
  10003. taicpu(p).opsize := S_B;
  10004. taicpu(p).oper[1]^.reg := NR_CL;
  10005. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10006. end;
  10007. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10008. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10009. begin
  10010. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10011. RemoveCurrentP(p);
  10012. end
  10013. else
  10014. begin
  10015. taicpu(p).opcode := A_MOV;
  10016. taicpu(p).opsize := S_W;
  10017. taicpu(p).oper[1]^.reg := NR_CX;
  10018. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10019. end;
  10020. {$ifdef x86_64}
  10021. S_LQ:
  10022. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10023. begin
  10024. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10025. RemoveCurrentP(p);
  10026. end
  10027. else
  10028. begin
  10029. taicpu(p).opcode := A_MOV;
  10030. taicpu(p).opsize := S_L;
  10031. taicpu(p).oper[1]^.reg := NR_ECX;
  10032. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10033. end;
  10034. {$endif x86_64}
  10035. else
  10036. InternalError(2021120401);
  10037. end;
  10038. Result := True;
  10039. Exit;
  10040. end;
  10041. end;
  10042. { This is anything but quick! }
  10043. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10044. Exit;
  10045. SetLength(InstrList, 0);
  10046. InstrMax := -1;
  10047. case taicpu(p).opsize of
  10048. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10049. begin
  10050. {$if defined(i386) or defined(i8086)}
  10051. { If the target size is 8-bit, make sure we can actually encode it }
  10052. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10053. Exit;
  10054. {$endif i386 or i8086}
  10055. LowerLimit := $FF;
  10056. SignedLowerLimit := $7F;
  10057. SignedLowerLimitBottom := -128;
  10058. MinSize := S_B;
  10059. if taicpu(p).opsize = S_BW then
  10060. begin
  10061. MaxSize := S_W;
  10062. UpperLimit := $FFFF;
  10063. SignedUpperLimit := $7FFF;
  10064. SignedUpperLimitBottom := -32768;
  10065. end
  10066. else
  10067. begin
  10068. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10069. MaxSize := S_L;
  10070. UpperLimit := $FFFFFFFF;
  10071. SignedUpperLimit := $7FFFFFFF;
  10072. SignedUpperLimitBottom := -2147483648;
  10073. end;
  10074. end;
  10075. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10076. begin
  10077. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10078. LowerLimit := $FFFF;
  10079. SignedLowerLimit := $7FFF;
  10080. SignedLowerLimitBottom := -32768;
  10081. UpperLimit := $FFFFFFFF;
  10082. SignedUpperLimit := $7FFFFFFF;
  10083. SignedUpperLimitBottom := -2147483648;
  10084. MinSize := S_W;
  10085. MaxSize := S_L;
  10086. end;
  10087. {$ifdef x86_64}
  10088. S_LQ:
  10089. begin
  10090. { Both the lower and upper limits are set to 32-bit. If a limit
  10091. is breached, then optimisation is impossible }
  10092. LowerLimit := $FFFFFFFF;
  10093. SignedLowerLimit := $7FFFFFFF;
  10094. SignedLowerLimitBottom := -2147483648;
  10095. UpperLimit := $FFFFFFFF;
  10096. SignedUpperLimit := $7FFFFFFF;
  10097. SignedUpperLimitBottom := -2147483648;
  10098. MinSize := S_L;
  10099. MaxSize := S_L;
  10100. end;
  10101. {$endif x86_64}
  10102. else
  10103. InternalError(2020112301);
  10104. end;
  10105. TestValMin := 0;
  10106. TestValMax := LowerLimit;
  10107. TestValSignedMax := SignedLowerLimit;
  10108. TryShiftDownLimit := LowerLimit;
  10109. TryShiftDown := S_NO;
  10110. ShiftDownOverflow := False;
  10111. RegChanged := False;
  10112. BitwiseOnly := True;
  10113. OrXorUsed := False;
  10114. UpperSignedOverflow := False;
  10115. LowerSignedOverflow := False;
  10116. UpperUnsignedOverflow := False;
  10117. LowerUnsignedOverflow := False;
  10118. hp1 := p;
  10119. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10120. (hp1.typ = ait_instruction) and
  10121. (
  10122. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10123. instruction that doesn't actually contain ThisReg }
  10124. (cs_opt_level3 in current_settings.optimizerswitches) or
  10125. { This allows this Movx optimisation to work through the SETcc instructions
  10126. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10127. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10128. skip over these SETcc instructions). }
  10129. (taicpu(hp1).opcode = A_SETcc) or
  10130. RegInInstruction(ThisReg, hp1)
  10131. ) do
  10132. begin
  10133. case taicpu(hp1).opcode of
  10134. A_INC,A_DEC:
  10135. begin
  10136. { Has to be an exact match on the register }
  10137. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10138. Break;
  10139. if taicpu(hp1).opcode = A_INC then
  10140. begin
  10141. Inc(TestValMin);
  10142. Inc(TestValMax);
  10143. Inc(TestValSignedMax);
  10144. end
  10145. else
  10146. begin
  10147. Dec(TestValMin);
  10148. Dec(TestValMax);
  10149. Dec(TestValSignedMax);
  10150. end;
  10151. end;
  10152. A_TEST, A_CMP:
  10153. begin
  10154. if (
  10155. { Too high a risk of non-linear behaviour that breaks DFA
  10156. here, unless it's cmp $0,%reg, which is equivalent to
  10157. test %reg,%reg }
  10158. OrXorUsed and
  10159. (taicpu(hp1).opcode = A_CMP) and
  10160. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10161. ) or
  10162. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10163. { Has to be an exact match on the register }
  10164. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10165. (
  10166. { Permit "test %reg,%reg" }
  10167. (taicpu(hp1).opcode = A_TEST) and
  10168. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10169. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10170. ) or
  10171. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10172. { Make sure the comparison value is not smaller than the
  10173. smallest allowed signed value for the minimum size (e.g.
  10174. -128 for 8-bit) }
  10175. not (
  10176. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10177. { Is it in the negative range? }
  10178. (
  10179. (taicpu(hp1).oper[0]^.val < 0) and
  10180. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10181. )
  10182. ) then
  10183. Break;
  10184. { Check to see if the active register is used afterwards }
  10185. TransferUsedRegs(TmpUsedRegs);
  10186. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10187. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10188. begin
  10189. { Make sure the comparison or any previous instructions
  10190. hasn't pushed the test values outside of the range of
  10191. MinSize }
  10192. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10193. begin
  10194. { Exceeded lower bound but not upper bound }
  10195. Exit;
  10196. end
  10197. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10198. begin
  10199. { Size didn't exceed lower bound }
  10200. TargetSize := MinSize;
  10201. end
  10202. else
  10203. Break;
  10204. case TargetSize of
  10205. S_B:
  10206. TargetSubReg := R_SUBL;
  10207. S_W:
  10208. TargetSubReg := R_SUBW;
  10209. S_L:
  10210. TargetSubReg := R_SUBD;
  10211. else
  10212. InternalError(2021051002);
  10213. end;
  10214. if TargetSize <> MaxSize then
  10215. begin
  10216. { Update the register to its new size }
  10217. setsubreg(ThisReg, TargetSubReg);
  10218. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10219. taicpu(hp1).oper[1]^.reg := ThisReg;
  10220. taicpu(hp1).opsize := TargetSize;
  10221. { Convert the input MOVZX to a MOV if necessary }
  10222. AdjustInitialLoadAndSize;
  10223. if (InstrMax >= 0) then
  10224. begin
  10225. for Index := 0 to InstrMax do
  10226. begin
  10227. { If p_removed is true, then the original MOV/Z was removed
  10228. and removing the AND instruction may not be safe if it
  10229. appears first }
  10230. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10231. InternalError(2020112311);
  10232. if InstrList[Index].oper[0]^.typ = top_reg then
  10233. InstrList[Index].oper[0]^.reg := ThisReg;
  10234. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10235. InstrList[Index].opsize := MinSize;
  10236. end;
  10237. end;
  10238. Result := True;
  10239. end;
  10240. Exit;
  10241. end;
  10242. end;
  10243. A_SETcc:
  10244. begin
  10245. { This allows this Movx optimisation to work through the SETcc instructions
  10246. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10247. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10248. skip over these SETcc instructions). }
  10249. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10250. { Of course, break out if the current register is used }
  10251. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10252. Break
  10253. else
  10254. { We must use Continue so the instruction doesn't get added
  10255. to InstrList }
  10256. Continue;
  10257. end;
  10258. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10259. begin
  10260. if
  10261. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10262. { Has to be an exact match on the register }
  10263. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10264. (
  10265. (
  10266. (taicpu(hp1).oper[0]^.typ = top_const) and
  10267. (
  10268. (
  10269. (taicpu(hp1).opcode = A_SHL) and
  10270. (
  10271. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10272. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10273. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10274. )
  10275. ) or (
  10276. (taicpu(hp1).opcode <> A_SHL) and
  10277. (
  10278. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10279. { Is it in the negative range? }
  10280. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10281. )
  10282. )
  10283. )
  10284. ) or (
  10285. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10286. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10287. )
  10288. ) then
  10289. Break;
  10290. { Only process OR and XOR if there are only bitwise operations,
  10291. since otherwise they can too easily fool the data flow
  10292. analysis (they can cause non-linear behaviour) }
  10293. case taicpu(hp1).opcode of
  10294. A_ADD:
  10295. begin
  10296. if OrXorUsed then
  10297. { Too high a risk of non-linear behaviour that breaks DFA here }
  10298. Break
  10299. else
  10300. BitwiseOnly := False;
  10301. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10302. begin
  10303. TestValMin := TestValMin * 2;
  10304. TestValMax := TestValMax * 2;
  10305. TestValSignedMax := TestValSignedMax * 2;
  10306. end
  10307. else
  10308. begin
  10309. WorkingValue := taicpu(hp1).oper[0]^.val;
  10310. TestValMin := TestValMin + WorkingValue;
  10311. TestValMax := TestValMax + WorkingValue;
  10312. TestValSignedMax := TestValSignedMax + WorkingValue;
  10313. end;
  10314. end;
  10315. A_SUB:
  10316. begin
  10317. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10318. begin
  10319. TestValMin := 0;
  10320. TestValMax := 0;
  10321. TestValSignedMax := 0;
  10322. end
  10323. else
  10324. begin
  10325. if OrXorUsed then
  10326. { Too high a risk of non-linear behaviour that breaks DFA here }
  10327. Break
  10328. else
  10329. BitwiseOnly := False;
  10330. WorkingValue := taicpu(hp1).oper[0]^.val;
  10331. TestValMin := TestValMin - WorkingValue;
  10332. TestValMax := TestValMax - WorkingValue;
  10333. TestValSignedMax := TestValSignedMax - WorkingValue;
  10334. end;
  10335. end;
  10336. A_AND:
  10337. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10338. begin
  10339. { we might be able to go smaller if AND appears first }
  10340. if InstrMax = -1 then
  10341. case MinSize of
  10342. S_B:
  10343. ;
  10344. S_W:
  10345. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10346. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10347. begin
  10348. TryShiftDown := S_B;
  10349. TryShiftDownLimit := $FF;
  10350. end;
  10351. S_L:
  10352. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10353. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10354. begin
  10355. TryShiftDown := S_B;
  10356. TryShiftDownLimit := $FF;
  10357. end
  10358. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10359. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10360. begin
  10361. TryShiftDown := S_W;
  10362. TryShiftDownLimit := $FFFF;
  10363. end;
  10364. else
  10365. InternalError(2020112320);
  10366. end;
  10367. WorkingValue := taicpu(hp1).oper[0]^.val;
  10368. TestValMin := TestValMin and WorkingValue;
  10369. TestValMax := TestValMax and WorkingValue;
  10370. TestValSignedMax := TestValSignedMax and WorkingValue;
  10371. end;
  10372. A_OR:
  10373. begin
  10374. if not BitwiseOnly then
  10375. Break;
  10376. OrXorUsed := True;
  10377. WorkingValue := taicpu(hp1).oper[0]^.val;
  10378. TestValMin := TestValMin or WorkingValue;
  10379. TestValMax := TestValMax or WorkingValue;
  10380. TestValSignedMax := TestValSignedMax or WorkingValue;
  10381. end;
  10382. A_XOR:
  10383. begin
  10384. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10385. begin
  10386. TestValMin := 0;
  10387. TestValMax := 0;
  10388. TestValSignedMax := 0;
  10389. end
  10390. else
  10391. begin
  10392. if not BitwiseOnly then
  10393. Break;
  10394. OrXorUsed := True;
  10395. WorkingValue := taicpu(hp1).oper[0]^.val;
  10396. TestValMin := TestValMin xor WorkingValue;
  10397. TestValMax := TestValMax xor WorkingValue;
  10398. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10399. end;
  10400. end;
  10401. A_SHL:
  10402. begin
  10403. BitwiseOnly := False;
  10404. WorkingValue := taicpu(hp1).oper[0]^.val;
  10405. TestValMin := TestValMin shl WorkingValue;
  10406. TestValMax := TestValMax shl WorkingValue;
  10407. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10408. end;
  10409. A_SHR,
  10410. { The first instruction was MOVZX, so the value won't be negative }
  10411. A_SAR:
  10412. begin
  10413. if InstrMax <> -1 then
  10414. BitwiseOnly := False
  10415. else
  10416. { we might be able to go smaller if SHR appears first }
  10417. case MinSize of
  10418. S_B:
  10419. ;
  10420. S_W:
  10421. if (taicpu(hp1).oper[0]^.val >= 8) then
  10422. begin
  10423. TryShiftDown := S_B;
  10424. TryShiftDownLimit := $FF;
  10425. TryShiftDownSignedLimit := $7F;
  10426. TryShiftDownSignedLimitLower := -128;
  10427. end;
  10428. S_L:
  10429. if (taicpu(hp1).oper[0]^.val >= 24) then
  10430. begin
  10431. TryShiftDown := S_B;
  10432. TryShiftDownLimit := $FF;
  10433. TryShiftDownSignedLimit := $7F;
  10434. TryShiftDownSignedLimitLower := -128;
  10435. end
  10436. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10437. begin
  10438. TryShiftDown := S_W;
  10439. TryShiftDownLimit := $FFFF;
  10440. TryShiftDownSignedLimit := $7FFF;
  10441. TryShiftDownSignedLimitLower := -32768;
  10442. end;
  10443. else
  10444. InternalError(2020112321);
  10445. end;
  10446. WorkingValue := taicpu(hp1).oper[0]^.val;
  10447. if taicpu(hp1).opcode = A_SAR then
  10448. begin
  10449. TestValMin := SarInt64(TestValMin, WorkingValue);
  10450. TestValMax := SarInt64(TestValMax, WorkingValue);
  10451. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10452. end
  10453. else
  10454. begin
  10455. TestValMin := TestValMin shr WorkingValue;
  10456. TestValMax := TestValMax shr WorkingValue;
  10457. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10458. end;
  10459. end;
  10460. else
  10461. InternalError(2020112303);
  10462. end;
  10463. end;
  10464. (*
  10465. A_IMUL:
  10466. case taicpu(hp1).ops of
  10467. 2:
  10468. begin
  10469. if not MatchOpType(hp1, top_reg, top_reg) or
  10470. { Has to be an exact match on the register }
  10471. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10472. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10473. Break;
  10474. TestValMin := TestValMin * TestValMin;
  10475. TestValMax := TestValMax * TestValMax;
  10476. TestValSignedMax := TestValSignedMax * TestValMax;
  10477. end;
  10478. 3:
  10479. begin
  10480. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10481. { Has to be an exact match on the register }
  10482. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10483. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10484. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10485. { Is it in the negative range? }
  10486. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10487. Break;
  10488. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10489. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10490. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10491. end;
  10492. else
  10493. Break;
  10494. end;
  10495. A_IDIV:
  10496. case taicpu(hp1).ops of
  10497. 3:
  10498. begin
  10499. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10500. { Has to be an exact match on the register }
  10501. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10502. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10503. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10504. { Is it in the negative range? }
  10505. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10506. Break;
  10507. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10508. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10509. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10510. end;
  10511. else
  10512. Break;
  10513. end;
  10514. *)
  10515. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10516. begin
  10517. { If there are no instructions in between, then we might be able to make a saving }
  10518. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10519. Break;
  10520. { We have something like:
  10521. movzbw %dl,%dx
  10522. ...
  10523. movswl %dx,%edx
  10524. Change the latter to a zero-extension then enter the
  10525. A_MOVZX case branch.
  10526. }
  10527. {$ifdef x86_64}
  10528. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10529. begin
  10530. { this becomes a zero extension from 32-bit to 64-bit, but
  10531. the upper 32 bits are already zero, so just delete the
  10532. instruction }
  10533. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10534. RemoveInstruction(hp1);
  10535. Result := True;
  10536. Exit;
  10537. end
  10538. else
  10539. {$endif x86_64}
  10540. begin
  10541. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10542. taicpu(hp1).opcode := A_MOVZX;
  10543. {$ifdef x86_64}
  10544. case taicpu(hp1).opsize of
  10545. S_BQ:
  10546. begin
  10547. taicpu(hp1).opsize := S_BL;
  10548. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10549. end;
  10550. S_WQ:
  10551. begin
  10552. taicpu(hp1).opsize := S_WL;
  10553. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10554. end;
  10555. S_LQ:
  10556. begin
  10557. taicpu(hp1).opcode := A_MOV;
  10558. taicpu(hp1).opsize := S_L;
  10559. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10560. { In this instance, we need to break out because the
  10561. instruction is no longer MOVZX or MOVSXD }
  10562. Result := True;
  10563. Exit;
  10564. end;
  10565. else
  10566. ;
  10567. end;
  10568. {$endif x86_64}
  10569. Result := CompressInstructions;
  10570. Exit;
  10571. end;
  10572. end;
  10573. A_MOVZX:
  10574. begin
  10575. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10576. Break;
  10577. if (InstrMax = -1) then
  10578. begin
  10579. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10580. begin
  10581. { Optimise around i40003 }
  10582. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10583. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10584. {$ifndef x86_64}
  10585. and (
  10586. (taicpu(p).oper[0]^.typ <> top_reg) or
  10587. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10588. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10589. )
  10590. {$endif not x86_64}
  10591. then
  10592. begin
  10593. if (taicpu(p).oper[0]^.typ = top_reg) then
  10594. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10595. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10596. taicpu(p).opsize := S_BL;
  10597. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10598. RemoveInstruction(hp1);
  10599. Result := True;
  10600. Exit;
  10601. end;
  10602. end
  10603. else
  10604. begin
  10605. { Will return false if the second parameter isn't ThisReg
  10606. (can happen on -O2 and under) }
  10607. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10608. begin
  10609. { The two MOVZX instructions are adjacent, so remove the first one }
  10610. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10611. RemoveCurrentP(p);
  10612. Result := True;
  10613. Exit;
  10614. end;
  10615. Break;
  10616. end;
  10617. end;
  10618. Result := CompressInstructions;
  10619. Exit;
  10620. end;
  10621. else
  10622. { This includes ADC, SBB and IDIV }
  10623. Break;
  10624. end;
  10625. if not CheckOverflowConditions then
  10626. Break;
  10627. { Contains highest index (so instruction count - 1) }
  10628. Inc(InstrMax);
  10629. if InstrMax > High(InstrList) then
  10630. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10631. InstrList[InstrMax] := taicpu(hp1);
  10632. end;
  10633. end;
  10634. {$pop}
  10635. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10636. var
  10637. hp1 : tai;
  10638. begin
  10639. Result:=false;
  10640. if (taicpu(p).ops >= 2) and
  10641. ((taicpu(p).oper[0]^.typ = top_const) or
  10642. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10643. (taicpu(p).oper[1]^.typ = top_reg) and
  10644. ((taicpu(p).ops = 2) or
  10645. ((taicpu(p).oper[2]^.typ = top_reg) and
  10646. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10647. GetLastInstruction(p,hp1) and
  10648. MatchInstruction(hp1,A_MOV,[]) and
  10649. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10650. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10651. begin
  10652. TransferUsedRegs(TmpUsedRegs);
  10653. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10654. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10655. { change
  10656. mov reg1,reg2
  10657. imul y,reg2 to imul y,reg1,reg2 }
  10658. begin
  10659. taicpu(p).ops := 3;
  10660. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10661. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10662. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10663. RemoveInstruction(hp1);
  10664. result:=true;
  10665. end;
  10666. end;
  10667. end;
  10668. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10669. var
  10670. ThisLabel: TAsmLabel;
  10671. begin
  10672. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10673. ThisLabel.decrefs;
  10674. taicpu(p).condition := C_None;
  10675. taicpu(p).opcode := A_RET;
  10676. taicpu(p).is_jmp := false;
  10677. taicpu(p).ops := taicpu(ret_p).ops;
  10678. case taicpu(ret_p).ops of
  10679. 0:
  10680. taicpu(p).clearop(0);
  10681. 1:
  10682. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10683. else
  10684. internalerror(2016041301);
  10685. end;
  10686. { If the original label is now dead, it might turn out that the label
  10687. immediately follows p. As a result, everything beyond it, which will
  10688. be just some final register configuration and a RET instruction, is
  10689. now dead code. [Kit] }
  10690. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10691. running RemoveDeadCodeAfterJump for each RET instruction, because
  10692. this optimisation rarely happens and most RETs appear at the end of
  10693. routines where there is nothing that can be stripped. [Kit] }
  10694. if not ThisLabel.is_used then
  10695. RemoveDeadCodeAfterJump(p);
  10696. end;
  10697. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10698. var
  10699. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10700. Unconditional, PotentialModified: Boolean;
  10701. OperPtr: POper;
  10702. NewRef: TReference;
  10703. InstrList: array of taicpu;
  10704. InstrMax, Index: Integer;
  10705. const
  10706. {$ifdef DEBUG_AOPTCPU}
  10707. SNoFlags: shortstring = ' so the flags aren''t modified';
  10708. {$else DEBUG_AOPTCPU}
  10709. SNoFlags = '';
  10710. {$endif DEBUG_AOPTCPU}
  10711. begin
  10712. Result:=false;
  10713. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10714. begin
  10715. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10716. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10717. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10718. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10719. GetNextInstruction(hp1, hp2) and
  10720. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10721. { Change from: To:
  10722. set(C) %reg j(~C) label
  10723. test %reg,%reg/cmp $0,%reg
  10724. je label
  10725. set(C) %reg j(C) label
  10726. test %reg,%reg/cmp $0,%reg
  10727. jne label
  10728. (Also do something similar with sete/setne instead of je/jne)
  10729. }
  10730. begin
  10731. { Before we do anything else, we need to check the instructions
  10732. in between SETcc and TEST to make sure they don't modify the
  10733. FLAGS register - if -O2 or under, there won't be any
  10734. instructions between SET and TEST }
  10735. TransferUsedRegs(TmpUsedRegs);
  10736. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10737. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10738. begin
  10739. next := p;
  10740. SetLength(InstrList, 0);
  10741. InstrMax := -1;
  10742. PotentialModified := False;
  10743. { Make a note of every instruction that modifies the FLAGS
  10744. register }
  10745. while GetNextInstruction(next, next) and (next <> hp1) do
  10746. begin
  10747. if next.typ <> ait_instruction then
  10748. { GetNextInstructionUsingReg should have returned False }
  10749. InternalError(2021051701);
  10750. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10751. begin
  10752. case taicpu(next).opcode of
  10753. A_SETcc,
  10754. A_CMOVcc,
  10755. A_Jcc:
  10756. begin
  10757. if PotentialModified then
  10758. { Not safe because the flags were modified earlier }
  10759. Exit
  10760. else
  10761. { Condition is the same as the initial SETcc, so this is safe
  10762. (don't add to instruction list though) }
  10763. Continue;
  10764. end;
  10765. A_ADD:
  10766. begin
  10767. if (taicpu(next).opsize = S_B) or
  10768. { LEA doesn't support 8-bit operands }
  10769. (taicpu(next).oper[1]^.typ <> top_reg) or
  10770. { Must write to a register }
  10771. (taicpu(next).oper[0]^.typ = top_ref) then
  10772. { Require a constant or a register }
  10773. Exit;
  10774. PotentialModified := True;
  10775. end;
  10776. A_SUB:
  10777. begin
  10778. if (taicpu(next).opsize = S_B) or
  10779. { LEA doesn't support 8-bit operands }
  10780. (taicpu(next).oper[1]^.typ <> top_reg) or
  10781. { Must write to a register }
  10782. (taicpu(next).oper[0]^.typ <> top_const) or
  10783. (taicpu(next).oper[0]^.val = $80000000) then
  10784. { Can't subtract a register with LEA - also
  10785. check that the value isn't -2^31, as this
  10786. can't be negated }
  10787. Exit;
  10788. PotentialModified := True;
  10789. end;
  10790. A_SAL,
  10791. A_SHL:
  10792. begin
  10793. if (taicpu(next).opsize = S_B) or
  10794. { LEA doesn't support 8-bit operands }
  10795. (taicpu(next).oper[1]^.typ <> top_reg) or
  10796. { Must write to a register }
  10797. (taicpu(next).oper[0]^.typ <> top_const) or
  10798. (taicpu(next).oper[0]^.val < 0) or
  10799. (taicpu(next).oper[0]^.val > 3) then
  10800. Exit;
  10801. PotentialModified := True;
  10802. end;
  10803. A_IMUL:
  10804. begin
  10805. if (taicpu(next).ops <> 3) or
  10806. (taicpu(next).oper[1]^.typ <> top_reg) or
  10807. { Must write to a register }
  10808. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10809. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10810. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10811. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10812. Exit
  10813. else
  10814. PotentialModified := True;
  10815. end;
  10816. else
  10817. { Don't know how to change this, so abort }
  10818. Exit;
  10819. end;
  10820. { Contains highest index (so instruction count - 1) }
  10821. Inc(InstrMax);
  10822. if InstrMax > High(InstrList) then
  10823. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10824. InstrList[InstrMax] := taicpu(next);
  10825. end;
  10826. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10827. end;
  10828. if not Assigned(next) or (next <> hp1) then
  10829. { It should be equal to hp1 }
  10830. InternalError(2021051702);
  10831. { Cycle through each instruction and check to see if we can
  10832. change them to versions that don't modify the flags }
  10833. if (InstrMax >= 0) then
  10834. begin
  10835. for Index := 0 to InstrMax do
  10836. case InstrList[Index].opcode of
  10837. A_ADD:
  10838. begin
  10839. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10840. InstrList[Index].opcode := A_LEA;
  10841. reference_reset(NewRef, 1, []);
  10842. NewRef.base := InstrList[Index].oper[1]^.reg;
  10843. if InstrList[Index].oper[0]^.typ = top_reg then
  10844. begin
  10845. NewRef.index := InstrList[Index].oper[0]^.reg;
  10846. NewRef.scalefactor := 1;
  10847. end
  10848. else
  10849. NewRef.offset := InstrList[Index].oper[0]^.val;
  10850. InstrList[Index].loadref(0, NewRef);
  10851. end;
  10852. A_SUB:
  10853. begin
  10854. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10855. InstrList[Index].opcode := A_LEA;
  10856. reference_reset(NewRef, 1, []);
  10857. NewRef.base := InstrList[Index].oper[1]^.reg;
  10858. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10859. InstrList[Index].loadref(0, NewRef);
  10860. end;
  10861. A_SHL,
  10862. A_SAL:
  10863. begin
  10864. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10865. InstrList[Index].opcode := A_LEA;
  10866. reference_reset(NewRef, 1, []);
  10867. NewRef.index := InstrList[Index].oper[1]^.reg;
  10868. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10869. InstrList[Index].loadref(0, NewRef);
  10870. end;
  10871. A_IMUL:
  10872. begin
  10873. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10874. InstrList[Index].opcode := A_LEA;
  10875. reference_reset(NewRef, 1, []);
  10876. NewRef.index := InstrList[Index].oper[1]^.reg;
  10877. case InstrList[Index].oper[0]^.val of
  10878. 2, 4, 8:
  10879. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10880. else {3, 5 and 9}
  10881. begin
  10882. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10883. NewRef.base := InstrList[Index].oper[1]^.reg;
  10884. end;
  10885. end;
  10886. InstrList[Index].loadref(0, NewRef);
  10887. end;
  10888. else
  10889. InternalError(2021051710);
  10890. end;
  10891. end;
  10892. { Mark the FLAGS register as used across this whole block }
  10893. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10894. end;
  10895. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10896. JumpC := taicpu(hp2).condition;
  10897. Unconditional := False;
  10898. if conditions_equal(JumpC, C_E) then
  10899. SetC := inverse_cond(taicpu(p).condition)
  10900. else if conditions_equal(JumpC, C_NE) then
  10901. SetC := taicpu(p).condition
  10902. else
  10903. { We've got something weird here (and inefficent) }
  10904. begin
  10905. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10906. SetC := C_NONE;
  10907. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10908. if condition_in(C_AE, JumpC) then
  10909. Unconditional := True
  10910. else
  10911. { Not sure what to do with this jump - drop out }
  10912. Exit;
  10913. end;
  10914. RemoveInstruction(hp1);
  10915. if Unconditional then
  10916. MakeUnconditional(taicpu(hp2))
  10917. else
  10918. begin
  10919. if SetC = C_NONE then
  10920. InternalError(2018061402);
  10921. taicpu(hp2).SetCondition(SetC);
  10922. end;
  10923. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10924. TmpUsedRegs }
  10925. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10926. begin
  10927. RemoveCurrentp(p, hp2);
  10928. if taicpu(hp2).opcode = A_SETcc then
  10929. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10930. else
  10931. begin
  10932. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10933. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10934. Include(OptsToCheck, aoc_DoPass2JccOpts);
  10935. end;
  10936. end
  10937. else
  10938. if taicpu(hp2).opcode = A_SETcc then
  10939. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10940. else
  10941. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10942. Result := True;
  10943. end
  10944. else if
  10945. { Make sure the instructions are adjacent }
  10946. (
  10947. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10948. GetNextInstruction(p, hp1)
  10949. ) and
  10950. MatchInstruction(hp1, A_MOV, [S_B]) and
  10951. { Writing to memory is allowed }
  10952. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10953. begin
  10954. {
  10955. Watch out for sequences such as:
  10956. set(c)b %regb
  10957. movb %regb,(ref)
  10958. movb $0,1(ref)
  10959. movb $0,2(ref)
  10960. movb $0,3(ref)
  10961. Much more efficient to turn it into:
  10962. movl $0,%regl
  10963. set(c)b %regb
  10964. movl %regl,(ref)
  10965. Or:
  10966. set(c)b %regb
  10967. movzbl %regb,%regl
  10968. movl %regl,(ref)
  10969. }
  10970. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10971. GetNextInstruction(hp1, hp2) and
  10972. MatchInstruction(hp2, A_MOV, [S_B]) and
  10973. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10974. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10975. begin
  10976. { Don't do anything else except set Result to True }
  10977. end
  10978. else
  10979. begin
  10980. if taicpu(p).oper[0]^.typ = top_reg then
  10981. begin
  10982. TransferUsedRegs(TmpUsedRegs);
  10983. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10984. end;
  10985. { If it's not a register, it's a memory address }
  10986. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10987. begin
  10988. { Even if the register is still in use, we can minimise the
  10989. pipeline stall by changing the MOV into another SETcc. }
  10990. taicpu(hp1).opcode := A_SETcc;
  10991. taicpu(hp1).condition := taicpu(p).condition;
  10992. if taicpu(hp1).oper[1]^.typ = top_ref then
  10993. begin
  10994. { Swapping the operand pointers like this is probably a
  10995. bit naughty, but it is far faster than using loadoper
  10996. to transfer the reference from oper[1] to oper[0] if
  10997. you take into account the extra procedure calls and
  10998. the memory allocation and deallocation required }
  10999. OperPtr := taicpu(hp1).oper[1];
  11000. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11001. taicpu(hp1).oper[0] := OperPtr;
  11002. end
  11003. else
  11004. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11005. taicpu(hp1).clearop(1);
  11006. taicpu(hp1).ops := 1;
  11007. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11008. end
  11009. else
  11010. begin
  11011. if taicpu(hp1).oper[1]^.typ = top_reg then
  11012. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11013. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11014. RemoveInstruction(hp1);
  11015. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11016. end
  11017. end;
  11018. Result := True;
  11019. end;
  11020. end;
  11021. end;
  11022. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11023. var
  11024. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11025. TargetReg: TRegister;
  11026. condition, inverted_condition: TAsmCond;
  11027. FoundMOV: Boolean;
  11028. begin
  11029. Result := False;
  11030. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11031. create the most optimial instructions possible due to limited
  11032. register availability, and there are situations where two
  11033. complementary "simple" CMOV blocks are created which, after the fact
  11034. can be merged into a "double" block. For example:
  11035. movw $257,%ax
  11036. movw $2,%r8w
  11037. xorl r9d,%r9d
  11038. testw $16,18(%rcx)
  11039. cmovew %ax,%dx
  11040. cmovew %r8w,%bx
  11041. cmovel %r9d,%r14d
  11042. movw $1283,%ax
  11043. movw $4,%r8w
  11044. movl $9,%r9d
  11045. cmovnew %ax,%dx
  11046. cmovnew %r8w,%bx
  11047. cmovnel %r9d,%r14d
  11048. The CMOVNE instructions at the end can be removed, and the
  11049. destination registers copied into the MOV instructions directly
  11050. above them, before finally being moved to before the first CMOVE
  11051. instructions, to produce:
  11052. movw $257,%ax
  11053. movw $2,%r8w
  11054. xorl r9d,%r9d
  11055. testw $16,18(%rcx)
  11056. movw $1283,%dx
  11057. movw $4,%bx
  11058. movl $9,%r14d
  11059. cmovew %ax,%dx
  11060. cmovew %r8w,%bx
  11061. cmovel %r9d,%r14d
  11062. Which can then be later optimised to:
  11063. movw $257,%ax
  11064. movw $2,%r8w
  11065. xorl r9d,%r9d
  11066. movw $1283,%dx
  11067. movw $4,%bx
  11068. movl $9,%r14d
  11069. testw $16,18(%rcx)
  11070. cmovew %ax,%dx
  11071. cmovew %r8w,%bx
  11072. cmovel %r9d,%r14d
  11073. }
  11074. TargetReg := taicpu(hp1).oper[1]^.reg;
  11075. condition := taicpu(hp1).condition;
  11076. inverted_condition := inverse_cond(condition);
  11077. pFirstMov := nil;
  11078. pLastMov := nil;
  11079. pCMOV := nil;
  11080. if (p.typ = ait_instruction) then
  11081. pCond := p
  11082. else if not GetNextInstruction(p, pCond) then
  11083. InternalError(2024012501);
  11084. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11085. { We should get the CMP or TEST instructeion }
  11086. InternalError(2024012502);
  11087. if (
  11088. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11089. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11090. ) then
  11091. begin
  11092. { We have to tread carefully here, hence why we're not using
  11093. GetNextInstructionUsingReg... we can only accept MOV and other
  11094. CMOV instructions. Anything else and we must drop out}
  11095. hp2 := hp1;
  11096. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11097. begin
  11098. if (hp2.typ <> ait_instruction) then
  11099. Exit;
  11100. case taicpu(hp2).opcode of
  11101. A_MOV:
  11102. begin
  11103. if not Assigned(pFirstMov) then
  11104. pFirstMov := hp2;
  11105. pLastMOV := hp2;
  11106. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11107. { Something different - drop out }
  11108. Exit;
  11109. { Otherwise, leave it for now }
  11110. end;
  11111. A_CMOVcc:
  11112. begin
  11113. if taicpu(hp2).condition = inverted_condition then
  11114. begin
  11115. { We found what we're looking for }
  11116. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11117. begin
  11118. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11119. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11120. begin
  11121. pCMOV := hp2;
  11122. Break;
  11123. end
  11124. else
  11125. { Unsafe reference - drop out }
  11126. Exit;
  11127. end;
  11128. end
  11129. else if taicpu(hp2).condition <> condition then
  11130. { Something weird - drop out }
  11131. Exit;
  11132. end;
  11133. else
  11134. { Invalid }
  11135. Exit;
  11136. end;
  11137. end;
  11138. if not Assigned(pCMOV) then
  11139. { No complementary CMOV found }
  11140. Exit;
  11141. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11142. begin
  11143. { Don't need to do anything special or search for a matching MOV }
  11144. Asml.Remove(pCMOV);
  11145. if RegInInstruction(TargetReg, pCond) then
  11146. { Make sure we don't overwrite the register if it's being used in the condition }
  11147. Asml.InsertAfter(pCMOV, pCond)
  11148. else
  11149. Asml.InsertBefore(pCMOV, pCond);
  11150. taicpu(pCMOV).opcode := A_MOV;
  11151. taicpu(pCMOV).condition := C_None;
  11152. { Don't need to worry about allocating new registers in these cases }
  11153. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11154. Result := True;
  11155. Exit;
  11156. end
  11157. else
  11158. begin
  11159. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11160. FoundMOV := False;
  11161. { Search for the MOV that sets the target register }
  11162. hp2 := pFirstMov;
  11163. repeat
  11164. if (taicpu(hp2).opcode = A_MOV) and
  11165. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11166. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11167. begin
  11168. { Change the destination }
  11169. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11170. if not FoundMOV then
  11171. begin
  11172. FoundMOV := True;
  11173. { Make sure the register is allocated }
  11174. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11175. end;
  11176. hp1 := tai(hp2.Previous);
  11177. Asml.Remove(hp2);
  11178. if RegInInstruction(TargetReg, pCond) then
  11179. { Make sure we don't overwrite the register if it's being used in the condition }
  11180. Asml.InsertAfter(hp2, pCond)
  11181. else
  11182. Asml.InsertBefore(hp2, pCond);
  11183. if (hp2 = pLastMov) then
  11184. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11185. Break;
  11186. hp2 := hp1;
  11187. end;
  11188. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11189. if FoundMOV then
  11190. { Delete the CMOV }
  11191. RemoveInstruction(pCMOV)
  11192. else
  11193. begin
  11194. { If no MOV was found, we have to actually move and transmute the CMOV }
  11195. Asml.Remove(pCMOV);
  11196. if RegInInstruction(TargetReg, pCond) then
  11197. { Make sure we don't overwrite the register if it's being used in the condition }
  11198. Asml.InsertAfter(pCMOV, pCond)
  11199. else
  11200. Asml.InsertBefore(pCMOV, pCond);
  11201. taicpu(pCMOV).opcode := A_MOV;
  11202. taicpu(pCMOV).condition := C_None;
  11203. end;
  11204. Result := True;
  11205. Exit;
  11206. end;
  11207. end;
  11208. end;
  11209. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11210. var
  11211. hp1, hp2, pCond: tai;
  11212. begin
  11213. Result := False;
  11214. { Search ahead for CMOV instructions }
  11215. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11216. begin
  11217. hp1 := p;
  11218. hp2 := p;
  11219. pCond := nil; { To prevent compiler warnings }
  11220. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11221. DEFAULTFLAGS }
  11222. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11223. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11224. pCond := p;
  11225. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11226. begin
  11227. if (hp1.typ <> ait_instruction) then
  11228. { Break out on markers and labels etc. }
  11229. Break;
  11230. case taicpu(hp1).opcode of
  11231. A_MOV:
  11232. { Ignore regular MOVs unless they are obviously not related
  11233. to a CMOV block }
  11234. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11235. Break;
  11236. A_CMOVcc:
  11237. if TryCmpCMovOpts(pCond, hp1) then
  11238. begin
  11239. hp1 := hp2;
  11240. { p itself isn't changed, and we're still inside a
  11241. while loop to catch subsequent CMOVs, so just flag
  11242. a new iteration }
  11243. Include(OptsToCheck, aoc_ForceNewIteration);
  11244. Continue;
  11245. end;
  11246. else
  11247. { Drop out if we find anything else }
  11248. Break;
  11249. end;
  11250. hp2 := hp1;
  11251. end;
  11252. end;
  11253. end;
  11254. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11255. var
  11256. hp1, hp2, pCond: tai;
  11257. begin
  11258. Result := False;
  11259. { Search ahead for CMOV instructions }
  11260. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11261. begin
  11262. hp1 := p;
  11263. hp2 := p;
  11264. pCond := nil; { To prevent compiler warnings }
  11265. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11266. DEFAULTFLAGS }
  11267. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11268. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11269. pCond := p;
  11270. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11271. begin
  11272. if (hp1.typ <> ait_instruction) then
  11273. { Break out on markers and labels etc. }
  11274. Break;
  11275. case taicpu(hp1).opcode of
  11276. A_MOV:
  11277. { Ignore regular MOVs unless they are obviously not related
  11278. to a CMOV block }
  11279. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11280. Break;
  11281. A_CMOVcc:
  11282. if TryCmpCMovOpts(pCond, hp1) then
  11283. begin
  11284. hp1 := hp2;
  11285. { p itself isn't changed, and we're still inside a
  11286. while loop to catch subsequent CMOVs, so just flag
  11287. a new iteration }
  11288. Include(OptsToCheck, aoc_ForceNewIteration);
  11289. Continue;
  11290. end;
  11291. else
  11292. { Drop out if we find anything else }
  11293. Break;
  11294. end;
  11295. hp2 := hp1;
  11296. end;
  11297. end;
  11298. end;
  11299. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11300. var
  11301. hp1: tai;
  11302. Count: Integer;
  11303. OrigLabel: TAsmLabel;
  11304. begin
  11305. result := False;
  11306. { Sometimes, the optimisations below can permit this }
  11307. RemoveDeadCodeAfterJump(p);
  11308. 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
  11309. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11310. begin
  11311. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11312. { Also a side-effect of optimisations }
  11313. if CollapseZeroDistJump(p, OrigLabel) then
  11314. begin
  11315. Result := True;
  11316. Exit;
  11317. end;
  11318. hp1 := GetLabelWithSym(OrigLabel);
  11319. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11320. begin
  11321. if taicpu(hp1).opcode = A_RET then
  11322. begin
  11323. {
  11324. change
  11325. jmp .L1
  11326. ...
  11327. .L1:
  11328. ret
  11329. into
  11330. ret
  11331. }
  11332. begin
  11333. ConvertJumpToRET(p, hp1);
  11334. result:=true;
  11335. end;
  11336. end
  11337. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11338. not (cs_opt_size in current_settings.optimizerswitches) and
  11339. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11340. begin
  11341. Result := True;
  11342. Exit;
  11343. end;
  11344. end;
  11345. end;
  11346. end;
  11347. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11348. begin
  11349. Result := assigned(p) and
  11350. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11351. (taicpu(p).oper[1]^.typ = top_reg) and
  11352. (
  11353. (taicpu(p).oper[0]^.typ = top_reg) or
  11354. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11355. it is not expected that this can cause a seg. violation }
  11356. (
  11357. (taicpu(p).oper[0]^.typ = top_ref) and
  11358. { TODO: Can we detect which references become constants at this
  11359. stage so we don't have to do a blanket ban? }
  11360. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11361. (
  11362. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11363. (
  11364. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11365. not RefModified and
  11366. { If the reference also appears in the condition, then we know it's safe, otherwise
  11367. any kind of access violation would have occurred already }
  11368. Assigned(cond_p) and
  11369. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11370. (cond_p.typ = ait_instruction) and
  11371. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11372. { Just consider 2-operand comparison instructions for now to be safe }
  11373. (taicpu(cond_p).ops = 2) and
  11374. (
  11375. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11376. (
  11377. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11378. { Don't risk identical registers but different offsets, as we may have constructs
  11379. such as buffer streams with things like length fields that indicate whether
  11380. any more data follows. And there are probably some contrived examples where
  11381. writing to offsets behind the one being read also lead to access violations }
  11382. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11383. (
  11384. { Check that we're not modifying a register that appears in the reference }
  11385. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11386. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11387. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11388. )
  11389. )
  11390. )
  11391. )
  11392. )
  11393. )
  11394. );
  11395. end;
  11396. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11397. begin
  11398. { Update integer registers, ignoring deallocations }
  11399. repeat
  11400. while assigned(p) and
  11401. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11402. (p.typ = ait_label) or
  11403. ((p.typ = ait_marker) and
  11404. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11405. p := tai(p.next);
  11406. while assigned(p) and
  11407. (p.typ=ait_RegAlloc) Do
  11408. begin
  11409. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11410. begin
  11411. case tai_regalloc(p).ratype of
  11412. ra_alloc :
  11413. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11414. else
  11415. ;
  11416. end;
  11417. end;
  11418. p := tai(p.next);
  11419. end;
  11420. until not(assigned(p)) or
  11421. (not(p.typ in SkipInstr) and
  11422. not((p.typ = ait_label) and
  11423. labelCanBeSkipped(tai_label(p))));
  11424. end;
  11425. {$ifndef 8086}
  11426. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11427. begin
  11428. Result := False;
  11429. EndJump := nil;
  11430. BlockStop := nil;
  11431. while (BlockStart <> fOptimizer.BlockEnd) and
  11432. { stop on labels }
  11433. (BlockStart.typ <> ait_label) do
  11434. begin
  11435. { Keep track of all integer registers that are used }
  11436. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11437. if BlockStart.typ = ait_instruction then
  11438. begin
  11439. if (taicpu(BlockStart).opcode = A_JMP) then
  11440. begin
  11441. if not IsJumpToLabel(taicpu(BlockStart)) or
  11442. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11443. Exit;
  11444. EndJump := BlockStart;
  11445. Break;
  11446. end
  11447. { Check to see if we have a valid MOV instruction instead }
  11448. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11449. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11450. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11451. begin
  11452. Exit;
  11453. end
  11454. else
  11455. { This will be a valid MOV }
  11456. fAllocationRange := BlockStart;
  11457. end;
  11458. OneBeforeBlock := BlockStart;
  11459. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11460. end;
  11461. if (BlockStart = fOptimizer.BlockEnd) then
  11462. Exit;
  11463. BlockStop := BlockStart;
  11464. Result := True;
  11465. end;
  11466. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11467. var
  11468. hp1: tai;
  11469. RefModified: Boolean;
  11470. begin
  11471. Result := 0;
  11472. hp1 := BlockStart;
  11473. RefModified := False; { As long as the condition is inverted, this can be reset }
  11474. while assigned(hp1) and
  11475. (hp1 <> BlockStop) do
  11476. begin
  11477. case hp1.typ of
  11478. ait_instruction:
  11479. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11480. begin
  11481. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11482. begin
  11483. Inc(Result);
  11484. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11485. Assigned(fCondition) and
  11486. { Will have 2 operands }
  11487. (
  11488. (
  11489. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11490. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11491. ) or
  11492. (
  11493. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11494. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11495. )
  11496. ) then
  11497. { It is no longer safe to use the reference in the condition.
  11498. this prevents problems such as:
  11499. mov (%reg),%reg
  11500. mov (%reg),...
  11501. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11502. (fixes #40165)
  11503. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11504. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11505. }
  11506. RefModified := True;
  11507. end
  11508. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11509. { CMOV with constants grows the code size }
  11510. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11511. begin
  11512. { Register was reserved by TryCMOVConst and
  11513. stored on ConstRegs }
  11514. end
  11515. else
  11516. begin
  11517. Result := -1;
  11518. Exit;
  11519. end;
  11520. end
  11521. else
  11522. begin
  11523. Result := -1;
  11524. Exit;
  11525. end;
  11526. else
  11527. { Most likely an align };
  11528. end;
  11529. fOptimizer.GetNextInstruction(hp1, hp1);
  11530. end;
  11531. end;
  11532. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11533. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11534. (this is done as a separate stage because the double types are extensions of the branching type,
  11535. but we can't discount the conditional jump until the last step) }
  11536. procedure EvaluateBranchingType;
  11537. begin
  11538. Inc(CMOVScore);
  11539. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11540. { Too many instructions to be worthwhile }
  11541. fState := tsInvalid;
  11542. end;
  11543. var
  11544. hp1: tai;
  11545. Count: Integer;
  11546. begin
  11547. { Table of valid CMOV block types
  11548. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11549. ---------- --------- --------- --------- --------- ---------
  11550. tsSimple X Yes X X X
  11551. tsDetour = 1st X X X X
  11552. tsBranching <> Mid Yes X X X
  11553. tsDouble End-label Yes * Yes X Yes
  11554. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11555. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11556. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11557. * Only one reference allowed
  11558. }
  11559. hp1 := nil; { To prevent compiler warnings }
  11560. Optimizer.CopyUsedRegs(RegisterTracking);
  11561. fOptimizer := Optimizer;
  11562. fLabel := AFirstLabel;
  11563. CMOVScore := 0;
  11564. ConstCount := 0;
  11565. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11566. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11567. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11568. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11569. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11570. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11571. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11572. fInsertionPoint := p_initialjump;
  11573. fCondition := nil;
  11574. fInitialJump := p_initialjump;
  11575. fFirstMovBlock := p_initialmov;
  11576. fFirstMovBlockStop := nil;
  11577. fSecondJump := nil;
  11578. fSecondMovBlock := nil;
  11579. fSecondMovBlockStop := nil;
  11580. fMidLabel := nil;
  11581. fSecondJump := nil;
  11582. fSecondMovBlock := nil;
  11583. fEndLabel := nil;
  11584. fAllocationRange := nil;
  11585. { Assume it all goes horribly wrong! }
  11586. fState := tsInvalid;
  11587. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11588. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11589. 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
  11590. begin
  11591. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11592. for Count := 0 to 1 do
  11593. with taicpu(fCondition).oper[Count]^ do
  11594. case typ of
  11595. top_reg:
  11596. if getregtype(reg) = R_INTREGISTER then
  11597. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11598. top_ref:
  11599. begin
  11600. if
  11601. {$ifdef x86_64}
  11602. (ref^.base <> NR_RIP) and
  11603. {$endif x86_64}
  11604. (ref^.base <> NR_NO) then
  11605. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11606. if (ref^.index <> NR_NO) then
  11607. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11608. end
  11609. else
  11610. ;
  11611. end;
  11612. { When inserting instructions before hp_prev, try to insert them
  11613. before the allocation of the FLAGS register }
  11614. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11615. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11616. { If not found, set it equal to the condition so it's something sensible }
  11617. fInsertionPoint := fCondition;
  11618. { When dealing with a comparison against zero, take note of the
  11619. instruction before it to see if we can move instructions further
  11620. back in order to benefit PostPeepholeOptTestOr.
  11621. }
  11622. if (
  11623. (
  11624. (taicpu(fCondition).opcode = A_CMP) and
  11625. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11626. ) or
  11627. (
  11628. (taicpu(fCondition).opcode = A_TEST) and
  11629. (
  11630. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11631. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11632. )
  11633. )
  11634. ) and
  11635. Optimizer.GetLastInstruction(fCondition, hp1) then
  11636. begin
  11637. { These instructions set the zero flag if the result is zero }
  11638. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11639. begin
  11640. fInsertionPoint := hp1;
  11641. { Also mark all the registers in this previous instruction
  11642. as 'in use', even if they've just been deallocated }
  11643. for Count := 0 to 1 do
  11644. with taicpu(hp1).oper[Count]^ do
  11645. case typ of
  11646. top_reg:
  11647. if getregtype(reg) = R_INTREGISTER then
  11648. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11649. top_ref:
  11650. begin
  11651. if
  11652. {$ifdef x86_64}
  11653. (ref^.base <> NR_RIP) and
  11654. {$endif x86_64}
  11655. (ref^.base <> NR_NO) then
  11656. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11657. if (ref^.index <> NR_NO) then
  11658. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11659. end
  11660. else
  11661. ;
  11662. end;
  11663. end;
  11664. end;
  11665. end
  11666. else
  11667. fCondition := nil;
  11668. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11669. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11670. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11671. { If not found, set it equal to p so it's something sensible }
  11672. fInsertionPoint := hp1;
  11673. hp1 := p_initialmov;
  11674. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11675. Exit;
  11676. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11677. if (hp1.typ <> ait_label) then { should be on a jump }
  11678. begin
  11679. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11680. { Need a label afterwards }
  11681. Exit;
  11682. end
  11683. else
  11684. fMidLabel := hp1;
  11685. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11686. { Not the correct label }
  11687. fMidLabel := nil;
  11688. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11689. { If there's neither a 2nd jump nor correct label, then it's invalid
  11690. (see above table) }
  11691. Exit;
  11692. { Analyse the first block of MOVs more closely }
  11693. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11694. if Assigned(fSecondJump) then
  11695. begin
  11696. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11697. begin
  11698. fState := tsDetour
  11699. end
  11700. else
  11701. begin
  11702. { Need the correct mid-label for this one }
  11703. if not Assigned(fMidLabel) then
  11704. Exit;
  11705. fState := tsBranching;
  11706. end;
  11707. end
  11708. else
  11709. { No jump. but mid-label is present }
  11710. fState := tsSimple;
  11711. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11712. begin
  11713. { Invalid or too many instructions to be worthwhile }
  11714. fState := tsInvalid;
  11715. Exit;
  11716. end;
  11717. { check further for
  11718. jCC xxx
  11719. <several movs 1>
  11720. jmp yyy
  11721. xxx:
  11722. <several movs 2>
  11723. yyy:
  11724. etc.
  11725. }
  11726. if (fState = tsBranching) and
  11727. { Estimate for required savings for extra jump }
  11728. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11729. { Only one reference is allowed for double blocks }
  11730. (AFirstLabel.getrefs = 1) then
  11731. begin
  11732. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11733. fSecondMovBlock := hp1;
  11734. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11735. begin
  11736. EvaluateBranchingType;
  11737. Exit;
  11738. end;
  11739. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11740. if (hp1.typ <> ait_label) then { should be on a jump }
  11741. begin
  11742. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11743. begin
  11744. { Need a label afterwards }
  11745. EvaluateBranchingType;
  11746. Exit;
  11747. end;
  11748. end
  11749. else
  11750. fEndLabel := hp1;
  11751. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11752. { Second jump doesn't go to the end }
  11753. fEndLabel := nil;
  11754. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11755. begin
  11756. { If there's neither a 3rd jump nor correct end label, then it's
  11757. not a invalid double block, but is a valid single branching
  11758. block (see above table) }
  11759. EvaluateBranchingType;
  11760. Exit;
  11761. end;
  11762. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11763. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11764. { Invalid or too many instructions to be worthwhile }
  11765. Exit;
  11766. Inc(CMOVScore, Count);
  11767. if Assigned(fThirdJump) then
  11768. begin
  11769. if not Assigned(fSecondJump) then
  11770. fState := tsDoubleSecondBranching
  11771. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11772. fState := tsDoubleBranchSame
  11773. else
  11774. fState := tsDoubleBranchDifferent;
  11775. end
  11776. else
  11777. fState := tsDouble;
  11778. end;
  11779. if fState = tsBranching then
  11780. EvaluateBranchingType;
  11781. end;
  11782. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11783. new register to store the constant }
  11784. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11785. var
  11786. RegSize: TSubRegister;
  11787. CurrentVal: TCGInt;
  11788. ANewReg: TRegister;
  11789. X: ShortInt;
  11790. begin
  11791. Result := False;
  11792. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11793. Exit;
  11794. if ConstCount >= MAX_CMOV_REGISTERS then
  11795. { Arrays are full }
  11796. Exit;
  11797. { Remember that CMOV can't encode 8-bit registers }
  11798. case taicpu(p).opsize of
  11799. S_W:
  11800. RegSize := R_SUBW;
  11801. S_L:
  11802. RegSize := R_SUBD;
  11803. {$ifdef x86_64}
  11804. S_Q:
  11805. RegSize := R_SUBQ;
  11806. {$endif x86_64}
  11807. else
  11808. InternalError(2021100401);
  11809. end;
  11810. { See if the value has already been reserved for another CMOV instruction }
  11811. CurrentVal := taicpu(p).oper[0]^.val;
  11812. for X := 0 to ConstCount - 1 do
  11813. if ConstVals[X] = CurrentVal then
  11814. begin
  11815. ConstRegs[ConstCount] := ConstRegs[X];
  11816. ConstSizes[ConstCount] := RegSize;
  11817. ConstVals[ConstCount] := CurrentVal;
  11818. Inc(ConstCount);
  11819. Inc(Count);
  11820. Result := True;
  11821. Exit;
  11822. end;
  11823. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11824. if ANewReg = NR_NO then
  11825. { No free registers }
  11826. Exit;
  11827. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11828. up vying for the same register }
  11829. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11830. ConstRegs[ConstCount] := ANewReg;
  11831. ConstSizes[ConstCount] := RegSize;
  11832. ConstVals[ConstCount] := CurrentVal;
  11833. Inc(ConstCount);
  11834. Inc(Count);
  11835. Result := True;
  11836. end;
  11837. destructor TCMOVTracking.Done;
  11838. begin
  11839. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11840. end;
  11841. procedure TCMOVTracking.Process(out new_p: tai);
  11842. var
  11843. Count, Writes: LongInt;
  11844. RegMatch: Boolean;
  11845. hp1, hp_new: tai;
  11846. inverted_condition, condition: TAsmCond;
  11847. begin
  11848. if (fState in [tsInvalid, tsProcessed]) then
  11849. InternalError(2023110701);
  11850. { Repurpose RegisterTracking to mark registers that we've defined }
  11851. RegisterTracking[R_INTREGISTER].Clear;
  11852. Count := 0;
  11853. Writes := 0;
  11854. condition := taicpu(fInitialJump).condition;
  11855. inverted_condition := inverse_cond(condition);
  11856. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11857. doesn't get CMOVs in this case }
  11858. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11859. begin
  11860. { Include the jump in the flag tracking }
  11861. if Assigned(fThirdJump) then
  11862. begin
  11863. if (fState = tsDoubleBranchSame) then
  11864. begin
  11865. { Will be an unconditional jump, so track to the instruction before it }
  11866. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11867. InternalError(2023110710);
  11868. end
  11869. else
  11870. hp1 := fThirdJump;
  11871. end
  11872. else
  11873. hp1 := fSecondMovBlockStop;
  11874. end
  11875. else
  11876. begin
  11877. { Include a conditional jump in the flag tracking }
  11878. if Assigned(fSecondJump) then
  11879. begin
  11880. if (fState = tsDetour) then
  11881. begin
  11882. { Will be an unconditional jump, so track to the instruction before it }
  11883. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11884. InternalError(2023110711);
  11885. end
  11886. else
  11887. hp1 := fSecondJump;
  11888. end
  11889. else
  11890. hp1 := fFirstMovBlockStop;
  11891. end;
  11892. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11893. { Process the second set of MOVs first, because if a destination
  11894. register is shared between the first and second MOV sets, it is more
  11895. efficient to turn the first one into a MOV instruction and place it
  11896. before the CMP if possible, but we won't know which registers are
  11897. shared until we've processed at least one list, so we might as well
  11898. make it the second one since that won't be modified again. }
  11899. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  11900. begin
  11901. hp1 := fSecondMovBlock;
  11902. repeat
  11903. if not Assigned(hp1) then
  11904. InternalError(2018062902);
  11905. if (hp1.typ = ait_instruction) then
  11906. begin
  11907. { Extra safeguard }
  11908. if (taicpu(hp1).opcode <> A_MOV) then
  11909. InternalError(2018062903);
  11910. { Note: tsDoubleBranchDifferent is essentially identical to
  11911. tsBranching and the 2nd block is best left largely
  11912. untouched, but we need to evaluate which registers the MOVs
  11913. write to in order to track what would be complementary CMOV
  11914. pairs that can be further optimised. [Kit] }
  11915. if fState <> tsDoubleBranchDifferent then
  11916. begin
  11917. if taicpu(hp1).oper[0]^.typ = top_const then
  11918. begin
  11919. RegMatch := False;
  11920. for Count := 0 to ConstCount - 1 do
  11921. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11922. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11923. begin
  11924. RegMatch := True;
  11925. { If it's in RegisterTracking, then this register
  11926. is being used more than once and hence has
  11927. already had its value defined (it gets added to
  11928. UsedRegs through AllocRegBetween below) }
  11929. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11930. begin
  11931. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11932. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11933. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11934. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11935. ConstMovs[Count] := hp_new;
  11936. end
  11937. else
  11938. { We just need an instruction between hp_prev and hp1
  11939. where we know the register is marked as in use }
  11940. hp_new := fSecondMovBlock;
  11941. { Keep track of largest write for this register so it can be optimised later }
  11942. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11943. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11944. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11945. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11946. Break;
  11947. end;
  11948. if not RegMatch then
  11949. InternalError(2021100411);
  11950. end;
  11951. taicpu(hp1).opcode := A_CMOVcc;
  11952. taicpu(hp1).condition := condition;
  11953. end;
  11954. { Store these writes to search for duplicates later on }
  11955. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11956. Inc(Writes);
  11957. end;
  11958. fOptimizer.GetNextInstruction(hp1, hp1);
  11959. until (hp1 = fSecondMovBlockStop);
  11960. end;
  11961. { Now do the first set of MOVs }
  11962. hp1 := fFirstMovBlock;
  11963. repeat
  11964. if not Assigned(hp1) then
  11965. InternalError(2018062904);
  11966. if (hp1.typ = ait_instruction) then
  11967. begin
  11968. RegMatch := False;
  11969. { Extra safeguard }
  11970. if (taicpu(hp1).opcode <> A_MOV) then
  11971. InternalError(2018062905);
  11972. { Search through the RegWrites list to see if there are any
  11973. opposing CMOV pairs that write to the same register }
  11974. for Count := 0 to Writes - 1 do
  11975. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  11976. begin
  11977. { We have a match. Keep this as a MOV }
  11978. { Move ahead in preparation }
  11979. fOptimizer.GetNextInstruction(hp1, hp1);
  11980. RegMatch := True;
  11981. Break;
  11982. end;
  11983. if RegMatch then
  11984. Continue;
  11985. if taicpu(hp1).oper[0]^.typ = top_const then
  11986. begin
  11987. for Count := 0 to ConstCount - 1 do
  11988. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11989. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11990. begin
  11991. RegMatch := True;
  11992. { If it's in RegisterTracking, then this register is
  11993. being used more than once and hence has already had
  11994. its value defined (it gets added to UsedRegs through
  11995. AllocRegBetween below) }
  11996. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11997. begin
  11998. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11999. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12000. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12001. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12002. ConstMovs[Count] := hp_new;
  12003. end
  12004. else
  12005. { We just need an instruction between hp_prev and hp1
  12006. where we know the register is marked as in use }
  12007. hp_new := fFirstMovBlock;
  12008. { Keep track of largest write for this register so it can be optimised later }
  12009. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12010. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12011. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12012. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12013. Break;
  12014. end;
  12015. if not RegMatch then
  12016. InternalError(2021100412);
  12017. end;
  12018. taicpu(hp1).opcode := A_CMOVcc;
  12019. taicpu(hp1).condition := inverted_condition;
  12020. if (fState = tsDoubleBranchDifferent) then
  12021. begin
  12022. { Store these writes to search for duplicates later on }
  12023. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12024. Inc(Writes);
  12025. end;
  12026. end;
  12027. fOptimizer.GetNextInstruction(hp1, hp1);
  12028. until (hp1 = fFirstMovBlockStop);
  12029. { Update initialisation MOVs to the smallest possible size }
  12030. for Count := 0 to ConstCount - 1 do
  12031. if Assigned(ConstMovs[Count]) then
  12032. begin
  12033. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12034. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12035. end;
  12036. case fState of
  12037. tsSimple:
  12038. begin
  12039. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12040. { No branch to delete }
  12041. end;
  12042. tsDetour:
  12043. begin
  12044. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12045. { Preserve jump }
  12046. end;
  12047. tsBranching, tsDoubleBranchDifferent:
  12048. begin
  12049. if (fState = tsBranching) then
  12050. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12051. else
  12052. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12053. taicpu(fSecondJump).opcode := A_JCC;
  12054. taicpu(fSecondJump).condition := inverted_condition;
  12055. end;
  12056. tsDouble, tsDoubleBranchSame:
  12057. begin
  12058. if (fState = tsDouble) then
  12059. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12060. else
  12061. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12062. { Delete second jump }
  12063. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12064. fOptimizer.RemoveInstruction(fSecondJump);
  12065. end;
  12066. tsDoubleSecondBranching:
  12067. begin
  12068. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12069. { Delete second jump, preserve third jump as conditional }
  12070. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12071. fOptimizer.RemoveInstruction(fSecondJump);
  12072. taicpu(fThirdJump).opcode := A_JCC;
  12073. taicpu(fThirdJump).condition := condition;
  12074. end;
  12075. else
  12076. InternalError(2023110720);
  12077. end;
  12078. { Now we can safely decrement the reference count }
  12079. tasmlabel(fLabel).decrefs;
  12080. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12081. { Remove the original jump }
  12082. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12083. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12084. fState := tsProcessed;
  12085. end;
  12086. {$endif 8086}
  12087. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12088. var
  12089. hp1,hp2: tai;
  12090. carryadd_opcode : TAsmOp;
  12091. symbol: TAsmSymbol;
  12092. increg, tmpreg: TRegister;
  12093. {$ifndef i8086}
  12094. CMOVTracking: PCMOVTracking;
  12095. hp3,hp4,hp5: tai;
  12096. {$endif i8086}
  12097. TempBool: Boolean;
  12098. begin
  12099. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12100. DoJumpOptimizations(p, TempBool) then
  12101. Exit(True);
  12102. result:=false;
  12103. if GetNextInstruction(p,hp1) then
  12104. begin
  12105. if (hp1.typ=ait_label) then
  12106. begin
  12107. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12108. Exit;
  12109. end
  12110. else if (hp1.typ<>ait_instruction) then
  12111. Exit;
  12112. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12113. if (
  12114. (
  12115. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12116. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12117. (Taicpu(hp1).oper[0]^.val=1)
  12118. ) or
  12119. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12120. ) and
  12121. GetNextInstruction(hp1,hp2) and
  12122. (hp2.typ = ait_label) and
  12123. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12124. { jb @@1 cmc
  12125. inc/dec operand --> adc/sbb operand,0
  12126. @@1:
  12127. ... and ...
  12128. jnb @@1
  12129. inc/dec operand --> adc/sbb operand,0
  12130. @@1: }
  12131. begin
  12132. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12133. begin
  12134. case taicpu(hp1).opcode of
  12135. A_INC,
  12136. A_ADD:
  12137. carryadd_opcode:=A_ADC;
  12138. A_DEC,
  12139. A_SUB:
  12140. carryadd_opcode:=A_SBB;
  12141. else
  12142. InternalError(2021011001);
  12143. end;
  12144. Taicpu(p).clearop(0);
  12145. Taicpu(p).ops:=0;
  12146. Taicpu(p).is_jmp:=false;
  12147. Taicpu(p).opcode:=A_CMC;
  12148. Taicpu(p).condition:=C_NONE;
  12149. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12150. Taicpu(hp1).ops:=2;
  12151. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12152. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12153. else
  12154. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12155. Taicpu(hp1).loadconst(0,0);
  12156. Taicpu(hp1).opcode:=carryadd_opcode;
  12157. result:=true;
  12158. exit;
  12159. end
  12160. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12161. begin
  12162. case taicpu(hp1).opcode of
  12163. A_INC,
  12164. A_ADD:
  12165. carryadd_opcode:=A_ADC;
  12166. A_DEC,
  12167. A_SUB:
  12168. carryadd_opcode:=A_SBB;
  12169. else
  12170. InternalError(2021011002);
  12171. end;
  12172. Taicpu(hp1).ops:=2;
  12173. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12174. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12175. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12176. else
  12177. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12178. Taicpu(hp1).loadconst(0,0);
  12179. Taicpu(hp1).opcode:=carryadd_opcode;
  12180. RemoveCurrentP(p, hp1);
  12181. result:=true;
  12182. exit;
  12183. end
  12184. {
  12185. jcc @@1 setcc tmpreg
  12186. inc/dec/add/sub operand -> (movzx tmpreg)
  12187. @@1: add/sub tmpreg,operand
  12188. While this increases code size slightly, it makes the code much faster if the
  12189. jump is unpredictable
  12190. }
  12191. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12192. begin
  12193. { search for an available register which is volatile }
  12194. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12195. if increg <> NR_NO then
  12196. begin
  12197. { We don't need to check if tmpreg is in hp1 or not, because
  12198. it will be marked as in use at p (if not, this is
  12199. indictive of a compiler bug). }
  12200. TAsmLabel(symbol).decrefs;
  12201. Taicpu(p).clearop(0);
  12202. Taicpu(p).ops:=1;
  12203. Taicpu(p).is_jmp:=false;
  12204. Taicpu(p).opcode:=A_SETcc;
  12205. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12206. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12207. Taicpu(p).loadreg(0,increg);
  12208. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12209. begin
  12210. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12211. R_SUBW:
  12212. begin
  12213. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12214. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12215. end;
  12216. R_SUBD:
  12217. begin
  12218. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12219. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12220. end;
  12221. {$ifdef x86_64}
  12222. R_SUBQ:
  12223. begin
  12224. { MOVZX doesn't have a 64-bit variant, because
  12225. the 32-bit version implicitly zeroes the
  12226. upper 32-bits of the destination register }
  12227. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12228. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12229. setsubreg(tmpreg, R_SUBQ);
  12230. end;
  12231. {$endif x86_64}
  12232. else
  12233. Internalerror(2020030601);
  12234. end;
  12235. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12236. asml.InsertAfter(hp2,p);
  12237. end
  12238. else
  12239. tmpreg := increg;
  12240. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12241. begin
  12242. Taicpu(hp1).ops:=2;
  12243. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12244. end;
  12245. Taicpu(hp1).loadreg(0,tmpreg);
  12246. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12247. Result := True;
  12248. { p is no longer a Jcc instruction, so exit }
  12249. Exit;
  12250. end;
  12251. end;
  12252. end;
  12253. { Detect the following:
  12254. jmp<cond> @Lbl1
  12255. jmp @Lbl2
  12256. ...
  12257. @Lbl1:
  12258. ret
  12259. Change to:
  12260. jmp<inv_cond> @Lbl2
  12261. ret
  12262. }
  12263. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12264. begin
  12265. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12266. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12267. MatchInstruction(hp2,A_RET,[S_NO]) then
  12268. begin
  12269. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12270. { Change label address to that of the unconditional jump }
  12271. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12272. TAsmLabel(symbol).DecRefs;
  12273. taicpu(hp1).opcode := A_RET;
  12274. taicpu(hp1).is_jmp := false;
  12275. taicpu(hp1).ops := taicpu(hp2).ops;
  12276. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12277. case taicpu(hp2).ops of
  12278. 0:
  12279. taicpu(hp1).clearop(0);
  12280. 1:
  12281. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12282. else
  12283. internalerror(2016041302);
  12284. end;
  12285. end;
  12286. {$ifndef i8086}
  12287. end
  12288. {
  12289. convert
  12290. j<c> .L1
  12291. mov 1,reg
  12292. jmp .L2
  12293. .L1
  12294. mov 0,reg
  12295. .L2
  12296. into
  12297. mov 0,reg
  12298. set<not(c)> reg
  12299. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12300. would destroy the flag contents
  12301. }
  12302. else if MatchInstruction(hp1,A_MOV,[]) and
  12303. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12304. {$ifdef i386}
  12305. (
  12306. { Under i386, ESI, EDI, EBP and ESP
  12307. don't have an 8-bit representation }
  12308. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12309. ) and
  12310. {$endif i386}
  12311. (taicpu(hp1).oper[0]^.val=1) and
  12312. GetNextInstruction(hp1,hp2) and
  12313. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12314. GetNextInstruction(hp2,hp3) and
  12315. (hp3.typ=ait_label) and
  12316. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12317. (tai_label(hp3).labsym.getrefs=1) and
  12318. GetNextInstruction(hp3,hp4) and
  12319. MatchInstruction(hp4,A_MOV,[]) and
  12320. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12321. (taicpu(hp4).oper[0]^.val=0) and
  12322. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12323. GetNextInstruction(hp4,hp5) and
  12324. (hp5.typ=ait_label) and
  12325. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12326. (tai_label(hp5).labsym.getrefs=1) then
  12327. begin
  12328. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12329. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12330. { remove last label }
  12331. RemoveInstruction(hp5);
  12332. { remove second label }
  12333. RemoveInstruction(hp3);
  12334. { remove jmp }
  12335. RemoveInstruction(hp2);
  12336. if taicpu(hp1).opsize=S_B then
  12337. RemoveInstruction(hp1)
  12338. else
  12339. taicpu(hp1).loadconst(0,0);
  12340. taicpu(hp4).opcode:=A_SETcc;
  12341. taicpu(hp4).opsize:=S_B;
  12342. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12343. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12344. taicpu(hp4).opercnt:=1;
  12345. taicpu(hp4).ops:=1;
  12346. taicpu(hp4).freeop(1);
  12347. RemoveCurrentP(p);
  12348. Result:=true;
  12349. exit;
  12350. end
  12351. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12352. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12353. begin
  12354. { check for
  12355. jCC xxx
  12356. <several movs>
  12357. xxx:
  12358. Also spot:
  12359. Jcc xxx
  12360. <several movs>
  12361. jmp xxx
  12362. Change to:
  12363. <several cmovs with inverted condition>
  12364. jmp xxx (only for the 2nd case)
  12365. }
  12366. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12367. if CMOVTracking^.State <> tsInvalid then
  12368. begin
  12369. CMovTracking^.Process(p);
  12370. Result := True;
  12371. end;
  12372. CMOVTracking^.Done;
  12373. {$endif i8086}
  12374. end;
  12375. end;
  12376. end;
  12377. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12378. var
  12379. hp1,hp2,hp3: tai;
  12380. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12381. NewSize: TOpSize;
  12382. NewRegSize: TSubRegister;
  12383. Limit: TCgInt;
  12384. SwapOper: POper;
  12385. begin
  12386. result:=false;
  12387. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12388. GetNextInstruction(p,hp1) and
  12389. (hp1.typ = ait_instruction);
  12390. if reg_and_hp1_is_instr and
  12391. (
  12392. (taicpu(hp1).opcode <> A_LEA) or
  12393. { If the LEA instruction can be converted into an arithmetic instruction,
  12394. it may be possible to then fold it. }
  12395. (
  12396. { If the flags register is in use, don't change the instruction
  12397. to an ADD otherwise this will scramble the flags. [Kit] }
  12398. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12399. ConvertLEA(taicpu(hp1))
  12400. )
  12401. ) and
  12402. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12403. GetNextInstruction(hp1,hp2) and
  12404. MatchInstruction(hp2,A_MOV,[]) and
  12405. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12406. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12407. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12408. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12409. {$ifdef i386}
  12410. { not all registers have byte size sub registers on i386 }
  12411. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12412. {$endif i386}
  12413. (((taicpu(hp1).ops=2) and
  12414. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12415. ((taicpu(hp1).ops=1) and
  12416. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12417. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12418. begin
  12419. { change movsX/movzX reg/ref, reg2
  12420. add/sub/or/... reg3/$const, reg2
  12421. mov reg2 reg/ref
  12422. to add/sub/or/... reg3/$const, reg/ref }
  12423. { by example:
  12424. movswl %si,%eax movswl %si,%eax p
  12425. decl %eax addl %edx,%eax hp1
  12426. movw %ax,%si movw %ax,%si hp2
  12427. ->
  12428. movswl %si,%eax movswl %si,%eax p
  12429. decw %eax addw %edx,%eax hp1
  12430. movw %ax,%si movw %ax,%si hp2
  12431. }
  12432. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12433. {
  12434. ->
  12435. movswl %si,%eax movswl %si,%eax p
  12436. decw %si addw %dx,%si hp1
  12437. movw %ax,%si movw %ax,%si hp2
  12438. }
  12439. case taicpu(hp1).ops of
  12440. 1:
  12441. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12442. 2:
  12443. begin
  12444. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12445. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12446. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12447. end;
  12448. else
  12449. internalerror(2008042702);
  12450. end;
  12451. {
  12452. ->
  12453. decw %si addw %dx,%si p
  12454. }
  12455. DebugMsg(SPeepholeOptimization + 'var3',p);
  12456. RemoveCurrentP(p, hp1);
  12457. RemoveInstruction(hp2);
  12458. Result := True;
  12459. Exit;
  12460. end;
  12461. if reg_and_hp1_is_instr and
  12462. (taicpu(hp1).opcode = A_MOV) and
  12463. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12464. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12465. {$ifdef x86_64}
  12466. { check for implicit extension to 64 bit }
  12467. or
  12468. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12469. (taicpu(hp1).opsize=S_Q) and
  12470. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12471. )
  12472. {$endif x86_64}
  12473. )
  12474. then
  12475. begin
  12476. { change
  12477. movx %reg1,%reg2
  12478. mov %reg2,%reg3
  12479. dealloc %reg2
  12480. into
  12481. movx %reg,%reg3
  12482. }
  12483. TransferUsedRegs(TmpUsedRegs);
  12484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12485. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12486. begin
  12487. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12488. {$ifdef x86_64}
  12489. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12490. (taicpu(hp1).opsize=S_Q) then
  12491. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12492. else
  12493. {$endif x86_64}
  12494. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12495. RemoveInstruction(hp1);
  12496. Result := True;
  12497. Exit;
  12498. end;
  12499. end;
  12500. if reg_and_hp1_is_instr and
  12501. ((taicpu(hp1).opcode=A_MOV) or
  12502. (taicpu(hp1).opcode=A_ADD) or
  12503. (taicpu(hp1).opcode=A_SUB) or
  12504. (taicpu(hp1).opcode=A_CMP) or
  12505. (taicpu(hp1).opcode=A_OR) or
  12506. (taicpu(hp1).opcode=A_XOR) or
  12507. (taicpu(hp1).opcode=A_AND)
  12508. ) and
  12509. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12510. begin
  12511. AndTest := (taicpu(hp1).opcode=A_AND) and
  12512. GetNextInstruction(hp1, hp2) and
  12513. (hp2.typ = ait_instruction) and
  12514. (
  12515. (
  12516. (taicpu(hp2).opcode=A_TEST) and
  12517. (
  12518. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12519. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12520. (
  12521. { If the AND and TEST instructions share a constant, this is also valid }
  12522. (taicpu(hp1).oper[0]^.typ = top_const) and
  12523. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12524. )
  12525. ) and
  12526. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12527. ) or
  12528. (
  12529. (taicpu(hp2).opcode=A_CMP) and
  12530. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12531. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12532. )
  12533. );
  12534. { change
  12535. movx (oper),%reg2
  12536. and $x,%reg2
  12537. test %reg2,%reg2
  12538. dealloc %reg2
  12539. into
  12540. op %reg1,%reg3
  12541. if the second op accesses only the bits stored in reg1
  12542. }
  12543. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12544. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12545. (taicpu(hp1).oper[0]^.typ = top_const) and
  12546. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12547. AndTest then
  12548. begin
  12549. { Check if the AND constant is in range }
  12550. case taicpu(p).opsize of
  12551. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12552. begin
  12553. NewSize := S_B;
  12554. Limit := $FF;
  12555. end;
  12556. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12557. begin
  12558. NewSize := S_W;
  12559. Limit := $FFFF;
  12560. end;
  12561. {$ifdef x86_64}
  12562. S_LQ:
  12563. begin
  12564. NewSize := S_L;
  12565. Limit := $FFFFFFFF;
  12566. end;
  12567. {$endif x86_64}
  12568. else
  12569. InternalError(2021120303);
  12570. end;
  12571. if (
  12572. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12573. { Check for negative operands }
  12574. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12575. ) and
  12576. GetNextInstruction(hp2,hp3) and
  12577. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12578. (taicpu(hp3).condition in [C_E,C_NE]) then
  12579. begin
  12580. TransferUsedRegs(TmpUsedRegs);
  12581. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12582. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12583. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12584. begin
  12585. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12586. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12587. taicpu(hp1).opcode := A_TEST;
  12588. taicpu(hp1).opsize := NewSize;
  12589. RemoveInstruction(hp2);
  12590. RemoveCurrentP(p, hp1);
  12591. Result:=true;
  12592. exit;
  12593. end;
  12594. end;
  12595. end;
  12596. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12597. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12598. (taicpu(hp1).opsize=S_B)) or
  12599. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12600. (taicpu(hp1).opsize=S_W))
  12601. {$ifdef x86_64}
  12602. or ((taicpu(p).opsize=S_LQ) and
  12603. (taicpu(hp1).opsize=S_L))
  12604. {$endif x86_64}
  12605. ) and
  12606. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12607. begin
  12608. { change
  12609. movx %reg1,%reg2
  12610. op %reg2,%reg3
  12611. dealloc %reg2
  12612. into
  12613. op %reg1,%reg3
  12614. if the second op accesses only the bits stored in reg1
  12615. }
  12616. TransferUsedRegs(TmpUsedRegs);
  12617. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12618. if AndTest then
  12619. begin
  12620. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12621. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12622. end
  12623. else
  12624. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12625. if not RegUsed then
  12626. begin
  12627. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12628. if taicpu(p).oper[0]^.typ=top_reg then
  12629. begin
  12630. case taicpu(hp1).opsize of
  12631. S_B:
  12632. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12633. S_W:
  12634. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12635. S_L:
  12636. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12637. else
  12638. Internalerror(2020102301);
  12639. end;
  12640. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12641. end
  12642. else
  12643. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12644. RemoveCurrentP(p);
  12645. if AndTest then
  12646. RemoveInstruction(hp2);
  12647. result:=true;
  12648. exit;
  12649. end;
  12650. end
  12651. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12652. (
  12653. { Bitwise operations only }
  12654. (taicpu(hp1).opcode=A_AND) or
  12655. (taicpu(hp1).opcode=A_TEST) or
  12656. (
  12657. (taicpu(hp1).oper[0]^.typ = top_const) and
  12658. (
  12659. (taicpu(hp1).opcode=A_OR) or
  12660. (taicpu(hp1).opcode=A_XOR)
  12661. )
  12662. )
  12663. ) and
  12664. (
  12665. (taicpu(hp1).oper[0]^.typ = top_const) or
  12666. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12667. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12668. ) then
  12669. begin
  12670. { change
  12671. movx %reg2,%reg2
  12672. op const,%reg2
  12673. into
  12674. op const,%reg2 (smaller version)
  12675. movx %reg2,%reg2
  12676. also change
  12677. movx %reg1,%reg2
  12678. and/test (oper),%reg2
  12679. dealloc %reg2
  12680. into
  12681. and/test (oper),%reg1
  12682. }
  12683. case taicpu(p).opsize of
  12684. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12685. begin
  12686. NewSize := S_B;
  12687. NewRegSize := R_SUBL;
  12688. Limit := $FF;
  12689. end;
  12690. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12691. begin
  12692. NewSize := S_W;
  12693. NewRegSize := R_SUBW;
  12694. Limit := $FFFF;
  12695. end;
  12696. {$ifdef x86_64}
  12697. S_LQ:
  12698. begin
  12699. NewSize := S_L;
  12700. NewRegSize := R_SUBD;
  12701. Limit := $FFFFFFFF;
  12702. end;
  12703. {$endif x86_64}
  12704. else
  12705. Internalerror(2021120302);
  12706. end;
  12707. TransferUsedRegs(TmpUsedRegs);
  12708. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12709. if AndTest then
  12710. begin
  12711. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12712. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12713. end
  12714. else
  12715. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12716. if
  12717. (
  12718. (taicpu(p).opcode = A_MOVZX) and
  12719. (
  12720. (taicpu(hp1).opcode=A_AND) or
  12721. (taicpu(hp1).opcode=A_TEST)
  12722. ) and
  12723. not (
  12724. { If both are references, then the final instruction will have
  12725. both operands as references, which is not allowed }
  12726. (taicpu(p).oper[0]^.typ = top_ref) and
  12727. (taicpu(hp1).oper[0]^.typ = top_ref)
  12728. ) and
  12729. not RegUsed
  12730. ) or
  12731. (
  12732. (
  12733. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12734. not RegUsed
  12735. ) and
  12736. (taicpu(p).oper[0]^.typ = top_reg) and
  12737. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12738. (taicpu(hp1).oper[0]^.typ = top_const) and
  12739. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12740. ) then
  12741. begin
  12742. {$if defined(i386) or defined(i8086)}
  12743. { If the target size is 8-bit, make sure we can actually encode it }
  12744. 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
  12745. Exit;
  12746. {$endif i386 or i8086}
  12747. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12748. taicpu(hp1).opsize := NewSize;
  12749. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12750. if AndTest then
  12751. begin
  12752. RemoveInstruction(hp2);
  12753. if not RegUsed then
  12754. begin
  12755. taicpu(hp1).opcode := A_TEST;
  12756. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12757. begin
  12758. { Make sure the reference is the second operand }
  12759. SwapOper := taicpu(hp1).oper[0];
  12760. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12761. taicpu(hp1).oper[1] := SwapOper;
  12762. end;
  12763. end;
  12764. end;
  12765. case taicpu(hp1).oper[0]^.typ of
  12766. top_reg:
  12767. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12768. top_const:
  12769. { For the AND/TEST case }
  12770. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12771. else
  12772. ;
  12773. end;
  12774. if RegUsed then
  12775. begin
  12776. AsmL.Remove(p);
  12777. AsmL.InsertAfter(p, hp1);
  12778. p := hp1;
  12779. end
  12780. else
  12781. RemoveCurrentP(p, hp1);
  12782. result:=true;
  12783. exit;
  12784. end;
  12785. end;
  12786. end;
  12787. if reg_and_hp1_is_instr and
  12788. (taicpu(p).oper[0]^.typ = top_reg) and
  12789. (
  12790. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12791. ) and
  12792. (taicpu(hp1).oper[0]^.typ = top_const) and
  12793. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12794. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12795. { Minimum shift value allowed is the bit difference between the sizes }
  12796. (taicpu(hp1).oper[0]^.val >=
  12797. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12798. 8 * (
  12799. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12800. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12801. )
  12802. ) then
  12803. begin
  12804. { For:
  12805. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12806. shl/sal ##, %reg1
  12807. Remove the movsx/movzx instruction if the shift overwrites the
  12808. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12809. }
  12810. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12811. RemoveCurrentP(p, hp1);
  12812. Result := True;
  12813. Exit;
  12814. end
  12815. else if reg_and_hp1_is_instr and
  12816. (taicpu(p).oper[0]^.typ = top_reg) and
  12817. (
  12818. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12819. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12820. ) and
  12821. (taicpu(hp1).oper[0]^.typ = top_const) and
  12822. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12823. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12824. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12825. (taicpu(hp1).oper[0]^.val <
  12826. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12827. 8 * (
  12828. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12829. )
  12830. ) then
  12831. begin
  12832. { For:
  12833. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12834. sar ##, %reg1 shr ##, %reg1
  12835. Move the shift to before the movx instruction if the shift value
  12836. is not too large.
  12837. }
  12838. asml.Remove(hp1);
  12839. asml.InsertBefore(hp1, p);
  12840. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12841. case taicpu(p).opsize of
  12842. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12843. taicpu(hp1).opsize := S_B;
  12844. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12845. taicpu(hp1).opsize := S_W;
  12846. {$ifdef x86_64}
  12847. S_LQ:
  12848. taicpu(hp1).opsize := S_L;
  12849. {$endif}
  12850. else
  12851. InternalError(2020112401);
  12852. end;
  12853. if (taicpu(hp1).opcode = A_SHR) then
  12854. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12855. else
  12856. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12857. Result := True;
  12858. end;
  12859. if reg_and_hp1_is_instr and
  12860. (taicpu(p).oper[0]^.typ = top_reg) and
  12861. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12862. (
  12863. (taicpu(hp1).opcode = taicpu(p).opcode)
  12864. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12865. {$ifdef x86_64}
  12866. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12867. {$endif x86_64}
  12868. ) then
  12869. begin
  12870. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12871. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12872. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12873. begin
  12874. {
  12875. For example:
  12876. movzbw %al,%ax
  12877. movzwl %ax,%eax
  12878. Compress into:
  12879. movzbl %al,%eax
  12880. }
  12881. RegUsed := False;
  12882. case taicpu(p).opsize of
  12883. S_BW:
  12884. case taicpu(hp1).opsize of
  12885. S_WL:
  12886. begin
  12887. taicpu(p).opsize := S_BL;
  12888. RegUsed := True;
  12889. end;
  12890. {$ifdef x86_64}
  12891. S_WQ:
  12892. begin
  12893. if taicpu(p).opcode = A_MOVZX then
  12894. begin
  12895. taicpu(p).opsize := S_BL;
  12896. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12897. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12898. end
  12899. else
  12900. taicpu(p).opsize := S_BQ;
  12901. RegUsed := True;
  12902. end;
  12903. {$endif x86_64}
  12904. else
  12905. ;
  12906. end;
  12907. {$ifdef x86_64}
  12908. S_BL:
  12909. case taicpu(hp1).opsize of
  12910. S_LQ:
  12911. begin
  12912. if taicpu(p).opcode = A_MOVZX then
  12913. begin
  12914. taicpu(p).opsize := S_BL;
  12915. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12916. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12917. end
  12918. else
  12919. taicpu(p).opsize := S_BQ;
  12920. RegUsed := True;
  12921. end;
  12922. else
  12923. ;
  12924. end;
  12925. S_WL:
  12926. case taicpu(hp1).opsize of
  12927. S_LQ:
  12928. begin
  12929. if taicpu(p).opcode = A_MOVZX then
  12930. begin
  12931. taicpu(p).opsize := S_WL;
  12932. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12933. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12934. end
  12935. else
  12936. taicpu(p).opsize := S_WQ;
  12937. RegUsed := True;
  12938. end;
  12939. else
  12940. ;
  12941. end;
  12942. {$endif x86_64}
  12943. else
  12944. ;
  12945. end;
  12946. if RegUsed then
  12947. begin
  12948. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12949. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12950. RemoveInstruction(hp1);
  12951. Result := True;
  12952. Exit;
  12953. end;
  12954. end;
  12955. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12956. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12957. GetNextInstruction(hp1, hp2) and
  12958. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12959. (
  12960. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12961. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12962. {$ifdef x86_64}
  12963. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12964. {$endif x86_64}
  12965. ) and
  12966. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12967. (
  12968. (
  12969. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12970. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12971. ) or
  12972. (
  12973. { Only allow the operands in reverse order for TEST instructions }
  12974. (taicpu(hp2).opcode = A_TEST) and
  12975. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12976. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12977. )
  12978. ) then
  12979. begin
  12980. {
  12981. For example:
  12982. movzbl %al,%eax
  12983. movzbl (ref),%edx
  12984. andl %edx,%eax
  12985. (%edx deallocated)
  12986. Change to:
  12987. andb (ref),%al
  12988. movzbl %al,%eax
  12989. Rules are:
  12990. - First two instructions have the same opcode and opsize
  12991. - First instruction's operands are the same super-register
  12992. - Second instruction operates on a different register
  12993. - Third instruction is AND, OR, XOR or TEST
  12994. - Third instruction's operands are the destination registers of the first two instructions
  12995. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12996. - Second instruction's destination register is deallocated afterwards
  12997. }
  12998. TransferUsedRegs(TmpUsedRegs);
  12999. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13000. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13001. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13002. begin
  13003. case taicpu(p).opsize of
  13004. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13005. NewSize := S_B;
  13006. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13007. NewSize := S_W;
  13008. {$ifdef x86_64}
  13009. S_LQ:
  13010. NewSize := S_L;
  13011. {$endif x86_64}
  13012. else
  13013. InternalError(2021120301);
  13014. end;
  13015. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13016. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13017. taicpu(hp2).opsize := NewSize;
  13018. RemoveInstruction(hp1);
  13019. { With TEST, it's best to keep the MOVX instruction at the top }
  13020. if (taicpu(hp2).opcode <> A_TEST) then
  13021. begin
  13022. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13023. asml.Remove(p);
  13024. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13025. asml.InsertAfter(p, hp2);
  13026. p := hp2;
  13027. end
  13028. else
  13029. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13030. Result := True;
  13031. Exit;
  13032. end;
  13033. end;
  13034. end;
  13035. if taicpu(p).opcode=A_MOVZX then
  13036. begin
  13037. { removes superfluous And's after movzx's }
  13038. if reg_and_hp1_is_instr and
  13039. (taicpu(hp1).opcode = A_AND) and
  13040. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13041. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13042. {$ifdef x86_64}
  13043. { check for implicit extension to 64 bit }
  13044. or
  13045. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13046. (taicpu(hp1).opsize=S_Q) and
  13047. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13048. )
  13049. {$endif x86_64}
  13050. )
  13051. then
  13052. begin
  13053. case taicpu(p).opsize Of
  13054. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13055. if (taicpu(hp1).oper[0]^.val = $ff) then
  13056. begin
  13057. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13058. RemoveInstruction(hp1);
  13059. Result:=true;
  13060. exit;
  13061. end;
  13062. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13063. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13064. begin
  13065. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13066. RemoveInstruction(hp1);
  13067. Result:=true;
  13068. exit;
  13069. end;
  13070. {$ifdef x86_64}
  13071. S_LQ:
  13072. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13073. begin
  13074. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13075. RemoveInstruction(hp1);
  13076. Result:=true;
  13077. exit;
  13078. end;
  13079. {$endif x86_64}
  13080. else
  13081. ;
  13082. end;
  13083. { we cannot get rid of the and, but can we get rid of the movz ?}
  13084. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13085. begin
  13086. case taicpu(p).opsize Of
  13087. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13088. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13089. begin
  13090. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13091. RemoveCurrentP(p,hp1);
  13092. Result:=true;
  13093. exit;
  13094. end;
  13095. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13096. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13097. begin
  13098. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13099. RemoveCurrentP(p,hp1);
  13100. Result:=true;
  13101. exit;
  13102. end;
  13103. {$ifdef x86_64}
  13104. S_LQ:
  13105. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13106. begin
  13107. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13108. RemoveCurrentP(p,hp1);
  13109. Result:=true;
  13110. exit;
  13111. end;
  13112. {$endif x86_64}
  13113. else
  13114. ;
  13115. end;
  13116. end;
  13117. end;
  13118. { changes some movzx constructs to faster synonyms (all examples
  13119. are given with eax/ax, but are also valid for other registers)}
  13120. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13121. begin
  13122. case taicpu(p).opsize of
  13123. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13124. (the machine code is equivalent to movzbl %al,%eax), but the
  13125. code generator still generates that assembler instruction and
  13126. it is silently converted. This should probably be checked.
  13127. [Kit] }
  13128. S_BW:
  13129. begin
  13130. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13131. (
  13132. not IsMOVZXAcceptable
  13133. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13134. or (
  13135. (cs_opt_size in current_settings.optimizerswitches) and
  13136. (taicpu(p).oper[1]^.reg = NR_AX)
  13137. )
  13138. ) then
  13139. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13140. begin
  13141. DebugMsg(SPeepholeOptimization + 'var7',p);
  13142. taicpu(p).opcode := A_AND;
  13143. taicpu(p).changeopsize(S_W);
  13144. taicpu(p).loadConst(0,$ff);
  13145. Result := True;
  13146. end
  13147. else if not IsMOVZXAcceptable and
  13148. GetNextInstruction(p, hp1) and
  13149. (tai(hp1).typ = ait_instruction) and
  13150. (taicpu(hp1).opcode = A_AND) and
  13151. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13152. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13153. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13154. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13155. begin
  13156. DebugMsg(SPeepholeOptimization + 'var8',p);
  13157. taicpu(p).opcode := A_MOV;
  13158. taicpu(p).changeopsize(S_W);
  13159. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13160. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13161. Result := True;
  13162. end;
  13163. end;
  13164. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13165. S_BL:
  13166. if not IsMOVZXAcceptable then
  13167. begin
  13168. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13169. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13170. begin
  13171. DebugMsg(SPeepholeOptimization + 'var9',p);
  13172. taicpu(p).opcode := A_AND;
  13173. taicpu(p).changeopsize(S_L);
  13174. taicpu(p).loadConst(0,$ff);
  13175. Result := True;
  13176. end
  13177. else if GetNextInstruction(p, hp1) and
  13178. (tai(hp1).typ = ait_instruction) and
  13179. (taicpu(hp1).opcode = A_AND) and
  13180. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13181. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13182. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13183. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13184. begin
  13185. DebugMsg(SPeepholeOptimization + 'var10',p);
  13186. taicpu(p).opcode := A_MOV;
  13187. taicpu(p).changeopsize(S_L);
  13188. { do not use R_SUBWHOLE
  13189. as movl %rdx,%eax
  13190. is invalid in assembler PM }
  13191. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13192. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13193. Result := True;
  13194. end;
  13195. end;
  13196. {$endif i8086}
  13197. S_WL:
  13198. if not IsMOVZXAcceptable then
  13199. begin
  13200. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13201. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13202. begin
  13203. DebugMsg(SPeepholeOptimization + 'var11',p);
  13204. taicpu(p).opcode := A_AND;
  13205. taicpu(p).changeopsize(S_L);
  13206. taicpu(p).loadConst(0,$ffff);
  13207. Result := True;
  13208. end
  13209. else if GetNextInstruction(p, hp1) and
  13210. (tai(hp1).typ = ait_instruction) and
  13211. (taicpu(hp1).opcode = A_AND) and
  13212. (taicpu(hp1).oper[0]^.typ = top_const) and
  13213. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13214. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13215. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13216. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13217. begin
  13218. DebugMsg(SPeepholeOptimization + 'var12',p);
  13219. taicpu(p).opcode := A_MOV;
  13220. taicpu(p).changeopsize(S_L);
  13221. { do not use R_SUBWHOLE
  13222. as movl %rdx,%eax
  13223. is invalid in assembler PM }
  13224. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13225. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13226. Result := True;
  13227. end;
  13228. end;
  13229. else
  13230. InternalError(2017050705);
  13231. end;
  13232. end
  13233. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13234. begin
  13235. if GetNextInstruction(p, hp1) and
  13236. (tai(hp1).typ = ait_instruction) and
  13237. (taicpu(hp1).opcode = A_AND) and
  13238. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13239. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13240. begin
  13241. //taicpu(p).opcode := A_MOV;
  13242. case taicpu(p).opsize Of
  13243. S_BL:
  13244. begin
  13245. DebugMsg(SPeepholeOptimization + 'var13',p);
  13246. taicpu(hp1).changeopsize(S_L);
  13247. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13248. end;
  13249. S_WL:
  13250. begin
  13251. DebugMsg(SPeepholeOptimization + 'var14',p);
  13252. taicpu(hp1).changeopsize(S_L);
  13253. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13254. end;
  13255. S_BW:
  13256. begin
  13257. DebugMsg(SPeepholeOptimization + 'var15',p);
  13258. taicpu(hp1).changeopsize(S_W);
  13259. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13260. end;
  13261. else
  13262. Internalerror(2017050704)
  13263. end;
  13264. Result := True;
  13265. end;
  13266. end;
  13267. end;
  13268. end;
  13269. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13270. var
  13271. hp1, hp2 : tai;
  13272. MaskLength : Cardinal;
  13273. MaskedBits : TCgInt;
  13274. ActiveReg : TRegister;
  13275. begin
  13276. Result:=false;
  13277. { There are no optimisations for reference targets }
  13278. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13279. Exit;
  13280. while GetNextInstruction(p, hp1) and
  13281. (hp1.typ = ait_instruction) do
  13282. begin
  13283. if (taicpu(p).oper[0]^.typ = top_const) then
  13284. begin
  13285. case taicpu(hp1).opcode of
  13286. A_AND:
  13287. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13288. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13289. { the second register must contain the first one, so compare their subreg types }
  13290. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13291. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13292. { change
  13293. and const1, reg
  13294. and const2, reg
  13295. to
  13296. and (const1 and const2), reg
  13297. }
  13298. begin
  13299. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13300. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13301. RemoveCurrentP(p, hp1);
  13302. Result:=true;
  13303. exit;
  13304. end;
  13305. A_CMP:
  13306. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13307. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13308. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13309. { Just check that the condition on the next instruction is compatible }
  13310. GetNextInstruction(hp1, hp2) and
  13311. (hp2.typ = ait_instruction) and
  13312. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13313. then
  13314. { change
  13315. and 2^n, reg
  13316. cmp 2^n, reg
  13317. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13318. to
  13319. and 2^n, reg
  13320. test reg, reg
  13321. j(~c) / set(~c) / cmov(~c)
  13322. }
  13323. begin
  13324. { Keep TEST instruction in, rather than remove it, because
  13325. it may trigger other optimisations such as MovAndTest2Test }
  13326. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13327. taicpu(hp1).opcode := A_TEST;
  13328. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13329. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13330. Result := True;
  13331. Exit;
  13332. end
  13333. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13334. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13335. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13336. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13337. { change
  13338. and $ff/$ff/$ffff, reg
  13339. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13340. dealloc reg
  13341. to
  13342. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13343. }
  13344. begin
  13345. TransferUsedRegs(TmpUsedRegs);
  13346. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13347. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13348. begin
  13349. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13350. case taicpu(p).oper[0]^.val of
  13351. $ff:
  13352. begin
  13353. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13354. taicpu(hp1).opsize:=S_B;
  13355. end;
  13356. $ffff:
  13357. begin
  13358. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13359. taicpu(hp1).opsize:=S_W;
  13360. end;
  13361. $ffffffff:
  13362. begin
  13363. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13364. taicpu(hp1).opsize:=S_L;
  13365. end;
  13366. else
  13367. Internalerror(2023030401);
  13368. end;
  13369. RemoveCurrentP(p);
  13370. Result := True;
  13371. Exit;
  13372. end;
  13373. end;
  13374. A_MOVZX:
  13375. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13376. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13377. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13378. (
  13379. (
  13380. (taicpu(p).opsize=S_W) and
  13381. (taicpu(hp1).opsize=S_BW)
  13382. ) or
  13383. (
  13384. (taicpu(p).opsize=S_L) and
  13385. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13386. )
  13387. {$ifdef x86_64}
  13388. or
  13389. (
  13390. (taicpu(p).opsize=S_Q) and
  13391. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13392. )
  13393. {$endif x86_64}
  13394. ) then
  13395. begin
  13396. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13397. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13398. ) or
  13399. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13400. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13401. then
  13402. begin
  13403. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13404. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13405. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13406. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13407. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13408. }
  13409. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13410. RemoveInstruction(hp1);
  13411. { See if there are other optimisations possible }
  13412. Continue;
  13413. end;
  13414. end;
  13415. A_SHL:
  13416. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13417. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13418. begin
  13419. {$ifopt R+}
  13420. {$define RANGE_WAS_ON}
  13421. {$R-}
  13422. {$endif}
  13423. { get length of potential and mask }
  13424. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13425. { really a mask? }
  13426. {$ifdef RANGE_WAS_ON}
  13427. {$R+}
  13428. {$endif}
  13429. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13430. { unmasked part shifted out? }
  13431. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13432. begin
  13433. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13434. RemoveCurrentP(p, hp1);
  13435. Result:=true;
  13436. exit;
  13437. end;
  13438. end;
  13439. A_SHR:
  13440. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13441. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13442. (taicpu(hp1).oper[0]^.val <= 63) then
  13443. begin
  13444. { Does SHR combined with the AND cover all the bits?
  13445. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13446. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13447. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13448. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13449. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13450. begin
  13451. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13452. RemoveCurrentP(p, hp1);
  13453. Result := True;
  13454. Exit;
  13455. end;
  13456. end;
  13457. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13458. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13459. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13460. begin
  13461. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13462. (
  13463. (
  13464. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13465. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13466. ) or (
  13467. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13468. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13469. {$ifdef x86_64}
  13470. ) or (
  13471. (taicpu(hp1).opsize = S_LQ) and
  13472. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13473. {$endif x86_64}
  13474. )
  13475. ) then
  13476. begin
  13477. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13478. begin
  13479. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13480. RemoveInstruction(hp1);
  13481. { See if there are other optimisations possible }
  13482. Continue;
  13483. end;
  13484. { The super-registers are the same though.
  13485. Note that this change by itself doesn't improve
  13486. code speed, but it opens up other optimisations. }
  13487. {$ifdef x86_64}
  13488. { Convert 64-bit register to 32-bit }
  13489. case taicpu(hp1).opsize of
  13490. S_BQ:
  13491. begin
  13492. taicpu(hp1).opsize := S_BL;
  13493. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13494. end;
  13495. S_WQ:
  13496. begin
  13497. taicpu(hp1).opsize := S_WL;
  13498. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13499. end
  13500. else
  13501. ;
  13502. end;
  13503. {$endif x86_64}
  13504. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13505. taicpu(hp1).opcode := A_MOVZX;
  13506. { See if there are other optimisations possible }
  13507. Continue;
  13508. end;
  13509. end;
  13510. else
  13511. ;
  13512. end;
  13513. end
  13514. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13515. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13516. begin
  13517. {$ifdef x86_64}
  13518. if (taicpu(p).opsize = S_Q) then
  13519. begin
  13520. { Never necessary }
  13521. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13522. RemoveCurrentP(p, hp1);
  13523. Result := True;
  13524. Exit;
  13525. end;
  13526. {$endif x86_64}
  13527. { Forward check to determine necessity of and %reg,%reg }
  13528. TransferUsedRegs(TmpUsedRegs);
  13529. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13530. { Saves on a bunch of dereferences }
  13531. ActiveReg := taicpu(p).oper[1]^.reg;
  13532. case taicpu(hp1).opcode of
  13533. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13534. if (
  13535. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13536. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13537. ) and
  13538. (
  13539. (taicpu(hp1).opcode <> A_MOV) or
  13540. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13541. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13542. ) and
  13543. not (
  13544. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13545. (taicpu(hp1).opcode = A_MOV) and
  13546. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13547. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13548. ) and
  13549. (
  13550. (
  13551. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13552. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13553. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13554. ) or
  13555. (
  13556. {$ifdef x86_64}
  13557. (
  13558. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13559. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13560. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13561. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13562. ) and
  13563. {$endif x86_64}
  13564. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13565. )
  13566. ) then
  13567. begin
  13568. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13569. RemoveCurrentP(p, hp1);
  13570. Result := True;
  13571. Exit;
  13572. end;
  13573. A_ADD,
  13574. A_AND,
  13575. A_BSF,
  13576. A_BSR,
  13577. A_BTC,
  13578. A_BTR,
  13579. A_BTS,
  13580. A_OR,
  13581. A_SUB,
  13582. A_XOR:
  13583. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13584. if (
  13585. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13586. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13587. ) and
  13588. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13589. begin
  13590. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13591. RemoveCurrentP(p, hp1);
  13592. Result := True;
  13593. Exit;
  13594. end;
  13595. A_CMP,
  13596. A_TEST:
  13597. if (
  13598. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13599. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13600. ) and
  13601. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13602. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13603. begin
  13604. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13605. RemoveCurrentP(p, hp1);
  13606. Result := True;
  13607. Exit;
  13608. end;
  13609. A_BSWAP,
  13610. A_NEG,
  13611. A_NOT:
  13612. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13613. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13614. begin
  13615. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13616. RemoveCurrentP(p, hp1);
  13617. Result := True;
  13618. Exit;
  13619. end;
  13620. else
  13621. ;
  13622. end;
  13623. end;
  13624. if (taicpu(hp1).is_jmp) and
  13625. (taicpu(hp1).opcode<>A_JMP) and
  13626. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13627. begin
  13628. { change
  13629. and x, reg
  13630. jxx
  13631. to
  13632. test x, reg
  13633. jxx
  13634. if reg is deallocated before the
  13635. jump, but only if it's a conditional jump (PFV)
  13636. }
  13637. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13638. taicpu(p).opcode := A_TEST;
  13639. Exit;
  13640. end;
  13641. Break;
  13642. end;
  13643. { Lone AND tests }
  13644. if (taicpu(p).oper[0]^.typ = top_const) then
  13645. begin
  13646. {
  13647. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13648. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13649. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13650. }
  13651. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13652. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13653. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13654. begin
  13655. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13656. if taicpu(p).opsize = S_L then
  13657. begin
  13658. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13659. Result := True;
  13660. end;
  13661. end;
  13662. end;
  13663. { Backward check to determine necessity of and %reg,%reg }
  13664. if (taicpu(p).oper[0]^.typ = top_reg) and
  13665. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13666. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13667. GetLastInstruction(p, hp2) and
  13668. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13669. { Check size of adjacent instruction to determine if the AND is
  13670. effectively a null operation }
  13671. (
  13672. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13673. { Note: Don't include S_Q }
  13674. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13675. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13676. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13677. ) then
  13678. begin
  13679. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13680. { If GetNextInstruction returned False, hp1 will be nil }
  13681. RemoveCurrentP(p, hp1);
  13682. Result := True;
  13683. Exit;
  13684. end;
  13685. end;
  13686. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13687. var
  13688. hp1, hp2: tai;
  13689. NewRef: TReference;
  13690. Distance: Cardinal;
  13691. TempTracking: TAllUsedRegs;
  13692. { This entire nested function is used in an if-statement below, but we
  13693. want to avoid all the used reg transfers and GetNextInstruction calls
  13694. until we really have to check }
  13695. function MemRegisterNotUsedLater: Boolean; inline;
  13696. var
  13697. hp2: tai;
  13698. begin
  13699. TransferUsedRegs(TmpUsedRegs);
  13700. hp2 := p;
  13701. repeat
  13702. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13703. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13704. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13705. end;
  13706. begin
  13707. Result := False;
  13708. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13709. (taicpu(p).oper[1]^.typ = top_reg) then
  13710. begin
  13711. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13712. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13713. (hp1.typ <> ait_instruction) or
  13714. not
  13715. (
  13716. (cs_opt_level3 in current_settings.optimizerswitches) or
  13717. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13718. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13719. ) then
  13720. Exit;
  13721. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13722. addq $x, %rax
  13723. movq %rax, %rdx
  13724. sarq $63, %rdx
  13725. (%rax still in use)
  13726. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13727. leaq $x(%rax),%rdx
  13728. addq $x, %rax
  13729. sarq $63, %rdx
  13730. ...which is okay since it breaks the dependency chain between
  13731. addq and movq, but if OptPass2MOV is called first:
  13732. addq $x, %rax
  13733. cqto
  13734. ...which is better in all ways, taking only 2 cycles to execute
  13735. and much smaller in code size.
  13736. }
  13737. { The extra register tracking is quite strenuous }
  13738. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13739. MatchInstruction(hp1, A_MOV, []) then
  13740. begin
  13741. { Update the register tracking to the MOV instruction }
  13742. CopyUsedRegs(TempTracking);
  13743. hp2 := p;
  13744. repeat
  13745. UpdateUsedRegs(tai(hp2.Next));
  13746. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13747. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13748. OptPass2ADD get called again }
  13749. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13750. begin
  13751. { Reset the tracking to the current instruction }
  13752. RestoreUsedRegs(TempTracking);
  13753. ReleaseUsedRegs(TempTracking);
  13754. Result := True;
  13755. Exit;
  13756. end;
  13757. { Reset the tracking to the current instruction }
  13758. RestoreUsedRegs(TempTracking);
  13759. ReleaseUsedRegs(TempTracking);
  13760. { If OptPass2MOV returned True, we don't need to set Result to
  13761. True if hp1 didn't change because the ADD instruction didn't
  13762. get modified and we'll be evaluating hp1 again when the
  13763. peephole optimizer reaches it }
  13764. end;
  13765. { Change:
  13766. add %reg2,%reg1
  13767. (%reg2 not modified in between)
  13768. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13769. To:
  13770. mov/s/z #(%reg1,%reg2),%reg1
  13771. }
  13772. if (taicpu(p).oper[0]^.typ = top_reg) and
  13773. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13774. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13775. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13776. (
  13777. (
  13778. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13779. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13780. { r/esp cannot be an index }
  13781. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13782. ) or (
  13783. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13784. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13785. )
  13786. ) and (
  13787. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13788. (
  13789. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13790. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13791. MemRegisterNotUsedLater
  13792. )
  13793. ) then
  13794. begin
  13795. if (
  13796. { Instructions are guaranteed to be adjacent on -O2 and under }
  13797. (cs_opt_level3 in current_settings.optimizerswitches) and
  13798. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13799. ) then
  13800. begin
  13801. { If the other register is used in between, move the MOV
  13802. instruction to right after the ADD instruction so a
  13803. saving can still be made }
  13804. Asml.Remove(hp1);
  13805. Asml.InsertAfter(hp1, p);
  13806. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13807. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13808. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13809. RemoveCurrentp(p, hp1);
  13810. end
  13811. else
  13812. begin
  13813. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13814. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13815. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13816. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13817. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13818. { hp1 may not be the immediate next instruction under -O3 }
  13819. RemoveCurrentp(p)
  13820. else
  13821. RemoveCurrentp(p, hp1);
  13822. end;
  13823. Result := True;
  13824. Exit;
  13825. end;
  13826. { Change:
  13827. addl/q $x,%reg1
  13828. movl/q %reg1,%reg2
  13829. To:
  13830. leal/q $x(%reg1),%reg2
  13831. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13832. Breaks the dependency chain.
  13833. }
  13834. if (taicpu(p).oper[0]^.typ = top_const) and
  13835. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13836. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13837. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13838. (
  13839. { Instructions are guaranteed to be adjacent on -O2 and under }
  13840. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13841. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13842. ) then
  13843. begin
  13844. TransferUsedRegs(TmpUsedRegs);
  13845. hp2 := p;
  13846. repeat
  13847. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13848. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13849. if (
  13850. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13851. not (cs_opt_size in current_settings.optimizerswitches) or
  13852. (
  13853. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13854. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13855. )
  13856. ) then
  13857. begin
  13858. { Change the MOV instruction to a LEA instruction, and update the
  13859. first operand }
  13860. reference_reset(NewRef, 1, []);
  13861. NewRef.base := taicpu(p).oper[1]^.reg;
  13862. NewRef.scalefactor := 1;
  13863. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13864. taicpu(hp1).opcode := A_LEA;
  13865. taicpu(hp1).loadref(0, NewRef);
  13866. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13867. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13868. begin
  13869. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13870. { Move what is now the LEA instruction to before the ADD instruction }
  13871. Asml.Remove(hp1);
  13872. Asml.InsertBefore(hp1, p);
  13873. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13874. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13875. p := hp1;
  13876. end
  13877. else
  13878. begin
  13879. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13880. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13881. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13882. { hp1 may not be the immediate next instruction under -O3 }
  13883. RemoveCurrentp(p)
  13884. else
  13885. RemoveCurrentp(p, hp1);
  13886. end;
  13887. Result := True;
  13888. end;
  13889. end;
  13890. end;
  13891. end;
  13892. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13893. var
  13894. SubReg: TSubRegister;
  13895. hp1, hp2: tai;
  13896. CallJmp: Boolean;
  13897. begin
  13898. Result := False;
  13899. CallJmp := False;
  13900. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13901. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13902. with taicpu(p).oper[0]^.ref^ do
  13903. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13904. if (offset = 0) then
  13905. begin
  13906. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13907. begin
  13908. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13909. taicpu(p).opcode := A_ADD;
  13910. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13911. Result := True;
  13912. end
  13913. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13914. begin
  13915. if (base <> NR_NO) then
  13916. begin
  13917. if (scalefactor <= 1) then
  13918. begin
  13919. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13920. taicpu(p).opcode := A_ADD;
  13921. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13922. Result := True;
  13923. end;
  13924. end
  13925. else
  13926. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13927. if (scalefactor in [2, 4, 8]) then
  13928. begin
  13929. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13930. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13931. taicpu(p).opcode := A_SHL;
  13932. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13933. Result := True;
  13934. end;
  13935. end;
  13936. end
  13937. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  13938. lot of latency, so break off the offset if %reg3 is used soon
  13939. afterwards }
  13940. else if not (cs_opt_size in current_settings.optimizerswitches) and
  13941. { If 3-component addresses don't have additional latency, don't
  13942. perform this optimisation }
  13943. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  13944. GetNextInstruction(p, hp1) and
  13945. (
  13946. (
  13947. { Permit jumps and calls since they have a larger degree of overhead }
  13948. (
  13949. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  13950. (
  13951. { ... unless the register specifies the location }
  13952. (taicpu(hp1).ops > 0) and
  13953. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13954. )
  13955. ) and
  13956. (
  13957. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13958. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13959. )
  13960. )
  13961. or
  13962. (
  13963. { Check up to two instructions ahead }
  13964. GetNextInstruction(hp1, hp2) and
  13965. (
  13966. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  13967. (
  13968. { Same as above }
  13969. (taicpu(hp2).ops > 0) and
  13970. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  13971. )
  13972. ) and
  13973. (
  13974. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13975. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  13976. )
  13977. )
  13978. ) then
  13979. begin
  13980. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  13981. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  13982. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13983. offset := 0;
  13984. if Assigned(symbol) or Assigned(relsymbol) then
  13985. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  13986. else
  13987. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  13988. { Inserting before the next instruction rather than after the
  13989. current instruction gives more accurate register tracking }
  13990. asml.InsertBefore(hp2, hp1);
  13991. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  13992. Result := True;
  13993. end;
  13994. end;
  13995. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13996. var
  13997. hp1, hp2: tai;
  13998. NewRef: TReference;
  13999. Distance: Cardinal;
  14000. TempTracking: TAllUsedRegs;
  14001. begin
  14002. Result := False;
  14003. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14004. MatchOpType(taicpu(p),top_const,top_reg) then
  14005. begin
  14006. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14007. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14008. (hp1.typ <> ait_instruction) or
  14009. not
  14010. (
  14011. (cs_opt_level3 in current_settings.optimizerswitches) or
  14012. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14013. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14014. ) then
  14015. Exit;
  14016. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14017. subq $x, %rax
  14018. movq %rax, %rdx
  14019. sarq $63, %rdx
  14020. (%rax still in use)
  14021. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14022. leaq $-x(%rax),%rdx
  14023. movq $x, %rax
  14024. sarq $63, %rdx
  14025. ...which is okay since it breaks the dependency chain between
  14026. subq and movq, but if OptPass2MOV is called first:
  14027. subq $x, %rax
  14028. cqto
  14029. ...which is better in all ways, taking only 2 cycles to execute
  14030. and much smaller in code size.
  14031. }
  14032. { The extra register tracking is quite strenuous }
  14033. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14034. MatchInstruction(hp1, A_MOV, []) then
  14035. begin
  14036. { Update the register tracking to the MOV instruction }
  14037. CopyUsedRegs(TempTracking);
  14038. hp2 := p;
  14039. repeat
  14040. UpdateUsedRegs(tai(hp2.Next));
  14041. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14042. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14043. OptPass2SUB get called again }
  14044. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14045. begin
  14046. { Reset the tracking to the current instruction }
  14047. RestoreUsedRegs(TempTracking);
  14048. ReleaseUsedRegs(TempTracking);
  14049. Result := True;
  14050. Exit;
  14051. end;
  14052. { Reset the tracking to the current instruction }
  14053. RestoreUsedRegs(TempTracking);
  14054. ReleaseUsedRegs(TempTracking);
  14055. { If OptPass2MOV returned True, we don't need to set Result to
  14056. True if hp1 didn't change because the SUB instruction didn't
  14057. get modified and we'll be evaluating hp1 again when the
  14058. peephole optimizer reaches it }
  14059. end;
  14060. { Change:
  14061. subl/q $x,%reg1
  14062. movl/q %reg1,%reg2
  14063. To:
  14064. leal/q $-x(%reg1),%reg2
  14065. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14066. Breaks the dependency chain and potentially permits the removal of
  14067. a CMP instruction if one follows.
  14068. }
  14069. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14070. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14071. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14072. (
  14073. { Instructions are guaranteed to be adjacent on -O2 and under }
  14074. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14075. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14076. ) then
  14077. begin
  14078. TransferUsedRegs(TmpUsedRegs);
  14079. hp2 := p;
  14080. repeat
  14081. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14082. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14083. if (
  14084. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14085. not (cs_opt_size in current_settings.optimizerswitches) or
  14086. (
  14087. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14088. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14089. )
  14090. ) then
  14091. begin
  14092. { Change the MOV instruction to a LEA instruction, and update the
  14093. first operand }
  14094. reference_reset(NewRef, 1, []);
  14095. NewRef.base := taicpu(p).oper[1]^.reg;
  14096. NewRef.scalefactor := 1;
  14097. NewRef.offset := -taicpu(p).oper[0]^.val;
  14098. taicpu(hp1).opcode := A_LEA;
  14099. taicpu(hp1).loadref(0, NewRef);
  14100. TransferUsedRegs(TmpUsedRegs);
  14101. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14102. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14103. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14104. begin
  14105. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14106. { Move what is now the LEA instruction to before the SUB instruction }
  14107. Asml.Remove(hp1);
  14108. Asml.InsertBefore(hp1, p);
  14109. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14110. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14111. p := hp1;
  14112. end
  14113. else
  14114. begin
  14115. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14116. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14117. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14118. { hp1 may not be the immediate next instruction under -O3 }
  14119. RemoveCurrentp(p)
  14120. else
  14121. RemoveCurrentp(p, hp1);
  14122. end;
  14123. Result := True;
  14124. end;
  14125. end;
  14126. end;
  14127. end;
  14128. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14129. begin
  14130. { we can skip all instructions not messing with the stack pointer }
  14131. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14132. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14133. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14134. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14135. ({(taicpu(hp1).ops=0) or }
  14136. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14137. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14138. ) and }
  14139. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14140. )
  14141. ) do
  14142. GetNextInstruction(hp1,hp1);
  14143. Result:=assigned(hp1);
  14144. end;
  14145. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14146. var
  14147. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14148. begin
  14149. Result:=false;
  14150. hp5:=nil;
  14151. hp6:=nil;
  14152. hp7:=nil;
  14153. hp8:=nil;
  14154. { replace
  14155. leal(q) x(<stackpointer>),<stackpointer>
  14156. <optional .seh_stackalloc ...>
  14157. <optional .seh_endprologue ...>
  14158. call procname
  14159. <optional NOP>
  14160. leal(q) -x(<stackpointer>),<stackpointer>
  14161. <optional VZEROUPPER>
  14162. ret
  14163. by
  14164. jmp procname
  14165. but do it only on level 4 because it destroys stack back traces
  14166. }
  14167. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14168. MatchOpType(taicpu(p),top_ref,top_reg) and
  14169. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14170. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14171. { the -8, -24, -40 are not required, but bail out early if possible,
  14172. higher values are unlikely }
  14173. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14174. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14175. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14176. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14177. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14178. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14179. GetNextInstruction(p, hp1) and
  14180. { Take a copy of hp1 }
  14181. SetAndTest(hp1, hp4) and
  14182. { trick to skip label }
  14183. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14184. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14185. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14186. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14187. SkipSimpleInstructions(hp1) and
  14188. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14189. GetNextInstruction(hp1, hp2) and
  14190. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14191. { skip nop instruction on win64 }
  14192. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14193. SetAndTest(hp2,hp6) and
  14194. GetNextInstruction(hp2,hp2) and
  14195. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14196. ) and
  14197. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14198. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14199. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14200. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14201. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14202. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14203. { Segment register will be NR_NO }
  14204. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14205. GetNextInstruction(hp2, hp3) and
  14206. { trick to skip label }
  14207. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14208. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14209. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14210. SetAndTest(hp3,hp5) and
  14211. GetNextInstruction(hp3,hp3) and
  14212. MatchInstruction(hp3,A_RET,[S_NO])
  14213. )
  14214. ) and
  14215. (taicpu(hp3).ops=0) then
  14216. begin
  14217. taicpu(hp1).opcode := A_JMP;
  14218. taicpu(hp1).is_jmp := true;
  14219. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14220. { search for the stackalloc directive and remove it }
  14221. hp7:=tai(p.next);
  14222. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14223. begin
  14224. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14225. begin
  14226. { sanity check }
  14227. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14228. Internalerror(2024012201);
  14229. hp8:=tai(hp7.next);
  14230. RemoveInstruction(tai(hp7));
  14231. hp7:=hp8;
  14232. break;
  14233. end
  14234. else
  14235. hp7:=tai(hp7.next);
  14236. end;
  14237. RemoveCurrentP(p, hp4);
  14238. RemoveInstruction(hp2);
  14239. RemoveInstruction(hp3);
  14240. { if there is a vzeroupper instruction then move it before the jmp }
  14241. if Assigned(hp5) then
  14242. begin
  14243. AsmL.Remove(hp5);
  14244. ASmL.InsertBefore(hp5,hp1)
  14245. end;
  14246. { remove nop on win64 }
  14247. if Assigned(hp6) then
  14248. RemoveInstruction(hp6);
  14249. Result:=true;
  14250. end;
  14251. end;
  14252. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14253. {$ifdef x86_64}
  14254. var
  14255. hp1, hp2, hp3, hp4, hp5: tai;
  14256. {$endif x86_64}
  14257. begin
  14258. Result:=false;
  14259. {$ifdef x86_64}
  14260. hp5:=nil;
  14261. { replace
  14262. push %rax
  14263. call procname
  14264. pop %rcx
  14265. ret
  14266. by
  14267. jmp procname
  14268. but do it only on level 4 because it destroys stack back traces
  14269. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14270. for all supported calling conventions
  14271. }
  14272. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14273. MatchOpType(taicpu(p),top_reg) and
  14274. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14275. GetNextInstruction(p, hp1) and
  14276. { Take a copy of hp1 }
  14277. SetAndTest(hp1, hp4) and
  14278. { trick to skip label }
  14279. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14280. SkipSimpleInstructions(hp1) and
  14281. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14282. GetNextInstruction(hp1, hp2) and
  14283. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14284. MatchOpType(taicpu(hp2),top_reg) and
  14285. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14286. GetNextInstruction(hp2, hp3) and
  14287. { trick to skip label }
  14288. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14289. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14290. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14291. SetAndTest(hp3,hp5) and
  14292. GetNextInstruction(hp3,hp3) and
  14293. MatchInstruction(hp3,A_RET,[S_NO])
  14294. )
  14295. ) and
  14296. (taicpu(hp3).ops=0) then
  14297. begin
  14298. taicpu(hp1).opcode := A_JMP;
  14299. taicpu(hp1).is_jmp := true;
  14300. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14301. RemoveCurrentP(p, hp4);
  14302. RemoveInstruction(hp2);
  14303. RemoveInstruction(hp3);
  14304. if Assigned(hp5) then
  14305. begin
  14306. AsmL.Remove(hp5);
  14307. ASmL.InsertBefore(hp5,hp1)
  14308. end;
  14309. Result:=true;
  14310. end;
  14311. {$endif x86_64}
  14312. end;
  14313. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14314. var
  14315. Value, RegName: string;
  14316. hp1: tai;
  14317. begin
  14318. Result:=false;
  14319. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14320. begin
  14321. case taicpu(p).oper[0]^.val of
  14322. 0:
  14323. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14324. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14325. (
  14326. { See if we can still convert the instruction }
  14327. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14328. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14329. ) then
  14330. begin
  14331. { change "mov $0,%reg" into "xor %reg,%reg" }
  14332. taicpu(p).opcode := A_XOR;
  14333. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14334. Result := True;
  14335. {$ifdef x86_64}
  14336. end
  14337. else if (taicpu(p).opsize = S_Q) then
  14338. begin
  14339. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14340. { The actual optimization }
  14341. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14342. taicpu(p).changeopsize(S_L);
  14343. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14344. Result := True;
  14345. end;
  14346. $1..$FFFFFFFF:
  14347. begin
  14348. { Code size reduction by J. Gareth "Kit" Moreton }
  14349. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14350. case taicpu(p).opsize of
  14351. S_Q:
  14352. begin
  14353. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14354. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14355. { The actual optimization }
  14356. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14357. taicpu(p).changeopsize(S_L);
  14358. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14359. Result := True;
  14360. end;
  14361. else
  14362. { Do nothing };
  14363. end;
  14364. {$endif x86_64}
  14365. end;
  14366. -1:
  14367. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14368. if (cs_opt_size in current_settings.optimizerswitches) and
  14369. (taicpu(p).opsize <> S_B) and
  14370. (
  14371. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14372. (
  14373. { See if we can still convert the instruction }
  14374. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14375. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14376. )
  14377. ) then
  14378. begin
  14379. { change "mov $-1,%reg" into "or $-1,%reg" }
  14380. { NOTES:
  14381. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14382. - This operation creates a false dependency on the register, so only do it when optimising for size
  14383. - 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
  14384. }
  14385. taicpu(p).opcode := A_OR;
  14386. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14387. Result := True;
  14388. end;
  14389. else
  14390. { Do nothing };
  14391. end;
  14392. end;
  14393. end;
  14394. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14395. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14396. begin
  14397. Result := False;
  14398. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14399. Exit;
  14400. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14401. so don't bother optimising }
  14402. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14403. Exit;
  14404. if (taicpu(p).oper[0]^.typ <> top_const) or
  14405. { If the value can fit into an 8-bit signed integer, a smaller
  14406. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14407. falls within this range }
  14408. (
  14409. (taicpu(p).oper[0]^.val > -128) and
  14410. (taicpu(p).oper[0]^.val <= 127)
  14411. ) then
  14412. Exit;
  14413. { If we're optimising for size, this is acceptable }
  14414. if (cs_opt_size in current_settings.optimizerswitches) then
  14415. Exit(True);
  14416. if (taicpu(p).oper[1]^.typ = top_reg) and
  14417. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14418. Exit(True);
  14419. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14420. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14421. Exit(True);
  14422. end;
  14423. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14424. var
  14425. hp1: tai;
  14426. Value: TCGInt;
  14427. begin
  14428. Result := False;
  14429. if MatchOpType(taicpu(p), top_const, top_reg) then
  14430. begin
  14431. { Detect:
  14432. andw x, %ax (0 <= x < $8000)
  14433. ...
  14434. movzwl %ax,%eax
  14435. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14436. }
  14437. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14438. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14439. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14440. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14441. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14442. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14443. begin
  14444. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14445. taicpu(hp1).opcode := A_CWDE;
  14446. taicpu(hp1).clearop(0);
  14447. taicpu(hp1).clearop(1);
  14448. taicpu(hp1).ops := 0;
  14449. { A change was made, but not with p, so don't set Result, but
  14450. notify the compiler that a change was made }
  14451. Include(OptsToCheck, aoc_ForceNewIteration);
  14452. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14453. end;
  14454. end;
  14455. { If "not x" is a power of 2 (popcnt = 1), change:
  14456. and $x, %reg/ref
  14457. To:
  14458. btr lb(x), %reg/ref
  14459. }
  14460. if IsBTXAcceptable(p) and
  14461. (
  14462. { Make sure a TEST doesn't follow that plays with the register }
  14463. not GetNextInstruction(p, hp1) or
  14464. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14465. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14466. ) then
  14467. begin
  14468. {$push}{$R-}{$Q-}
  14469. { Value is a sign-extended 32-bit integer - just correct it
  14470. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14471. checks to see if this operand is an immediate. }
  14472. Value := not taicpu(p).oper[0]^.val;
  14473. {$pop}
  14474. {$ifdef x86_64}
  14475. if taicpu(p).opsize = S_L then
  14476. {$endif x86_64}
  14477. Value := Value and $FFFFFFFF;
  14478. if (PopCnt(QWord(Value)) = 1) then
  14479. begin
  14480. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14481. taicpu(p).opcode := A_BTR;
  14482. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14483. Result := True;
  14484. Exit;
  14485. end;
  14486. end;
  14487. end;
  14488. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14489. begin
  14490. Result := False;
  14491. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14492. Exit;
  14493. { Convert:
  14494. movswl %ax,%eax -> cwtl
  14495. movslq %eax,%rax -> cdqe
  14496. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14497. refer to the same opcode and depends only on the assembler's
  14498. current operand-size attribute. [Kit]
  14499. }
  14500. with taicpu(p) do
  14501. case opsize of
  14502. S_WL:
  14503. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14504. begin
  14505. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14506. opcode := A_CWDE;
  14507. clearop(0);
  14508. clearop(1);
  14509. ops := 0;
  14510. Result := True;
  14511. end;
  14512. {$ifdef x86_64}
  14513. S_LQ:
  14514. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14515. begin
  14516. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14517. opcode := A_CDQE;
  14518. clearop(0);
  14519. clearop(1);
  14520. ops := 0;
  14521. Result := True;
  14522. end;
  14523. {$endif x86_64}
  14524. else
  14525. ;
  14526. end;
  14527. end;
  14528. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14529. var
  14530. hp1, hp2: tai;
  14531. IdentityMask, Shift: TCGInt;
  14532. LimitSize: Topsize;
  14533. DoNotMerge: Boolean;
  14534. begin
  14535. Result := False;
  14536. { All these optimisations work on "shr const,%reg" }
  14537. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14538. Exit;
  14539. DoNotMerge := False;
  14540. Shift := taicpu(p).oper[0]^.val;
  14541. LimitSize := taicpu(p).opsize;
  14542. hp1 := p;
  14543. repeat
  14544. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14545. Break;
  14546. { Detect:
  14547. shr x, %reg
  14548. and y, %reg
  14549. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14550. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14551. }
  14552. case taicpu(hp1).opcode of
  14553. A_AND:
  14554. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14555. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14556. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14557. begin
  14558. { Make sure the FLAGS register isn't in use }
  14559. TransferUsedRegs(TmpUsedRegs);
  14560. hp2 := p;
  14561. repeat
  14562. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14563. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14564. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14565. begin
  14566. { Generate the identity mask }
  14567. case taicpu(p).opsize of
  14568. S_B:
  14569. IdentityMask := $FF shr Shift;
  14570. S_W:
  14571. IdentityMask := $FFFF shr Shift;
  14572. S_L:
  14573. IdentityMask := $FFFFFFFF shr Shift;
  14574. {$ifdef x86_64}
  14575. S_Q:
  14576. { We need to force the operands to be unsigned 64-bit
  14577. integers otherwise the wrong value is generated }
  14578. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14579. {$endif x86_64}
  14580. else
  14581. InternalError(2022081501);
  14582. end;
  14583. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14584. begin
  14585. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14586. { All the possible 1 bits are covered, so we can remove the AND }
  14587. hp2 := tai(hp1.Previous);
  14588. RemoveInstruction(hp1);
  14589. { p wasn't actually changed, so don't set Result to True,
  14590. but a change was nonetheless made elsewhere }
  14591. Include(OptsToCheck, aoc_ForceNewIteration);
  14592. { Do another pass in case other AND or MOVZX instructions
  14593. follow }
  14594. hp1 := hp2;
  14595. Continue;
  14596. end;
  14597. end;
  14598. end;
  14599. A_TEST, A_CMP, A_Jcc:
  14600. { Skip over conditional jumps and relevant comparisons }
  14601. Continue;
  14602. A_MOVZX:
  14603. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14604. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14605. begin
  14606. { Since the original register is being read as is, subsequent
  14607. SHRs must not be merged at this point }
  14608. DoNotMerge := True;
  14609. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14610. begin
  14611. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14612. begin
  14613. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14614. { All the possible 1 bits are covered, so we can remove the AND }
  14615. hp2 := tai(hp1.Previous);
  14616. RemoveInstruction(hp1);
  14617. hp1 := hp2;
  14618. end
  14619. else { Different register target }
  14620. begin
  14621. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14622. taicpu(hp1).opcode := A_MOV;
  14623. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14624. case taicpu(hp1).opsize of
  14625. S_BW:
  14626. taicpu(hp1).opsize := S_W;
  14627. S_BL, S_WL:
  14628. taicpu(hp1).opsize := S_L;
  14629. else
  14630. InternalError(2022081503);
  14631. end;
  14632. end;
  14633. end
  14634. else if (Shift > 0) and
  14635. (taicpu(p).opsize = S_W) and
  14636. (taicpu(hp1).opsize = S_WL) and
  14637. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14638. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14639. begin
  14640. { Detect:
  14641. shr x, %ax (x > 0)
  14642. ...
  14643. movzwl %ax,%eax
  14644. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14645. }
  14646. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14647. taicpu(hp1).opcode := A_CWDE;
  14648. taicpu(hp1).clearop(0);
  14649. taicpu(hp1).clearop(1);
  14650. taicpu(hp1).ops := 0;
  14651. end;
  14652. { Move onto the next instruction }
  14653. Continue;
  14654. end;
  14655. A_SHL, A_SAL, A_SHR:
  14656. if (taicpu(hp1).opsize <= LimitSize) and
  14657. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14658. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14659. begin
  14660. { Make sure the sizes don't exceed the register size limit
  14661. (measured by the shift value falling below the limit) }
  14662. if taicpu(hp1).opsize < LimitSize then
  14663. LimitSize := taicpu(hp1).opsize;
  14664. if taicpu(hp1).opcode = A_SHR then
  14665. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14666. else
  14667. begin
  14668. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14669. DoNotMerge := True;
  14670. end;
  14671. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14672. Break;
  14673. { Since we've established that the combined shift is within
  14674. limits, we can actually combine the adjacent SHR
  14675. instructions even if they're different sizes }
  14676. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14677. begin
  14678. hp2 := tai(hp1.Previous);
  14679. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14680. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14681. RemoveInstruction(hp1);
  14682. hp1 := hp2;
  14683. end;
  14684. { Move onto the next instruction }
  14685. Continue;
  14686. end;
  14687. else
  14688. ;
  14689. end;
  14690. Break;
  14691. until False;
  14692. { Detect the following (looking backwards):
  14693. shr %cl,%reg
  14694. shr x, %reg
  14695. Swap the two SHR instructions to minimise a pipeline stall.
  14696. }
  14697. if GetLastInstruction(p, hp1) and
  14698. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14699. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14700. { First operand will be %cl }
  14701. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14702. { Just to be sure }
  14703. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14704. begin
  14705. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14706. { Moving the entries this way ensures the register tracking remains correct }
  14707. Asml.Remove(p);
  14708. Asml.InsertBefore(p, hp1);
  14709. p := hp1;
  14710. { Don't set Result to True because the current instruction is now
  14711. "shr %cl,%reg" and there's nothing more we can do with it }
  14712. end;
  14713. end;
  14714. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14715. var
  14716. hp1, hp2: tai;
  14717. Opposite, SecondOpposite: TAsmOp;
  14718. NewCond: TAsmCond;
  14719. begin
  14720. Result := False;
  14721. { Change:
  14722. add/sub 128,(dest)
  14723. To:
  14724. sub/add -128,(dest)
  14725. This generaally takes fewer bytes to encode because -128 can be stored
  14726. in a signed byte, whereas +128 cannot.
  14727. }
  14728. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14729. begin
  14730. if taicpu(p).opcode = A_ADD then
  14731. Opposite := A_SUB
  14732. else
  14733. Opposite := A_ADD;
  14734. { Be careful if the flags are in use, because the CF flag inverts
  14735. when changing from ADD to SUB and vice versa }
  14736. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14737. GetNextInstruction(p, hp1) then
  14738. begin
  14739. TransferUsedRegs(TmpUsedRegs);
  14740. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14741. hp2 := hp1;
  14742. { Scan ahead to check if everything's safe }
  14743. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14744. begin
  14745. if (hp1.typ <> ait_instruction) then
  14746. { Probably unsafe since the flags are still in use }
  14747. Exit;
  14748. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14749. { Stop searching at an unconditional jump }
  14750. Break;
  14751. if not
  14752. (
  14753. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14754. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14755. ) and
  14756. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14757. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14758. Exit;
  14759. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14760. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14761. { Move to the next instruction }
  14762. GetNextInstruction(hp1, hp1);
  14763. end;
  14764. while Assigned(hp2) and (hp2 <> hp1) do
  14765. begin
  14766. NewCond := C_None;
  14767. case taicpu(hp2).condition of
  14768. C_A, C_NBE:
  14769. NewCond := C_BE;
  14770. C_B, C_C, C_NAE:
  14771. NewCond := C_AE;
  14772. C_AE, C_NB, C_NC:
  14773. NewCond := C_B;
  14774. C_BE, C_NA:
  14775. NewCond := C_A;
  14776. else
  14777. { No change needed };
  14778. end;
  14779. if NewCond <> C_None then
  14780. begin
  14781. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14782. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14783. taicpu(hp2).condition := NewCond;
  14784. end
  14785. else
  14786. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14787. begin
  14788. { Because of the flipping of the carry bit, to ensure
  14789. the operation remains equivalent, ADC becomes SBB
  14790. and vice versa, and the constant is not-inverted.
  14791. If multiple ADCs or SBBs appear in a row, each one
  14792. changed causes the carry bit to invert, so they all
  14793. need to be flipped }
  14794. if taicpu(hp2).opcode = A_ADC then
  14795. SecondOpposite := A_SBB
  14796. else
  14797. SecondOpposite := A_ADC;
  14798. if taicpu(hp2).oper[0]^.typ <> top_const then
  14799. { Should have broken out of this optimisation already }
  14800. InternalError(2021112901);
  14801. 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]^) + ' -> ' +
  14802. 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);
  14803. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14804. taicpu(hp2).opcode := SecondOpposite;
  14805. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14806. end;
  14807. { Move to the next instruction }
  14808. GetNextInstruction(hp2, hp2);
  14809. end;
  14810. if (hp2 <> hp1) then
  14811. InternalError(2021111501);
  14812. end;
  14813. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14814. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14815. taicpu(p).opcode := Opposite;
  14816. taicpu(p).oper[0]^.val := -128;
  14817. { No further optimisations can be made on this instruction, so move
  14818. onto the next one to save time }
  14819. p := tai(p.Next);
  14820. UpdateUsedRegs(p);
  14821. Result := True;
  14822. Exit;
  14823. end;
  14824. { Detect:
  14825. add/sub %reg2,(dest)
  14826. add/sub x, (dest)
  14827. (dest can be a register or a reference)
  14828. Swap the instructions to minimise a pipeline stall. This reverses the
  14829. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14830. optimisations could be made.
  14831. }
  14832. if (taicpu(p).oper[0]^.typ = top_reg) and
  14833. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14834. (
  14835. (
  14836. (taicpu(p).oper[1]^.typ = top_reg) and
  14837. { We can try searching further ahead if we're writing to a register }
  14838. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14839. ) or
  14840. (
  14841. (taicpu(p).oper[1]^.typ = top_ref) and
  14842. GetNextInstruction(p, hp1)
  14843. )
  14844. ) and
  14845. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14846. (taicpu(hp1).oper[0]^.typ = top_const) and
  14847. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14848. begin
  14849. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14850. TransferUsedRegs(TmpUsedRegs);
  14851. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14852. hp2 := p;
  14853. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14854. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14855. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14856. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14857. begin
  14858. asml.remove(hp1);
  14859. asml.InsertBefore(hp1, p);
  14860. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14861. Result := True;
  14862. end;
  14863. end;
  14864. end;
  14865. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14866. var
  14867. hp1: tai;
  14868. begin
  14869. Result:=false;
  14870. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14871. while GetNextInstruction(p, hp1) and
  14872. TrySwapMovCmp(p, hp1) do
  14873. begin
  14874. if MatchInstruction(hp1, A_MOV, []) then
  14875. begin
  14876. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14877. begin
  14878. { A little hacky, but since CMP doesn't read the flags, only
  14879. modify them, it's safe if they get scrambled by MOV -> XOR }
  14880. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14881. Result := PostPeepholeOptMov(hp1);
  14882. {$ifdef x86_64}
  14883. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14884. { Used to shrink instruction size }
  14885. PostPeepholeOptXor(hp1);
  14886. {$endif x86_64}
  14887. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14888. end
  14889. else
  14890. begin
  14891. Result := PostPeepholeOptMov(hp1);
  14892. {$ifdef x86_64}
  14893. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14894. { Used to shrink instruction size }
  14895. PostPeepholeOptXor(hp1);
  14896. {$endif x86_64}
  14897. end;
  14898. end;
  14899. { Enabling this flag is actually a null operation, but it marks
  14900. the code as 'modified' during this pass }
  14901. Include(OptsToCheck, aoc_ForceNewIteration);
  14902. end;
  14903. { change "cmp $0, %reg" to "test %reg, %reg" }
  14904. if MatchOpType(taicpu(p),top_const,top_reg) and
  14905. (taicpu(p).oper[0]^.val = 0) then
  14906. begin
  14907. taicpu(p).opcode := A_TEST;
  14908. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14909. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14910. Result:=true;
  14911. end;
  14912. end;
  14913. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14914. var
  14915. IsTestConstX, IsValid : Boolean;
  14916. hp1,hp2 : tai;
  14917. begin
  14918. Result:=false;
  14919. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14920. if (taicpu(p).opcode = A_TEST) then
  14921. while GetNextInstruction(p, hp1) and
  14922. TrySwapMovCmp(p, hp1) do
  14923. begin
  14924. if MatchInstruction(hp1, A_MOV, []) then
  14925. begin
  14926. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14927. begin
  14928. { A little hacky, but since TEST doesn't read the flags, only
  14929. modify them, it's safe if they get scrambled by MOV -> XOR }
  14930. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14931. Result := PostPeepholeOptMov(hp1);
  14932. {$ifdef x86_64}
  14933. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14934. { Used to shrink instruction size }
  14935. PostPeepholeOptXor(hp1);
  14936. {$endif x86_64}
  14937. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14938. end
  14939. else
  14940. begin
  14941. Result := PostPeepholeOptMov(hp1);
  14942. {$ifdef x86_64}
  14943. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14944. { Used to shrink instruction size }
  14945. PostPeepholeOptXor(hp1);
  14946. {$endif x86_64}
  14947. end;
  14948. end;
  14949. { Enabling this flag is actually a null operation, but it marks
  14950. the code as 'modified' during this pass }
  14951. Include(OptsToCheck, aoc_ForceNewIteration);
  14952. end;
  14953. { If x is a power of 2 (popcnt = 1), change:
  14954. or $x, %reg/ref
  14955. To:
  14956. bts lb(x), %reg/ref
  14957. }
  14958. if (taicpu(p).opcode = A_OR) and
  14959. IsBTXAcceptable(p) and
  14960. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14961. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14962. (
  14963. { Don't optimise if a test instruction follows }
  14964. not GetNextInstruction(p, hp1) or
  14965. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14966. ) then
  14967. begin
  14968. 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);
  14969. taicpu(p).opcode := A_BTS;
  14970. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14971. Result := True;
  14972. Exit;
  14973. end;
  14974. { If x is a power of 2 (popcnt = 1), change:
  14975. test $x, %reg/ref
  14976. je / sete / cmove (or jne / setne)
  14977. To:
  14978. bt lb(x), %reg/ref
  14979. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14980. }
  14981. if (taicpu(p).opcode = A_TEST) and
  14982. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14983. (taicpu(p).oper[0]^.typ = top_const) and
  14984. (
  14985. (cs_opt_size in current_settings.optimizerswitches) or
  14986. (
  14987. (taicpu(p).oper[1]^.typ = top_reg) and
  14988. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14989. ) or
  14990. (
  14991. (taicpu(p).oper[1]^.typ <> top_reg) and
  14992. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14993. )
  14994. ) and
  14995. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14996. { For sizes less than S_L, the byte size is equal or larger with BT,
  14997. so don't bother optimising }
  14998. (taicpu(p).opsize >= S_L) then
  14999. begin
  15000. IsValid := True;
  15001. { Check the next set of instructions, watching the FLAGS register
  15002. and the conditions used }
  15003. TransferUsedRegs(TmpUsedRegs);
  15004. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15005. hp1 := p;
  15006. hp2 := nil;
  15007. while GetNextInstruction(hp1, hp1) do
  15008. begin
  15009. if not Assigned(hp2) then
  15010. { The first instruction after TEST }
  15011. hp2 := hp1;
  15012. if (hp1.typ <> ait_instruction) then
  15013. begin
  15014. { If the flags are no longer in use, everything is fine }
  15015. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15016. IsValid := False;
  15017. Break;
  15018. end;
  15019. case taicpu(hp1).condition of
  15020. C_None:
  15021. begin
  15022. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15023. { Something is not quite normal, so play safe and don't change }
  15024. IsValid := False;
  15025. Break;
  15026. end;
  15027. C_E, C_Z, C_NE, C_NZ:
  15028. { This is fine };
  15029. else
  15030. begin
  15031. { Unsupported condition }
  15032. IsValid := False;
  15033. Break;
  15034. end;
  15035. end;
  15036. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15037. end;
  15038. if IsValid then
  15039. begin
  15040. while hp2 <> hp1 do
  15041. begin
  15042. case taicpu(hp2).condition of
  15043. C_Z, C_E:
  15044. taicpu(hp2).condition := C_NC;
  15045. C_NZ, C_NE:
  15046. taicpu(hp2).condition := C_C;
  15047. else
  15048. { Should not get this by this point }
  15049. InternalError(2022110701);
  15050. end;
  15051. GetNextInstruction(hp2, hp2);
  15052. end;
  15053. 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);
  15054. taicpu(p).opcode := A_BT;
  15055. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15056. Result := True;
  15057. Exit;
  15058. end;
  15059. end;
  15060. { removes the line marked with (x) from the sequence
  15061. and/or/xor/add/sub/... $x, %y
  15062. test/or %y, %y | test $-1, %y (x)
  15063. j(n)z _Label
  15064. as the first instruction already adjusts the ZF
  15065. %y operand may also be a reference }
  15066. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15067. MatchOperand(taicpu(p).oper[0]^,-1);
  15068. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15069. GetLastInstruction(p, hp1) and
  15070. (tai(hp1).typ = ait_instruction) and
  15071. GetNextInstruction(p,hp2) and
  15072. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15073. case taicpu(hp1).opcode Of
  15074. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15075. { These two instructions set the zero flag if the result is zero }
  15076. A_POPCNT, A_LZCNT:
  15077. begin
  15078. if (
  15079. { With POPCNT, an input of zero will set the zero flag
  15080. because the population count of zero is zero }
  15081. (taicpu(hp1).opcode = A_POPCNT) and
  15082. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15083. (
  15084. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15085. { Faster than going through the second half of the 'or'
  15086. condition below }
  15087. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15088. )
  15089. ) or (
  15090. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15091. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15092. { and in case of carry for A(E)/B(E)/C/NC }
  15093. (
  15094. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15095. (
  15096. (taicpu(hp1).opcode <> A_ADD) and
  15097. (taicpu(hp1).opcode <> A_SUB) and
  15098. (taicpu(hp1).opcode <> A_LZCNT)
  15099. )
  15100. )
  15101. ) then
  15102. begin
  15103. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15104. RemoveCurrentP(p, hp2);
  15105. Result:=true;
  15106. Exit;
  15107. end;
  15108. end;
  15109. A_SHL, A_SAL, A_SHR, A_SAR:
  15110. begin
  15111. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15112. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15113. { therefore, it's only safe to do this optimization for }
  15114. { shifts by a (nonzero) constant }
  15115. (taicpu(hp1).oper[0]^.typ = top_const) and
  15116. (taicpu(hp1).oper[0]^.val <> 0) and
  15117. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15118. { and in case of carry for A(E)/B(E)/C/NC }
  15119. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15120. begin
  15121. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15122. RemoveCurrentP(p, hp2);
  15123. Result:=true;
  15124. Exit;
  15125. end;
  15126. end;
  15127. A_DEC, A_INC, A_NEG:
  15128. begin
  15129. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15130. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15131. { and in case of carry for A(E)/B(E)/C/NC }
  15132. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15133. begin
  15134. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15135. RemoveCurrentP(p, hp2);
  15136. Result:=true;
  15137. Exit;
  15138. end;
  15139. end;
  15140. A_ANDN, A_BZHI:
  15141. begin
  15142. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15143. { Only the zero and sign flags are consistent with what the result is }
  15144. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15145. begin
  15146. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15147. RemoveCurrentP(p, hp2);
  15148. Result:=true;
  15149. Exit;
  15150. end;
  15151. end;
  15152. A_BEXTR:
  15153. begin
  15154. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15155. { Only the zero flag is set }
  15156. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15157. begin
  15158. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15159. RemoveCurrentP(p, hp2);
  15160. Result:=true;
  15161. Exit;
  15162. end;
  15163. end;
  15164. else
  15165. ;
  15166. end; { case }
  15167. { change "test $-1,%reg" into "test %reg,%reg" }
  15168. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15169. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15170. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15171. if MatchInstruction(p, A_OR, []) and
  15172. { Can only match if they're both registers }
  15173. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15174. begin
  15175. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15176. taicpu(p).opcode := A_TEST;
  15177. { No need to set Result to True, as we've done all the optimisations we can }
  15178. end;
  15179. end;
  15180. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15181. var
  15182. hp1,hp3 : tai;
  15183. {$ifndef x86_64}
  15184. hp2 : taicpu;
  15185. {$endif x86_64}
  15186. begin
  15187. Result:=false;
  15188. hp3:=nil;
  15189. {$ifndef x86_64}
  15190. { don't do this on modern CPUs, this really hurts them due to
  15191. broken call/ret pairing }
  15192. if (current_settings.optimizecputype < cpu_Pentium2) and
  15193. not(cs_create_pic in current_settings.moduleswitches) and
  15194. GetNextInstruction(p, hp1) and
  15195. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15196. MatchOpType(taicpu(hp1),top_ref) and
  15197. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15198. begin
  15199. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15200. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15201. InsertLLItem(p.previous, p, hp2);
  15202. taicpu(p).opcode := A_JMP;
  15203. taicpu(p).is_jmp := true;
  15204. RemoveInstruction(hp1);
  15205. Result:=true;
  15206. end
  15207. else
  15208. {$endif x86_64}
  15209. { replace
  15210. call procname
  15211. ret
  15212. by
  15213. jmp procname
  15214. but do it only on level 4 because it destroys stack back traces
  15215. else if the subroutine is marked as no return, remove the ret
  15216. }
  15217. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15218. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15219. GetNextInstruction(p, hp1) and
  15220. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15221. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15222. SetAndTest(hp1,hp3) and
  15223. GetNextInstruction(hp1,hp1) and
  15224. MatchInstruction(hp1,A_RET,[S_NO])
  15225. )
  15226. ) and
  15227. (taicpu(hp1).ops=0) then
  15228. begin
  15229. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15230. { we might destroy stack alignment here if we do not do a call }
  15231. (target_info.stackalign<=sizeof(SizeUInt)) then
  15232. begin
  15233. taicpu(p).opcode := A_JMP;
  15234. taicpu(p).is_jmp := true;
  15235. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15236. end
  15237. else
  15238. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15239. RemoveInstruction(hp1);
  15240. if Assigned(hp3) then
  15241. begin
  15242. AsmL.Remove(hp3);
  15243. AsmL.InsertBefore(hp3,p)
  15244. end;
  15245. Result:=true;
  15246. end;
  15247. end;
  15248. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15249. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15250. begin
  15251. case OpSize of
  15252. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15253. Result := (Val <= $FF) and (Val >= -128);
  15254. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15255. Result := (Val <= $FFFF) and (Val >= -32768);
  15256. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15257. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15258. else
  15259. Result := True;
  15260. end;
  15261. end;
  15262. var
  15263. hp1, hp2 : tai;
  15264. SizeChange: Boolean;
  15265. PreMessage: string;
  15266. begin
  15267. Result := False;
  15268. if (taicpu(p).oper[0]^.typ = top_reg) and
  15269. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15270. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15271. begin
  15272. { Change (using movzbl %al,%eax as an example):
  15273. movzbl %al, %eax movzbl %al, %eax
  15274. cmpl x, %eax testl %eax,%eax
  15275. To:
  15276. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15277. movzbl %al, %eax movzbl %al, %eax
  15278. Smaller instruction and minimises pipeline stall as the CPU
  15279. doesn't have to wait for the register to get zero-extended. [Kit]
  15280. Also allow if the smaller of the two registers is being checked,
  15281. as this still removes the false dependency.
  15282. }
  15283. if
  15284. (
  15285. (
  15286. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15287. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15288. ) or (
  15289. { If MatchOperand returns True, they must both be registers }
  15290. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15291. )
  15292. ) and
  15293. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15294. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15295. begin
  15296. 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);
  15297. asml.Remove(hp1);
  15298. asml.InsertBefore(hp1, p);
  15299. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15300. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15301. begin
  15302. taicpu(hp1).opcode := A_TEST;
  15303. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15304. end;
  15305. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15306. case taicpu(p).opsize of
  15307. S_BW, S_BL:
  15308. begin
  15309. SizeChange := taicpu(hp1).opsize <> S_B;
  15310. taicpu(hp1).changeopsize(S_B);
  15311. end;
  15312. S_WL:
  15313. begin
  15314. SizeChange := taicpu(hp1).opsize <> S_W;
  15315. taicpu(hp1).changeopsize(S_W);
  15316. end
  15317. else
  15318. InternalError(2020112701);
  15319. end;
  15320. UpdateUsedRegs(tai(p.Next));
  15321. { Check if the register is used aferwards - if not, we can
  15322. remove the movzx instruction completely }
  15323. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15324. begin
  15325. { Hp1 is a better position than p for debugging purposes }
  15326. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15327. RemoveCurrentp(p, hp1);
  15328. Result := True;
  15329. end;
  15330. if SizeChange then
  15331. DebugMsg(SPeepholeOptimization + PreMessage +
  15332. 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)
  15333. else
  15334. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15335. Exit;
  15336. end;
  15337. { Change (using movzwl %ax,%eax as an example):
  15338. movzwl %ax, %eax
  15339. movb %al, (dest) (Register is smaller than read register in movz)
  15340. To:
  15341. movb %al, (dest) (Move one back to avoid a false dependency)
  15342. movzwl %ax, %eax
  15343. }
  15344. if (taicpu(hp1).opcode = A_MOV) and
  15345. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15346. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15347. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15348. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15349. begin
  15350. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15351. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15352. asml.Remove(hp1);
  15353. asml.InsertBefore(hp1, p);
  15354. if taicpu(hp1).oper[1]^.typ = top_reg then
  15355. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15356. { Check if the register is used aferwards - if not, we can
  15357. remove the movzx instruction completely }
  15358. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15359. begin
  15360. { Hp1 is a better position than p for debugging purposes }
  15361. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15362. RemoveCurrentp(p, hp1);
  15363. Result := True;
  15364. end;
  15365. Exit;
  15366. end;
  15367. end;
  15368. end;
  15369. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15370. var
  15371. hp1: tai;
  15372. {$ifdef x86_64}
  15373. PreMessage, RegName: string;
  15374. {$endif x86_64}
  15375. begin
  15376. Result := False;
  15377. { If x is a power of 2 (popcnt = 1), change:
  15378. xor $x, %reg/ref
  15379. To:
  15380. btc lb(x), %reg/ref
  15381. }
  15382. if IsBTXAcceptable(p) and
  15383. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15384. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15385. (
  15386. { Don't optimise if a test instruction follows }
  15387. not GetNextInstruction(p, hp1) or
  15388. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15389. ) then
  15390. begin
  15391. 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);
  15392. taicpu(p).opcode := A_BTC;
  15393. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15394. Result := True;
  15395. Exit;
  15396. end;
  15397. {$ifdef x86_64}
  15398. { Code size reduction by J. Gareth "Kit" Moreton }
  15399. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15400. as this removes the REX prefix }
  15401. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15402. Exit;
  15403. if taicpu(p).oper[0]^.typ <> top_reg then
  15404. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15405. InternalError(2018011500);
  15406. case taicpu(p).opsize of
  15407. S_Q:
  15408. begin
  15409. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15410. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15411. { The actual optimization }
  15412. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15413. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15414. taicpu(p).changeopsize(S_L);
  15415. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15416. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15417. end;
  15418. else
  15419. ;
  15420. end;
  15421. {$endif x86_64}
  15422. end;
  15423. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15424. var
  15425. XReg: TRegister;
  15426. begin
  15427. Result := False;
  15428. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15429. Smaller encoding and slightly faster on some platforms (also works for
  15430. ZMM-sized registers) }
  15431. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15432. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15433. begin
  15434. XReg := taicpu(p).oper[0]^.reg;
  15435. if (taicpu(p).oper[1]^.reg = XReg) then
  15436. begin
  15437. taicpu(p).changeopsize(S_XMM);
  15438. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15439. if (cs_opt_size in current_settings.optimizerswitches) then
  15440. begin
  15441. { Change input registers to %xmm0 to reduce size. Note that
  15442. there's a risk of a false dependency doing this, so only
  15443. optimise for size here }
  15444. XReg := NR_XMM0;
  15445. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15446. end
  15447. else
  15448. begin
  15449. setsubreg(XReg, R_SUBMMX);
  15450. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15451. end;
  15452. taicpu(p).oper[0]^.reg := XReg;
  15453. taicpu(p).oper[1]^.reg := XReg;
  15454. Result := True;
  15455. end;
  15456. end;
  15457. end;
  15458. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15459. var
  15460. OperIdx: Integer;
  15461. begin
  15462. for OperIdx := 0 to p.ops - 1 do
  15463. if p.oper[OperIdx]^.typ = top_ref then
  15464. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15465. end;
  15466. end.