aoptx86.pas 561 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152
  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,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  108. function PrePeepholeOptSxx(var p : tai) : boolean;
  109. function PrePeepholeOptIMUL(var p : tai) : boolean;
  110. function PrePeepholeOptAND(var p : tai) : boolean;
  111. function OptPass1Test(var p: tai): boolean;
  112. function OptPass1Add(var p: tai): boolean;
  113. function OptPass1AND(var p : tai) : boolean;
  114. function OptPass1_V_MOVAP(var p : tai) : boolean;
  115. function OptPass1VOP(var p : tai) : boolean;
  116. function OptPass1MOV(var p : tai) : boolean;
  117. function OptPass1Movx(var p : tai) : boolean;
  118. function OptPass1MOVXX(var p : tai) : boolean;
  119. function OptPass1OP(var p : tai) : boolean;
  120. function OptPass1LEA(var p : tai) : boolean;
  121. function OptPass1Sub(var p : tai) : boolean;
  122. function OptPass1SHLSAL(var p : tai) : boolean;
  123. function OptPass1FSTP(var p : tai) : boolean;
  124. function OptPass1FLD(var p : tai) : boolean;
  125. function OptPass1Cmp(var p : tai) : boolean;
  126. function OptPass1PXor(var p : tai) : boolean;
  127. function OptPass1VPXor(var p: tai): boolean;
  128. function OptPass1Imul(var p : tai) : boolean;
  129. function OptPass1Jcc(var p : tai) : boolean;
  130. function OptPass1SHXX(var p: tai): boolean;
  131. function OptPass1VMOVDQ(var p: tai): Boolean;
  132. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  133. function OptPass2Movx(var p : tai): Boolean;
  134. function OptPass2MOV(var p : tai) : boolean;
  135. function OptPass2Imul(var p : tai) : boolean;
  136. function OptPass2Jmp(var p : tai) : boolean;
  137. function OptPass2Jcc(var p : tai) : boolean;
  138. function OptPass2Lea(var p: tai): Boolean;
  139. function OptPass2SUB(var p: tai): Boolean;
  140. function OptPass2ADD(var p : tai): Boolean;
  141. function OptPass2SETcc(var p : tai) : boolean;
  142. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  143. function PostPeepholeOptMov(var p : tai) : Boolean;
  144. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  145. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  146. function PostPeepholeOptXor(var p : tai) : Boolean;
  147. {$endif x86_64}
  148. function PostPeepholeOptAnd(var p : tai) : boolean;
  149. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  150. function PostPeepholeOptCmp(var p : tai) : Boolean;
  151. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  152. function PostPeepholeOptCall(var p : tai) : Boolean;
  153. function PostPeepholeOptLea(var p : tai) : Boolean;
  154. function PostPeepholeOptPush(var p: tai): Boolean;
  155. function PostPeepholeOptShr(var p : tai) : boolean;
  156. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  157. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  158. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  159. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  160. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  161. { Processor-dependent reference optimisation }
  162. class procedure OptimizeRefs(var p: taicpu); static;
  163. end;
  164. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  168. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  169. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  170. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  171. {$if max_operands>2}
  172. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  173. {$endif max_operands>2}
  174. function RefsEqual(const r1, r2: treference): boolean;
  175. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  176. { returns true, if ref is a reference using only the registers passed as base and index
  177. and having an offset }
  178. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  179. implementation
  180. uses
  181. cutils,verbose,
  182. systems,
  183. globals,
  184. cpuinfo,
  185. procinfo,
  186. paramgr,
  187. aasmbase,
  188. aoptbase,aoptutils,
  189. symconst,symsym,
  190. cgx86,
  191. itcpugas;
  192. {$ifdef DEBUG_AOPTCPU}
  193. const
  194. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  195. {$else DEBUG_AOPTCPU}
  196. { Empty strings help the optimizer to remove string concatenations that won't
  197. ever appear to the user on release builds. [Kit] }
  198. const
  199. SPeepholeOptimization = '';
  200. {$endif DEBUG_AOPTCPU}
  201. LIST_STEP_SIZE = 4;
  202. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  203. begin
  204. result :=
  205. (instr.typ = ait_instruction) and
  206. (taicpu(instr).opcode = op) and
  207. ((opsize = []) or (taicpu(instr).opsize in opsize));
  208. end;
  209. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  210. begin
  211. result :=
  212. (instr.typ = ait_instruction) and
  213. ((taicpu(instr).opcode = op1) or
  214. (taicpu(instr).opcode = op2)
  215. ) and
  216. ((opsize = []) or (taicpu(instr).opsize in opsize));
  217. end;
  218. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  219. begin
  220. result :=
  221. (instr.typ = ait_instruction) and
  222. ((taicpu(instr).opcode = op1) or
  223. (taicpu(instr).opcode = op2) or
  224. (taicpu(instr).opcode = op3)
  225. ) and
  226. ((opsize = []) or (taicpu(instr).opsize in opsize));
  227. end;
  228. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  229. const opsize : topsizes) : boolean;
  230. var
  231. op : TAsmOp;
  232. begin
  233. result:=false;
  234. if (instr.typ <> ait_instruction) or
  235. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  236. exit;
  237. for op in ops do
  238. begin
  239. if taicpu(instr).opcode = op then
  240. begin
  241. result:=true;
  242. exit;
  243. end;
  244. end;
  245. end;
  246. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  247. begin
  248. result := (oper.typ = top_reg) and (oper.reg = reg);
  249. end;
  250. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  251. begin
  252. result := (oper.typ = top_const) and (oper.val = a);
  253. end;
  254. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  255. begin
  256. result := oper1.typ = oper2.typ;
  257. if result then
  258. case oper1.typ of
  259. top_const:
  260. Result:=oper1.val = oper2.val;
  261. top_reg:
  262. Result:=oper1.reg = oper2.reg;
  263. top_ref:
  264. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  265. else
  266. internalerror(2013102801);
  267. end
  268. end;
  269. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  270. begin
  271. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  272. if result then
  273. case oper1.typ of
  274. top_const:
  275. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  276. top_reg:
  277. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  278. top_ref:
  279. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  280. else
  281. internalerror(2020052401);
  282. end
  283. end;
  284. function RefsEqual(const r1, r2: treference): boolean;
  285. begin
  286. RefsEqual :=
  287. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  288. (r1.relsymbol = r2.relsymbol) and
  289. (r1.segment = r2.segment) and (r1.base = r2.base) and
  290. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  291. (r1.offset = r2.offset) and
  292. (r1.volatility + r2.volatility = []);
  293. end;
  294. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  295. begin
  296. Result:=(ref.offset=0) and
  297. (ref.scalefactor in [0,1]) and
  298. (ref.segment=NR_NO) and
  299. (ref.symbol=nil) and
  300. (ref.relsymbol=nil) and
  301. ((base=NR_INVALID) or
  302. (ref.base=base)) and
  303. ((index=NR_INVALID) or
  304. (ref.index=index)) and
  305. (ref.volatility=[]);
  306. end;
  307. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  308. begin
  309. Result:=(ref.scalefactor in [0,1]) and
  310. (ref.segment=NR_NO) and
  311. (ref.symbol=nil) and
  312. (ref.relsymbol=nil) and
  313. ((base=NR_INVALID) or
  314. (ref.base=base)) and
  315. ((index=NR_INVALID) or
  316. (ref.index=index)) and
  317. (ref.volatility=[]);
  318. end;
  319. function InstrReadsFlags(p: tai): boolean;
  320. begin
  321. InstrReadsFlags := true;
  322. case p.typ of
  323. ait_instruction:
  324. if InsProp[taicpu(p).opcode].Ch*
  325. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  326. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  327. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  328. exit;
  329. ait_label:
  330. exit;
  331. else
  332. ;
  333. end;
  334. InstrReadsFlags := false;
  335. end;
  336. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  337. begin
  338. Next:=Current;
  339. repeat
  340. Result:=GetNextInstruction(Next,Next);
  341. until not (Result) or
  342. not(cs_opt_level3 in current_settings.optimizerswitches) or
  343. (Next.typ<>ait_instruction) or
  344. RegInInstruction(reg,Next) or
  345. is_calljmp(taicpu(Next).opcode);
  346. end;
  347. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  348. begin
  349. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  350. Next := Current;
  351. repeat
  352. Result := GetNextInstruction(Next,Next);
  353. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  354. if is_calljmpuncondret(taicpu(Next).opcode) then
  355. begin
  356. Result := False;
  357. Exit;
  358. end
  359. else
  360. CrossJump := True;
  361. until not Result or
  362. not (cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ <> ait_instruction) or
  364. RegInInstruction(reg,Next);
  365. end;
  366. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  367. begin
  368. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  369. begin
  370. Result:=GetNextInstruction(Current,Next);
  371. exit;
  372. end;
  373. Next:=tai(Current.Next);
  374. Result:=false;
  375. while assigned(Next) do
  376. begin
  377. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  378. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  379. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  380. exit
  381. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  382. begin
  383. Result:=true;
  384. exit;
  385. end;
  386. Next:=tai(Next.Next);
  387. end;
  388. end;
  389. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  390. begin
  391. Result:=RegReadByInstruction(reg,hp);
  392. end;
  393. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  394. var
  395. p: taicpu;
  396. opcount: longint;
  397. begin
  398. RegReadByInstruction := false;
  399. if hp.typ <> ait_instruction then
  400. exit;
  401. p := taicpu(hp);
  402. case p.opcode of
  403. A_CALL:
  404. regreadbyinstruction := true;
  405. A_IMUL:
  406. case p.ops of
  407. 1:
  408. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  409. (
  410. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  411. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  412. );
  413. 2,3:
  414. regReadByInstruction :=
  415. reginop(reg,p.oper[0]^) or
  416. reginop(reg,p.oper[1]^);
  417. else
  418. InternalError(2019112801);
  419. end;
  420. A_MUL:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  425. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  426. );
  427. end;
  428. A_IDIV,A_DIV:
  429. begin
  430. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  431. (
  432. (getregtype(reg)=R_INTREGISTER) and
  433. (
  434. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  435. )
  436. );
  437. end;
  438. else
  439. begin
  440. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  441. begin
  442. RegReadByInstruction := false;
  443. exit;
  444. end;
  445. for opcount := 0 to p.ops-1 do
  446. if (p.oper[opCount]^.typ = top_ref) and
  447. RegInRef(reg,p.oper[opcount]^.ref^) then
  448. begin
  449. RegReadByInstruction := true;
  450. exit
  451. end;
  452. { special handling for SSE MOVSD }
  453. if (p.opcode=A_MOVSD) and (p.ops>0) then
  454. begin
  455. if p.ops<>2 then
  456. internalerror(2017042702);
  457. regReadByInstruction := reginop(reg,p.oper[0]^) or
  458. (
  459. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  460. );
  461. exit;
  462. end;
  463. with insprop[p.opcode] do
  464. begin
  465. case getregtype(reg) of
  466. R_INTREGISTER:
  467. begin
  468. case getsupreg(reg) of
  469. RS_EAX:
  470. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ECX:
  476. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EDX:
  482. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_EBX:
  488. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_ESP:
  494. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. RS_EBP:
  500. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  501. begin
  502. RegReadByInstruction := true;
  503. exit
  504. end;
  505. RS_ESI:
  506. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  507. begin
  508. RegReadByInstruction := true;
  509. exit
  510. end;
  511. RS_EDI:
  512. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  513. begin
  514. RegReadByInstruction := true;
  515. exit
  516. end;
  517. end;
  518. end;
  519. R_MMREGISTER:
  520. begin
  521. case getsupreg(reg) of
  522. RS_XMM0:
  523. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  524. begin
  525. RegReadByInstruction := true;
  526. exit
  527. end;
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  534. begin
  535. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  536. begin
  537. case p.condition of
  538. C_A,C_NBE, { CF=0 and ZF=0 }
  539. C_BE,C_NA: { CF=1 or ZF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  541. C_AE,C_NB,C_NC, { CF=0 }
  542. C_B,C_NAE,C_C: { CF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  544. C_NE,C_NZ, { ZF=0 }
  545. C_E,C_Z: { ZF=1 }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  547. C_G,C_NLE, { ZF=0 and SF=OF }
  548. C_LE,C_NG: { ZF=1 or SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_GE,C_NL, { SF=OF }
  551. C_L,C_NGE: { SF<>OF }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  553. C_NO, { OF=0 }
  554. C_O: { OF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  556. C_NP,C_PO, { PF=0 }
  557. C_P,C_PE: { PF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  559. C_NS, { SF=0 }
  560. C_S: { SF=1 }
  561. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  562. else
  563. internalerror(2017042701);
  564. end;
  565. if RegReadByInstruction then
  566. exit;
  567. end;
  568. case getsubreg(reg) of
  569. R_SUBW,R_SUBD,R_SUBQ:
  570. RegReadByInstruction :=
  571. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  572. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  573. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  574. R_SUBFLAGCARRY:
  575. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  576. R_SUBFLAGPARITY:
  577. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  578. R_SUBFLAGAUXILIARY:
  579. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  580. R_SUBFLAGZERO:
  581. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  582. R_SUBFLAGSIGN:
  583. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  584. R_SUBFLAGOVERFLOW:
  585. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  586. R_SUBFLAGINTERRUPT:
  587. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  588. R_SUBFLAGDIRECTION:
  589. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  590. else
  591. internalerror(2017042601);
  592. end;
  593. exit;
  594. end;
  595. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  596. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  597. (p.oper[0]^.reg=p.oper[1]^.reg) then
  598. exit;
  599. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  615. begin
  616. RegReadByInstruction := true;
  617. exit
  618. end;
  619. end;
  620. end;
  621. end;
  622. end;
  623. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  624. begin
  625. result:=false;
  626. if p1.typ<>ait_instruction then
  627. exit;
  628. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  629. exit(true);
  630. if (getregtype(reg)=R_INTREGISTER) and
  631. { change information for xmm movsd are not correct }
  632. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  633. begin
  634. case getsupreg(reg) of
  635. { RS_EAX = RS_RAX on x86-64 }
  636. RS_EAX:
  637. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. RS_ECX:
  639. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. RS_EDX:
  641. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. RS_EBX:
  643. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. RS_ESP:
  645. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. RS_EBP:
  647. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. RS_ESI:
  649. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. RS_EDI:
  651. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. else
  653. ;
  654. end;
  655. if result then
  656. exit;
  657. end
  658. else if getregtype(reg)=R_MMREGISTER then
  659. begin
  660. case getsupreg(reg) of
  661. RS_XMM0:
  662. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  663. else
  664. ;
  665. end;
  666. if result then
  667. exit;
  668. end
  669. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  670. begin
  671. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  672. exit(true);
  673. case getsubreg(reg) of
  674. R_SUBFLAGCARRY:
  675. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  676. R_SUBFLAGPARITY:
  677. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  678. R_SUBFLAGAUXILIARY:
  679. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  680. R_SUBFLAGZERO:
  681. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  682. R_SUBFLAGSIGN:
  683. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  684. R_SUBFLAGOVERFLOW:
  685. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  686. R_SUBFLAGINTERRUPT:
  687. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  688. R_SUBFLAGDIRECTION:
  689. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  690. R_SUBW,R_SUBD,R_SUBQ:
  691. { Everything except the direction bits }
  692. Result:=
  693. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  694. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  695. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  696. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  697. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  698. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  699. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. else
  701. ;
  702. end;
  703. if result then
  704. exit;
  705. end
  706. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  707. exit(true);
  708. Result:=inherited RegInInstruction(Reg, p1);
  709. end;
  710. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  711. const
  712. WriteOps: array[0..3] of set of TInsChange =
  713. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  714. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  715. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  716. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  717. var
  718. OperIdx: Integer;
  719. begin
  720. Result := False;
  721. if p1.typ <> ait_instruction then
  722. exit;
  723. with insprop[taicpu(p1).opcode] do
  724. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  725. begin
  726. case getsubreg(reg) of
  727. R_SUBW,R_SUBD,R_SUBQ:
  728. Result :=
  729. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  730. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  731. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  732. R_SUBFLAGCARRY:
  733. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  734. R_SUBFLAGPARITY:
  735. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  736. R_SUBFLAGAUXILIARY:
  737. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  738. R_SUBFLAGZERO:
  739. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  740. R_SUBFLAGSIGN:
  741. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  742. R_SUBFLAGOVERFLOW:
  743. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  744. R_SUBFLAGINTERRUPT:
  745. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  746. R_SUBFLAGDIRECTION:
  747. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  748. else
  749. internalerror(2017042602);
  750. end;
  751. exit;
  752. end;
  753. case taicpu(p1).opcode of
  754. A_CALL:
  755. { We could potentially set Result to False if the register in
  756. question is non-volatile for the subroutine's calling convention,
  757. but this would require detecting the calling convention in use and
  758. also assuming that the routine doesn't contain malformed assembly
  759. language, for example... so it could only be done under -O4 as it
  760. would be considered a side-effect. [Kit] }
  761. Result := True;
  762. A_MOVSD:
  763. { special handling for SSE MOVSD }
  764. if (taicpu(p1).ops>0) then
  765. begin
  766. if taicpu(p1).ops<>2 then
  767. internalerror(2017042703);
  768. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  769. end;
  770. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  771. so fix it here (FK)
  772. }
  773. A_VMOVSS,
  774. A_VMOVSD:
  775. begin
  776. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  777. exit;
  778. end;
  779. A_IMUL:
  780. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  781. else
  782. ;
  783. end;
  784. if Result then
  785. exit;
  786. with insprop[taicpu(p1).opcode] do
  787. begin
  788. if getregtype(reg)=R_INTREGISTER then
  789. begin
  790. case getsupreg(reg) of
  791. RS_EAX:
  792. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  793. begin
  794. Result := True;
  795. exit
  796. end;
  797. RS_ECX:
  798. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  799. begin
  800. Result := True;
  801. exit
  802. end;
  803. RS_EDX:
  804. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  805. begin
  806. Result := True;
  807. exit
  808. end;
  809. RS_EBX:
  810. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  811. begin
  812. Result := True;
  813. exit
  814. end;
  815. RS_ESP:
  816. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  817. begin
  818. Result := True;
  819. exit
  820. end;
  821. RS_EBP:
  822. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  823. begin
  824. Result := True;
  825. exit
  826. end;
  827. RS_ESI:
  828. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  829. begin
  830. Result := True;
  831. exit
  832. end;
  833. RS_EDI:
  834. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  835. begin
  836. Result := True;
  837. exit
  838. end;
  839. end;
  840. end;
  841. for OperIdx := 0 to taicpu(p1).ops - 1 do
  842. if (WriteOps[OperIdx]*Ch<>[]) and
  843. { The register doesn't get modified inside a reference }
  844. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  845. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  846. begin
  847. Result := true;
  848. exit
  849. end;
  850. end;
  851. end;
  852. {$ifdef DEBUG_AOPTCPU}
  853. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  854. begin
  855. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  856. end;
  857. function debug_tostr(i: tcgint): string; inline;
  858. begin
  859. Result := tostr(i);
  860. end;
  861. function debug_regname(r: TRegister): string; inline;
  862. begin
  863. Result := '%' + std_regname(r);
  864. end;
  865. { Debug output function - creates a string representation of an operator }
  866. function debug_operstr(oper: TOper): string;
  867. begin
  868. case oper.typ of
  869. top_const:
  870. Result := '$' + debug_tostr(oper.val);
  871. top_reg:
  872. Result := debug_regname(oper.reg);
  873. top_ref:
  874. begin
  875. if oper.ref^.offset <> 0 then
  876. Result := debug_tostr(oper.ref^.offset) + '('
  877. else
  878. Result := '(';
  879. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  880. begin
  881. Result := Result + debug_regname(oper.ref^.base);
  882. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  883. Result := Result + ',' + debug_regname(oper.ref^.index);
  884. end
  885. else
  886. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  887. Result := Result + debug_regname(oper.ref^.index);
  888. if (oper.ref^.scalefactor > 1) then
  889. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  890. else
  891. Result := Result + ')';
  892. end;
  893. else
  894. Result := '[UNKNOWN]';
  895. end;
  896. end;
  897. function debug_op2str(opcode: tasmop): string; inline;
  898. begin
  899. Result := std_op2str[opcode];
  900. end;
  901. function debug_opsize2str(opsize: topsize): string; inline;
  902. begin
  903. Result := gas_opsize2str[opsize];
  904. end;
  905. {$else DEBUG_AOPTCPU}
  906. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  907. begin
  908. end;
  909. function debug_tostr(i: tcgint): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_regname(r: TRegister): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. function debug_operstr(oper: TOper): string; inline;
  918. begin
  919. Result := '';
  920. end;
  921. function debug_op2str(opcode: tasmop): string; inline;
  922. begin
  923. Result := '';
  924. end;
  925. function debug_opsize2str(opsize: topsize): string; inline;
  926. begin
  927. Result := '';
  928. end;
  929. {$endif DEBUG_AOPTCPU}
  930. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  931. begin
  932. {$ifdef x86_64}
  933. { Always fine on x86-64 }
  934. Result := True;
  935. {$else x86_64}
  936. Result :=
  937. {$ifdef i8086}
  938. (current_settings.cputype >= cpu_386) and
  939. {$endif i8086}
  940. (
  941. { Always accept if optimising for size }
  942. (cs_opt_size in current_settings.optimizerswitches) or
  943. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  944. (current_settings.optimizecputype >= cpu_Pentium2)
  945. );
  946. {$endif x86_64}
  947. end;
  948. { Attempts to allocate a volatile integer register for use between p and hp,
  949. using AUsedRegs for the current register usage information. Returns NR_NO
  950. if no free register could be found }
  951. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  952. var
  953. RegSet: TCPURegisterSet;
  954. CurrentSuperReg: Integer;
  955. CurrentReg: TRegister;
  956. Currentp: tai;
  957. Breakout: Boolean;
  958. begin
  959. Result := NR_NO;
  960. RegSet :=
  961. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  962. current_procinfo.saved_regs_int;
  963. for CurrentSuperReg in RegSet do
  964. begin
  965. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  966. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  967. {$if defined(i386) or defined(i8086)}
  968. { If the target size is 8-bit, make sure we can actually encode it }
  969. and (
  970. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  971. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  972. )
  973. {$endif i386 or i8086}
  974. then
  975. begin
  976. Currentp := p;
  977. Breakout := False;
  978. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  979. begin
  980. case Currentp.typ of
  981. ait_instruction:
  982. begin
  983. if RegInInstruction(CurrentReg, Currentp) then
  984. begin
  985. Breakout := True;
  986. Break;
  987. end;
  988. { Cannot allocate across an unconditional jump }
  989. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  990. Exit;
  991. end;
  992. ait_marker:
  993. { Don't try anything more if a marker is hit }
  994. Exit;
  995. ait_regalloc:
  996. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  997. begin
  998. Breakout := True;
  999. Break;
  1000. end;
  1001. else
  1002. ;
  1003. end;
  1004. end;
  1005. if Breakout then
  1006. { Try the next register }
  1007. Continue;
  1008. { We have a free register available }
  1009. Result := CurrentReg;
  1010. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1011. Exit;
  1012. end;
  1013. end;
  1014. end;
  1015. { Attempts to allocate a volatile MM register for use between p and hp,
  1016. using AUsedRegs for the current register usage information. Returns NR_NO
  1017. if no free register could be found }
  1018. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1019. var
  1020. RegSet: TCPURegisterSet;
  1021. CurrentSuperReg: Integer;
  1022. CurrentReg: TRegister;
  1023. Currentp: tai;
  1024. Breakout: Boolean;
  1025. begin
  1026. Result := NR_NO;
  1027. RegSet :=
  1028. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1029. current_procinfo.saved_regs_mm;
  1030. for CurrentSuperReg in RegSet do
  1031. begin
  1032. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1033. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1034. begin
  1035. Currentp := p;
  1036. Breakout := False;
  1037. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1038. begin
  1039. case Currentp.typ of
  1040. ait_instruction:
  1041. begin
  1042. if RegInInstruction(CurrentReg, Currentp) then
  1043. begin
  1044. Breakout := True;
  1045. Break;
  1046. end;
  1047. { Cannot allocate across an unconditional jump }
  1048. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1049. Exit;
  1050. end;
  1051. ait_marker:
  1052. { Don't try anything more if a marker is hit }
  1053. Exit;
  1054. ait_regalloc:
  1055. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1056. begin
  1057. Breakout := True;
  1058. Break;
  1059. end;
  1060. else
  1061. ;
  1062. end;
  1063. end;
  1064. if Breakout then
  1065. { Try the next register }
  1066. Continue;
  1067. { We have a free register available }
  1068. Result := CurrentReg;
  1069. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1070. Exit;
  1071. end;
  1072. end;
  1073. end;
  1074. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1075. begin
  1076. if not SuperRegistersEqual(reg1,reg2) then
  1077. exit(false);
  1078. if getregtype(reg1)<>R_INTREGISTER then
  1079. exit(true); {because SuperRegisterEqual is true}
  1080. case getsubreg(reg1) of
  1081. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1082. higher, it preserves the high bits, so the new value depends on
  1083. reg2's previous value. In other words, it is equivalent to doing:
  1084. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1085. R_SUBL:
  1086. exit(getsubreg(reg2)=R_SUBL);
  1087. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1088. higher, it actually does a:
  1089. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1090. R_SUBH:
  1091. exit(getsubreg(reg2)=R_SUBH);
  1092. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1093. bits of reg2:
  1094. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1095. R_SUBW:
  1096. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1097. { a write to R_SUBD always overwrites every other subregister,
  1098. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1099. R_SUBD,
  1100. R_SUBQ:
  1101. exit(true);
  1102. else
  1103. internalerror(2017042801);
  1104. end;
  1105. end;
  1106. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1107. begin
  1108. if not SuperRegistersEqual(reg1,reg2) then
  1109. exit(false);
  1110. if getregtype(reg1)<>R_INTREGISTER then
  1111. exit(true); {because SuperRegisterEqual is true}
  1112. case getsubreg(reg1) of
  1113. R_SUBL:
  1114. exit(getsubreg(reg2)<>R_SUBH);
  1115. R_SUBH:
  1116. exit(getsubreg(reg2)<>R_SUBL);
  1117. R_SUBW,
  1118. R_SUBD,
  1119. R_SUBQ:
  1120. exit(true);
  1121. else
  1122. internalerror(2017042802);
  1123. end;
  1124. end;
  1125. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1126. var
  1127. hp1 : tai;
  1128. l : TCGInt;
  1129. begin
  1130. result:=false;
  1131. { changes the code sequence
  1132. shr/sar const1, x
  1133. shl const2, x
  1134. to
  1135. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1136. if GetNextInstruction(p, hp1) and
  1137. MatchInstruction(hp1,A_SHL,[]) and
  1138. (taicpu(p).oper[0]^.typ = top_const) and
  1139. (taicpu(hp1).oper[0]^.typ = top_const) and
  1140. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1141. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1142. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1143. begin
  1144. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1145. not(cs_opt_size in current_settings.optimizerswitches) then
  1146. begin
  1147. { shr/sar const1, %reg
  1148. shl const2, %reg
  1149. with const1 > const2 }
  1150. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1151. taicpu(hp1).opcode := A_AND;
  1152. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1153. case taicpu(p).opsize Of
  1154. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1155. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1156. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1157. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1158. else
  1159. Internalerror(2017050703)
  1160. end;
  1161. end
  1162. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1163. not(cs_opt_size in current_settings.optimizerswitches) then
  1164. begin
  1165. { shr/sar const1, %reg
  1166. shl const2, %reg
  1167. with const1 < const2 }
  1168. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1169. taicpu(p).opcode := A_AND;
  1170. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1171. case taicpu(p).opsize Of
  1172. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1173. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1174. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1175. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1176. else
  1177. Internalerror(2017050702)
  1178. end;
  1179. end
  1180. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1181. begin
  1182. { shr/sar const1, %reg
  1183. shl const2, %reg
  1184. with const1 = const2 }
  1185. taicpu(p).opcode := A_AND;
  1186. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1187. case taicpu(p).opsize Of
  1188. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1189. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1190. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1191. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1192. else
  1193. Internalerror(2017050701)
  1194. end;
  1195. RemoveInstruction(hp1);
  1196. end;
  1197. end;
  1198. end;
  1199. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1200. var
  1201. opsize : topsize;
  1202. hp1 : tai;
  1203. tmpref : treference;
  1204. ShiftValue : Cardinal;
  1205. BaseValue : TCGInt;
  1206. begin
  1207. result:=false;
  1208. opsize:=taicpu(p).opsize;
  1209. { changes certain "imul const, %reg"'s to lea sequences }
  1210. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1211. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1212. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1213. if (taicpu(p).oper[0]^.val = 1) then
  1214. if (taicpu(p).ops = 2) then
  1215. { remove "imul $1, reg" }
  1216. begin
  1217. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1218. Result := RemoveCurrentP(p);
  1219. end
  1220. else
  1221. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1222. begin
  1223. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1224. InsertLLItem(p.previous, p.next, hp1);
  1225. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1226. p.free;
  1227. p := hp1;
  1228. end
  1229. else if ((taicpu(p).ops <= 2) or
  1230. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1231. not(cs_opt_size in current_settings.optimizerswitches) and
  1232. (not(GetNextInstruction(p, hp1)) or
  1233. not((tai(hp1).typ = ait_instruction) and
  1234. ((taicpu(hp1).opcode=A_Jcc) and
  1235. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1236. begin
  1237. {
  1238. imul X, reg1, reg2 to
  1239. lea (reg1,reg1,Y), reg2
  1240. shl ZZ,reg2
  1241. imul XX, reg1 to
  1242. lea (reg1,reg1,YY), reg1
  1243. shl ZZ,reg2
  1244. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1245. it does not exist as a separate optimization target in FPC though.
  1246. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1247. at most two zeros
  1248. }
  1249. reference_reset(tmpref,1,[]);
  1250. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1251. begin
  1252. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1253. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1254. TmpRef.base := taicpu(p).oper[1]^.reg;
  1255. TmpRef.index := taicpu(p).oper[1]^.reg;
  1256. if not(BaseValue in [3,5,9]) then
  1257. Internalerror(2018110101);
  1258. TmpRef.ScaleFactor := BaseValue-1;
  1259. if (taicpu(p).ops = 2) then
  1260. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1261. else
  1262. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1263. AsmL.InsertAfter(hp1,p);
  1264. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1265. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1266. RemoveCurrentP(p, hp1);
  1267. if ShiftValue>0 then
  1268. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1269. end;
  1270. end;
  1271. end;
  1272. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1273. begin
  1274. Result := False;
  1275. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1276. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1277. begin
  1278. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1279. taicpu(p).opcode := A_MOV;
  1280. Result := True;
  1281. end;
  1282. end;
  1283. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1284. var
  1285. p: taicpu absolute hp; { Implicit typecast }
  1286. i: Integer;
  1287. begin
  1288. Result := False;
  1289. if not assigned(hp) or
  1290. (hp.typ <> ait_instruction) then
  1291. Exit;
  1292. Prefetch(insprop[p.opcode]);
  1293. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1294. with insprop[p.opcode] do
  1295. begin
  1296. case getsubreg(reg) of
  1297. R_SUBW,R_SUBD,R_SUBQ:
  1298. Result:=
  1299. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1300. uncommon flags are checked first }
  1301. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1302. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1303. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1304. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1305. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1306. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1307. R_SUBFLAGCARRY:
  1308. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1309. R_SUBFLAGPARITY:
  1310. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1311. R_SUBFLAGAUXILIARY:
  1312. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1313. R_SUBFLAGZERO:
  1314. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1315. R_SUBFLAGSIGN:
  1316. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1317. R_SUBFLAGOVERFLOW:
  1318. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1319. R_SUBFLAGINTERRUPT:
  1320. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1321. R_SUBFLAGDIRECTION:
  1322. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1323. else
  1324. internalerror(2017050501);
  1325. end;
  1326. exit;
  1327. end;
  1328. { Handle special cases first }
  1329. case p.opcode of
  1330. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1331. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1332. begin
  1333. Result :=
  1334. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1335. (p.oper[1]^.typ = top_reg) and
  1336. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1337. (
  1338. (p.oper[0]^.typ = top_const) or
  1339. (
  1340. (p.oper[0]^.typ = top_reg) and
  1341. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1342. ) or (
  1343. (p.oper[0]^.typ = top_ref) and
  1344. not RegInRef(reg,p.oper[0]^.ref^)
  1345. )
  1346. );
  1347. end;
  1348. A_MUL, A_IMUL:
  1349. Result :=
  1350. (
  1351. (p.ops=3) and { IMUL only }
  1352. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1353. (
  1354. (
  1355. (p.oper[1]^.typ=top_reg) and
  1356. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1357. ) or (
  1358. (p.oper[1]^.typ=top_ref) and
  1359. not RegInRef(reg,p.oper[1]^.ref^)
  1360. )
  1361. )
  1362. ) or (
  1363. (
  1364. (p.ops=1) and
  1365. (
  1366. (
  1367. (
  1368. (p.oper[0]^.typ=top_reg) and
  1369. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1370. )
  1371. ) or (
  1372. (p.oper[0]^.typ=top_ref) and
  1373. not RegInRef(reg,p.oper[0]^.ref^)
  1374. )
  1375. ) and (
  1376. (
  1377. (p.opsize=S_B) and
  1378. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1379. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1380. ) or (
  1381. (p.opsize=S_W) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1383. ) or (
  1384. (p.opsize=S_L) and
  1385. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1386. {$ifdef x86_64}
  1387. ) or (
  1388. (p.opsize=S_Q) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1390. {$endif x86_64}
  1391. )
  1392. )
  1393. )
  1394. );
  1395. A_CBW:
  1396. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1397. {$ifndef x86_64}
  1398. A_LDS:
  1399. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LES:
  1401. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1402. {$endif not x86_64}
  1403. A_LFS:
  1404. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1405. A_LGS:
  1406. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1407. A_LSS:
  1408. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1410. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1411. A_LODSB:
  1412. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1413. A_LODSW:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1415. {$ifdef x86_64}
  1416. A_LODSQ:
  1417. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1418. {$endif x86_64}
  1419. A_LODSD:
  1420. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1421. A_FSTSW, A_FNSTSW:
  1422. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1423. else
  1424. begin
  1425. with insprop[p.opcode] do
  1426. begin
  1427. if (
  1428. { xor %reg,%reg etc. is classed as a new value }
  1429. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1430. MatchOpType(p, top_reg, top_reg) and
  1431. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1432. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1433. ) then
  1434. begin
  1435. Result := True;
  1436. Exit;
  1437. end;
  1438. { Make sure the entire register is overwritten }
  1439. if (getregtype(reg) = R_INTREGISTER) then
  1440. begin
  1441. if (p.ops > 0) then
  1442. begin
  1443. if RegInOp(reg, p.oper[0]^) then
  1444. begin
  1445. if (p.oper[0]^.typ = top_ref) then
  1446. begin
  1447. if RegInRef(reg, p.oper[0]^.ref^) then
  1448. begin
  1449. Result := False;
  1450. Exit;
  1451. end;
  1452. end
  1453. else if (p.oper[0]^.typ = top_reg) then
  1454. begin
  1455. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end
  1460. else if ([Ch_WOp1]*Ch<>[]) then
  1461. begin
  1462. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1463. Result := True
  1464. else
  1465. begin
  1466. Result := False;
  1467. Exit;
  1468. end;
  1469. end;
  1470. end;
  1471. end;
  1472. if (p.ops > 1) then
  1473. begin
  1474. if RegInOp(reg, p.oper[1]^) then
  1475. begin
  1476. if (p.oper[1]^.typ = top_ref) then
  1477. begin
  1478. if RegInRef(reg, p.oper[1]^.ref^) then
  1479. begin
  1480. Result := False;
  1481. Exit;
  1482. end;
  1483. end
  1484. else if (p.oper[1]^.typ = top_reg) then
  1485. begin
  1486. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end
  1491. else if ([Ch_WOp2]*Ch<>[]) then
  1492. begin
  1493. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1494. Result := True
  1495. else
  1496. begin
  1497. Result := False;
  1498. Exit;
  1499. end;
  1500. end;
  1501. end;
  1502. end;
  1503. if (p.ops > 2) then
  1504. begin
  1505. if RegInOp(reg, p.oper[2]^) then
  1506. begin
  1507. if (p.oper[2]^.typ = top_ref) then
  1508. begin
  1509. if RegInRef(reg, p.oper[2]^.ref^) then
  1510. begin
  1511. Result := False;
  1512. Exit;
  1513. end;
  1514. end
  1515. else if (p.oper[2]^.typ = top_reg) then
  1516. begin
  1517. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end
  1522. else if ([Ch_WOp3]*Ch<>[]) then
  1523. begin
  1524. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1525. Result := True
  1526. else
  1527. begin
  1528. Result := False;
  1529. Exit;
  1530. end;
  1531. end;
  1532. end;
  1533. end;
  1534. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1535. begin
  1536. if (p.oper[3]^.typ = top_ref) then
  1537. begin
  1538. if RegInRef(reg, p.oper[3]^.ref^) then
  1539. begin
  1540. Result := False;
  1541. Exit;
  1542. end;
  1543. end
  1544. else if (p.oper[3]^.typ = top_reg) then
  1545. begin
  1546. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end
  1551. else if ([Ch_WOp4]*Ch<>[]) then
  1552. begin
  1553. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1554. Result := True
  1555. else
  1556. begin
  1557. Result := False;
  1558. Exit;
  1559. end;
  1560. end;
  1561. end;
  1562. end;
  1563. end;
  1564. end;
  1565. end;
  1566. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1567. case getsupreg(reg) of
  1568. RS_EAX:
  1569. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1570. begin
  1571. Result := True;
  1572. Exit;
  1573. end;
  1574. RS_ECX:
  1575. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1576. begin
  1577. Result := True;
  1578. Exit;
  1579. end;
  1580. RS_EDX:
  1581. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1582. begin
  1583. Result := True;
  1584. Exit;
  1585. end;
  1586. RS_EBX:
  1587. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1588. begin
  1589. Result := True;
  1590. Exit;
  1591. end;
  1592. RS_ESP:
  1593. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1594. begin
  1595. Result := True;
  1596. Exit;
  1597. end;
  1598. RS_EBP:
  1599. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1600. begin
  1601. Result := True;
  1602. Exit;
  1603. end;
  1604. RS_ESI:
  1605. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1606. begin
  1607. Result := True;
  1608. Exit;
  1609. end;
  1610. RS_EDI:
  1611. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1612. begin
  1613. Result := True;
  1614. Exit;
  1615. end;
  1616. else
  1617. ;
  1618. end;
  1619. end;
  1620. end;
  1621. end;
  1622. end;
  1623. end;
  1624. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1625. var
  1626. hp2,hp3 : tai;
  1627. begin
  1628. { some x86-64 issue a NOP before the real exit code }
  1629. if MatchInstruction(p,A_NOP,[]) then
  1630. GetNextInstruction(p,p);
  1631. result:=assigned(p) and (p.typ=ait_instruction) and
  1632. ((taicpu(p).opcode = A_RET) or
  1633. ((taicpu(p).opcode=A_LEAVE) and
  1634. GetNextInstruction(p,hp2) and
  1635. MatchInstruction(hp2,A_RET,[S_NO])
  1636. ) or
  1637. (((taicpu(p).opcode=A_LEA) and
  1638. MatchOpType(taicpu(p),top_ref,top_reg) and
  1639. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1640. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1641. ) and
  1642. GetNextInstruction(p,hp2) and
  1643. MatchInstruction(hp2,A_RET,[S_NO])
  1644. ) or
  1645. ((((taicpu(p).opcode=A_MOV) and
  1646. MatchOpType(taicpu(p),top_reg,top_reg) and
  1647. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1648. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1649. ((taicpu(p).opcode=A_LEA) and
  1650. MatchOpType(taicpu(p),top_ref,top_reg) and
  1651. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1653. )
  1654. ) and
  1655. GetNextInstruction(p,hp2) and
  1656. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1657. MatchOpType(taicpu(hp2),top_reg) and
  1658. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1659. GetNextInstruction(hp2,hp3) and
  1660. MatchInstruction(hp3,A_RET,[S_NO])
  1661. )
  1662. );
  1663. end;
  1664. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1665. begin
  1666. isFoldableArithOp := False;
  1667. case hp1.opcode of
  1668. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1669. isFoldableArithOp :=
  1670. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1671. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1672. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1673. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1674. (taicpu(hp1).oper[1]^.reg = reg);
  1675. A_INC,A_DEC,A_NEG,A_NOT:
  1676. isFoldableArithOp :=
  1677. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[0]^.reg = reg);
  1679. else
  1680. ;
  1681. end;
  1682. end;
  1683. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1684. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1685. var
  1686. hp2: tai;
  1687. begin
  1688. hp2 := p;
  1689. repeat
  1690. hp2 := tai(hp2.previous);
  1691. if assigned(hp2) and
  1692. (hp2.typ = ait_regalloc) and
  1693. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1694. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1695. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1696. begin
  1697. RemoveInstruction(hp2);
  1698. break;
  1699. end;
  1700. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1701. end;
  1702. begin
  1703. case current_procinfo.procdef.returndef.typ of
  1704. arraydef,recorddef,pointerdef,
  1705. stringdef,enumdef,procdef,objectdef,errordef,
  1706. filedef,setdef,procvardef,
  1707. classrefdef,forwarddef:
  1708. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1709. orddef:
  1710. if current_procinfo.procdef.returndef.size <> 0 then
  1711. begin
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. { for int64/qword }
  1714. if current_procinfo.procdef.returndef.size = 8 then
  1715. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1716. end;
  1717. else
  1718. ;
  1719. end;
  1720. end;
  1721. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1722. var
  1723. hp1,hp2 : tai;
  1724. begin
  1725. result:=false;
  1726. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1727. begin
  1728. { vmova* reg1,reg1
  1729. =>
  1730. <nop> }
  1731. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1732. begin
  1733. RemoveCurrentP(p);
  1734. result:=true;
  1735. exit;
  1736. end
  1737. else if GetNextInstruction(p,hp1) then
  1738. begin
  1739. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1740. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1741. begin
  1742. { vmova* reg1,reg2
  1743. vmova* reg2,reg3
  1744. dealloc reg2
  1745. =>
  1746. vmova* reg1,reg3 }
  1747. TransferUsedRegs(TmpUsedRegs);
  1748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1749. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1750. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1751. begin
  1752. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1753. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1754. RemoveInstruction(hp1);
  1755. result:=true;
  1756. exit;
  1757. end
  1758. { special case:
  1759. vmova* reg1,<op>
  1760. vmova* <op>,reg1
  1761. =>
  1762. vmova* reg1,<op> }
  1763. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1764. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1765. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1766. ) then
  1767. begin
  1768. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1769. RemoveInstruction(hp1);
  1770. result:=true;
  1771. exit;
  1772. end
  1773. end
  1774. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1775. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1776. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1777. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1778. ) and
  1779. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1780. begin
  1781. { vmova* reg1,reg2
  1782. vmovs* reg2,<op>
  1783. dealloc reg2
  1784. =>
  1785. vmovs* reg1,reg3 }
  1786. TransferUsedRegs(TmpUsedRegs);
  1787. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1788. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1789. begin
  1790. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1791. taicpu(p).opcode:=taicpu(hp1).opcode;
  1792. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1793. RemoveInstruction(hp1);
  1794. result:=true;
  1795. exit;
  1796. end
  1797. end;
  1798. end;
  1799. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1800. begin
  1801. if MatchInstruction(hp1,[A_VFMADDPD,
  1802. A_VFMADD132PD,
  1803. A_VFMADD132PS,
  1804. A_VFMADD132SD,
  1805. A_VFMADD132SS,
  1806. A_VFMADD213PD,
  1807. A_VFMADD213PS,
  1808. A_VFMADD213SD,
  1809. A_VFMADD213SS,
  1810. A_VFMADD231PD,
  1811. A_VFMADD231PS,
  1812. A_VFMADD231SD,
  1813. A_VFMADD231SS,
  1814. A_VFMADDSUB132PD,
  1815. A_VFMADDSUB132PS,
  1816. A_VFMADDSUB213PD,
  1817. A_VFMADDSUB213PS,
  1818. A_VFMADDSUB231PD,
  1819. A_VFMADDSUB231PS,
  1820. A_VFMSUB132PD,
  1821. A_VFMSUB132PS,
  1822. A_VFMSUB132SD,
  1823. A_VFMSUB132SS,
  1824. A_VFMSUB213PD,
  1825. A_VFMSUB213PS,
  1826. A_VFMSUB213SD,
  1827. A_VFMSUB213SS,
  1828. A_VFMSUB231PD,
  1829. A_VFMSUB231PS,
  1830. A_VFMSUB231SD,
  1831. A_VFMSUB231SS,
  1832. A_VFMSUBADD132PD,
  1833. A_VFMSUBADD132PS,
  1834. A_VFMSUBADD213PD,
  1835. A_VFMSUBADD213PS,
  1836. A_VFMSUBADD231PD,
  1837. A_VFMSUBADD231PS,
  1838. A_VFNMADD132PD,
  1839. A_VFNMADD132PS,
  1840. A_VFNMADD132SD,
  1841. A_VFNMADD132SS,
  1842. A_VFNMADD213PD,
  1843. A_VFNMADD213PS,
  1844. A_VFNMADD213SD,
  1845. A_VFNMADD213SS,
  1846. A_VFNMADD231PD,
  1847. A_VFNMADD231PS,
  1848. A_VFNMADD231SD,
  1849. A_VFNMADD231SS,
  1850. A_VFNMSUB132PD,
  1851. A_VFNMSUB132PS,
  1852. A_VFNMSUB132SD,
  1853. A_VFNMSUB132SS,
  1854. A_VFNMSUB213PD,
  1855. A_VFNMSUB213PS,
  1856. A_VFNMSUB213SD,
  1857. A_VFNMSUB213SS,
  1858. A_VFNMSUB231PD,
  1859. A_VFNMSUB231PS,
  1860. A_VFNMSUB231SD,
  1861. A_VFNMSUB231SS],[S_NO]) and
  1862. { we mix single and double opperations here because we assume that the compiler
  1863. generates vmovapd only after double operations and vmovaps only after single operations }
  1864. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1865. GetNextInstruction(hp1,hp2) and
  1866. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1867. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1868. begin
  1869. TransferUsedRegs(TmpUsedRegs);
  1870. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1871. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1872. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1873. begin
  1874. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1875. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1876. RemoveInstruction(hp2);
  1877. end;
  1878. end
  1879. else if (hp1.typ = ait_instruction) and
  1880. GetNextInstruction(hp1, hp2) and
  1881. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1882. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1883. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1884. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1885. (((taicpu(p).opcode=A_MOVAPS) and
  1886. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1887. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1888. ((taicpu(p).opcode=A_MOVAPD) and
  1889. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1890. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1891. ) then
  1892. { change
  1893. movapX reg,reg2
  1894. addsX/subsX/... reg3, reg2
  1895. movapX reg2,reg
  1896. to
  1897. addsX/subsX/... reg3,reg
  1898. }
  1899. begin
  1900. TransferUsedRegs(TmpUsedRegs);
  1901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1903. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1904. begin
  1905. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1906. debug_op2str(taicpu(p).opcode)+' '+
  1907. debug_op2str(taicpu(hp1).opcode)+' '+
  1908. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1909. { we cannot eliminate the first move if
  1910. the operations uses the same register for source and dest }
  1911. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1912. RemoveCurrentP(p, nil);
  1913. p:=hp1;
  1914. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1915. RemoveInstruction(hp2);
  1916. result:=true;
  1917. end;
  1918. end
  1919. else if (hp1.typ = ait_instruction) and
  1920. (((taicpu(p).opcode=A_VMOVAPD) and
  1921. (taicpu(hp1).opcode=A_VCOMISD)) or
  1922. ((taicpu(p).opcode=A_VMOVAPS) and
  1923. ((taicpu(hp1).opcode=A_VCOMISS))
  1924. )
  1925. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1926. { change
  1927. movapX reg,reg2
  1928. addsX/subsX/... reg3, reg2
  1929. movapX reg2,reg
  1930. to
  1931. addsX/subsX/... reg3,reg
  1932. }
  1933. begin
  1934. TransferUsedRegs(TmpUsedRegs);
  1935. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1936. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1937. begin
  1938. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1939. debug_op2str(taicpu(p).opcode)+' '+
  1940. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1941. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1942. taicpu(hp1).loadoper(0, taicpu(p).oper[1]^);
  1943. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1944. taicpu(hp1).loadoper(1, taicpu(p).oper[1]^);
  1945. RemoveCurrentP(p, nil);
  1946. result:=true;
  1947. exit;
  1948. end;
  1949. end
  1950. end;
  1951. end;
  1952. end;
  1953. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1954. var
  1955. hp1 : tai;
  1956. begin
  1957. result:=false;
  1958. { replace
  1959. V<Op>X %mreg1,%mreg2,%mreg3
  1960. VMovX %mreg3,%mreg4
  1961. dealloc %mreg3
  1962. by
  1963. V<Op>X %mreg1,%mreg2,%mreg4
  1964. ?
  1965. }
  1966. if GetNextInstruction(p,hp1) and
  1967. { we mix single and double operations here because we assume that the compiler
  1968. generates vmovapd only after double operations and vmovaps only after single operations }
  1969. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1970. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1971. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1972. begin
  1973. TransferUsedRegs(TmpUsedRegs);
  1974. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1975. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1976. begin
  1977. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1978. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1979. RemoveInstruction(hp1);
  1980. result:=true;
  1981. end;
  1982. end;
  1983. end;
  1984. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1985. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1986. begin
  1987. Result := False;
  1988. { For safety reasons, only check for exact register matches }
  1989. { Check base register }
  1990. if (ref.base = AOldReg) then
  1991. begin
  1992. ref.base := ANewReg;
  1993. Result := True;
  1994. end;
  1995. { Check index register }
  1996. if (ref.index = AOldReg) then
  1997. begin
  1998. ref.index := ANewReg;
  1999. Result := True;
  2000. end;
  2001. end;
  2002. { Replaces all references to AOldReg in an operand to ANewReg }
  2003. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2004. var
  2005. OldSupReg, NewSupReg: TSuperRegister;
  2006. OldSubReg, NewSubReg: TSubRegister;
  2007. OldRegType: TRegisterType;
  2008. ThisOper: POper;
  2009. begin
  2010. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2011. Result := False;
  2012. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2013. InternalError(2020011801);
  2014. OldSupReg := getsupreg(AOldReg);
  2015. OldSubReg := getsubreg(AOldReg);
  2016. OldRegType := getregtype(AOldReg);
  2017. NewSupReg := getsupreg(ANewReg);
  2018. NewSubReg := getsubreg(ANewReg);
  2019. if OldRegType <> getregtype(ANewReg) then
  2020. InternalError(2020011802);
  2021. if OldSubReg <> NewSubReg then
  2022. InternalError(2020011803);
  2023. case ThisOper^.typ of
  2024. top_reg:
  2025. if (
  2026. (ThisOper^.reg = AOldReg) or
  2027. (
  2028. (OldRegType = R_INTREGISTER) and
  2029. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2030. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2031. (
  2032. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2033. {$ifndef x86_64}
  2034. and (
  2035. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2036. don't have an 8-bit representation }
  2037. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2038. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2039. )
  2040. {$endif x86_64}
  2041. )
  2042. )
  2043. ) then
  2044. begin
  2045. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2046. Result := True;
  2047. end;
  2048. top_ref:
  2049. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2050. Result := True;
  2051. else
  2052. ;
  2053. end;
  2054. end;
  2055. { Replaces all references to AOldReg in an instruction to ANewReg }
  2056. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2057. const
  2058. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2059. var
  2060. OperIdx: Integer;
  2061. begin
  2062. Result := False;
  2063. for OperIdx := 0 to p.ops - 1 do
  2064. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2065. begin
  2066. { The shift and rotate instructions can only use CL }
  2067. if not (
  2068. (OperIdx = 0) and
  2069. { This second condition just helps to avoid unnecessarily
  2070. calling MatchInstruction for 10 different opcodes }
  2071. (p.oper[0]^.reg = NR_CL) and
  2072. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2073. ) then
  2074. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2075. end
  2076. else if p.oper[OperIdx]^.typ = top_ref then
  2077. { It's okay to replace registers in references that get written to }
  2078. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2079. end;
  2080. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2081. begin
  2082. with ref^ do
  2083. Result :=
  2084. (index = NR_NO) and
  2085. (
  2086. {$ifdef x86_64}
  2087. (
  2088. (base = NR_RIP) and
  2089. (refaddr in [addr_pic, addr_pic_no_got])
  2090. ) or
  2091. {$endif x86_64}
  2092. (base = NR_STACK_POINTER_REG) or
  2093. (base = current_procinfo.framepointer)
  2094. );
  2095. end;
  2096. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2097. var
  2098. l: asizeint;
  2099. begin
  2100. Result := False;
  2101. { Should have been checked previously }
  2102. if p.opcode <> A_LEA then
  2103. InternalError(2020072501);
  2104. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2105. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2106. not(cs_opt_size in current_settings.optimizerswitches) then
  2107. exit;
  2108. with p.oper[0]^.ref^ do
  2109. begin
  2110. if (base <> p.oper[1]^.reg) or
  2111. (index <> NR_NO) or
  2112. assigned(symbol) then
  2113. exit;
  2114. l:=offset;
  2115. if (l=1) and UseIncDec then
  2116. begin
  2117. p.opcode:=A_INC;
  2118. p.loadreg(0,p.oper[1]^.reg);
  2119. p.ops:=1;
  2120. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2121. end
  2122. else if (l=-1) and UseIncDec then
  2123. begin
  2124. p.opcode:=A_DEC;
  2125. p.loadreg(0,p.oper[1]^.reg);
  2126. p.ops:=1;
  2127. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2128. end
  2129. else
  2130. begin
  2131. if (l<0) and (l<>-2147483648) then
  2132. begin
  2133. p.opcode:=A_SUB;
  2134. p.loadConst(0,-l);
  2135. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2136. end
  2137. else
  2138. begin
  2139. p.opcode:=A_ADD;
  2140. p.loadConst(0,l);
  2141. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2142. end;
  2143. end;
  2144. end;
  2145. Result := True;
  2146. end;
  2147. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2148. var
  2149. CurrentReg, ReplaceReg: TRegister;
  2150. begin
  2151. Result := False;
  2152. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2153. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2154. case hp.opcode of
  2155. A_FSTSW, A_FNSTSW,
  2156. A_IN, A_INS, A_OUT, A_OUTS,
  2157. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2158. { These routines have explicit operands, but they are restricted in
  2159. what they can be (e.g. IN and OUT can only read from AL, AX or
  2160. EAX. }
  2161. Exit;
  2162. A_IMUL:
  2163. begin
  2164. { The 1-operand version writes to implicit registers
  2165. The 2-operand version reads from the first operator, and reads
  2166. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2167. the 3-operand version reads from a register that it doesn't write to
  2168. }
  2169. case hp.ops of
  2170. 1:
  2171. if (
  2172. (
  2173. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2174. ) or
  2175. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2176. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2177. begin
  2178. Result := True;
  2179. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2180. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2181. end;
  2182. 2:
  2183. { Only modify the first parameter }
  2184. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2185. begin
  2186. Result := True;
  2187. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2188. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2189. end;
  2190. 3:
  2191. { Only modify the second parameter }
  2192. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2193. begin
  2194. Result := True;
  2195. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2196. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2197. end;
  2198. else
  2199. InternalError(2020012901);
  2200. end;
  2201. end;
  2202. else
  2203. if (hp.ops > 0) and
  2204. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2205. begin
  2206. Result := True;
  2207. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2208. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2209. end;
  2210. end;
  2211. end;
  2212. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2213. var
  2214. hp1, hp2, hp3: tai;
  2215. DoOptimisation, TempBool: Boolean;
  2216. {$ifdef x86_64}
  2217. NewConst: TCGInt;
  2218. {$endif x86_64}
  2219. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2220. begin
  2221. if taicpu(hp1).opcode = signed_movop then
  2222. begin
  2223. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2224. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2225. end
  2226. else
  2227. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2228. end;
  2229. function TryConstMerge(var p1, p2: tai): Boolean;
  2230. var
  2231. ThisRef: TReference;
  2232. begin
  2233. Result := False;
  2234. ThisRef := taicpu(p2).oper[1]^.ref^;
  2235. { Only permit writes to the stack, since we can guarantee alignment with that }
  2236. if (ThisRef.index = NR_NO) and
  2237. (
  2238. (ThisRef.base = NR_STACK_POINTER_REG) or
  2239. (ThisRef.base = current_procinfo.framepointer)
  2240. ) then
  2241. begin
  2242. case taicpu(p).opsize of
  2243. S_B:
  2244. begin
  2245. { Word writes must be on a 2-byte boundary }
  2246. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2247. begin
  2248. { Reduce offset of second reference to see if it is sequential with the first }
  2249. Dec(ThisRef.offset, 1);
  2250. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2251. begin
  2252. { Make sure the constants aren't represented as a
  2253. negative number, as these won't merge properly }
  2254. taicpu(p1).opsize := S_W;
  2255. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2256. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2257. RemoveInstruction(p2);
  2258. Result := True;
  2259. end;
  2260. end;
  2261. end;
  2262. S_W:
  2263. begin
  2264. { Longword writes must be on a 4-byte boundary }
  2265. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2266. begin
  2267. { Reduce offset of second reference to see if it is sequential with the first }
  2268. Dec(ThisRef.offset, 2);
  2269. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2270. begin
  2271. { Make sure the constants aren't represented as a
  2272. negative number, as these won't merge properly }
  2273. taicpu(p1).opsize := S_L;
  2274. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2275. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2276. RemoveInstruction(p2);
  2277. Result := True;
  2278. end;
  2279. end;
  2280. end;
  2281. {$ifdef x86_64}
  2282. S_L:
  2283. begin
  2284. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2285. see if the constants can be encoded this way. }
  2286. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2287. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2288. { Quadword writes must be on an 8-byte boundary }
  2289. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2290. begin
  2291. { Reduce offset of second reference to see if it is sequential with the first }
  2292. Dec(ThisRef.offset, 4);
  2293. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2294. begin
  2295. { Make sure the constants aren't represented as a
  2296. negative number, as these won't merge properly }
  2297. taicpu(p1).opsize := S_Q;
  2298. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2299. taicpu(p1).oper[0]^.val := NewConst;
  2300. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2301. RemoveInstruction(p2);
  2302. Result := True;
  2303. end;
  2304. end;
  2305. end;
  2306. {$endif x86_64}
  2307. else
  2308. ;
  2309. end;
  2310. end;
  2311. end;
  2312. var
  2313. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2314. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2315. NewSize: topsize;
  2316. CurrentReg, ActiveReg: TRegister;
  2317. SourceRef, TargetRef: TReference;
  2318. MovAligned, MovUnaligned: TAsmOp;
  2319. ThisRef: TReference;
  2320. begin
  2321. Result:=false;
  2322. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2323. { remove mov reg1,reg1? }
  2324. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2325. then
  2326. begin
  2327. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2328. { take care of the register (de)allocs following p }
  2329. RemoveCurrentP(p, hp1);
  2330. Result:=true;
  2331. exit;
  2332. end;
  2333. { All the next optimisations require a next instruction }
  2334. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2335. Exit;
  2336. { Look for:
  2337. mov %reg1,%reg2
  2338. ??? %reg2,r/m
  2339. Change to:
  2340. mov %reg1,%reg2
  2341. ??? %reg1,r/m
  2342. }
  2343. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2344. begin
  2345. CurrentReg := taicpu(p).oper[1]^.reg;
  2346. if RegReadByInstruction(CurrentReg, hp1) and
  2347. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2348. begin
  2349. { A change has occurred, just not in p }
  2350. Result := True;
  2351. TransferUsedRegs(TmpUsedRegs);
  2352. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2353. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2354. { Just in case something didn't get modified (e.g. an
  2355. implicit register) }
  2356. not RegReadByInstruction(CurrentReg, hp1) then
  2357. begin
  2358. { We can remove the original MOV }
  2359. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2360. RemoveCurrentp(p, hp1);
  2361. { UsedRegs got updated by RemoveCurrentp }
  2362. Result := True;
  2363. Exit;
  2364. end;
  2365. { If we know a MOV instruction has become a null operation, we might as well
  2366. get rid of it now to save time. }
  2367. if (taicpu(hp1).opcode = A_MOV) and
  2368. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2369. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2370. { Just being a register is enough to confirm it's a null operation }
  2371. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2372. begin
  2373. Result := True;
  2374. { Speed-up to reduce a pipeline stall... if we had something like...
  2375. movl %eax,%edx
  2376. movw %dx,%ax
  2377. ... the second instruction would change to movw %ax,%ax, but
  2378. given that it is now %ax that's active rather than %eax,
  2379. penalties might occur due to a partial register write, so instead,
  2380. change it to a MOVZX instruction when optimising for speed.
  2381. }
  2382. if not (cs_opt_size in current_settings.optimizerswitches) and
  2383. IsMOVZXAcceptable and
  2384. (taicpu(hp1).opsize < taicpu(p).opsize)
  2385. {$ifdef x86_64}
  2386. { operations already implicitly set the upper 64 bits to zero }
  2387. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2388. {$endif x86_64}
  2389. then
  2390. begin
  2391. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2392. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2393. case taicpu(p).opsize of
  2394. S_W:
  2395. if taicpu(hp1).opsize = S_B then
  2396. taicpu(hp1).opsize := S_BL
  2397. else
  2398. InternalError(2020012911);
  2399. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2400. case taicpu(hp1).opsize of
  2401. S_B:
  2402. taicpu(hp1).opsize := S_BL;
  2403. S_W:
  2404. taicpu(hp1).opsize := S_WL;
  2405. else
  2406. InternalError(2020012912);
  2407. end;
  2408. else
  2409. InternalError(2020012910);
  2410. end;
  2411. taicpu(hp1).opcode := A_MOVZX;
  2412. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2413. end
  2414. else
  2415. begin
  2416. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2417. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2418. RemoveInstruction(hp1);
  2419. { The instruction after what was hp1 is now the immediate next instruction,
  2420. so we can continue to make optimisations if it's present }
  2421. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2422. Exit;
  2423. hp1 := hp2;
  2424. end;
  2425. end;
  2426. end;
  2427. end;
  2428. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2429. overwrites the original destination register. e.g.
  2430. movl ###,%reg2d
  2431. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2432. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2433. }
  2434. if (taicpu(p).oper[1]^.typ = top_reg) and
  2435. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2436. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2437. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2438. begin
  2439. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2440. begin
  2441. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2442. case taicpu(p).oper[0]^.typ of
  2443. top_const:
  2444. { We have something like:
  2445. movb $x, %regb
  2446. movzbl %regb,%regd
  2447. Change to:
  2448. movl $x, %regd
  2449. }
  2450. begin
  2451. case taicpu(hp1).opsize of
  2452. S_BW:
  2453. begin
  2454. convert_mov_value(A_MOVSX, $FF);
  2455. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2456. taicpu(p).opsize := S_W;
  2457. end;
  2458. S_BL:
  2459. begin
  2460. convert_mov_value(A_MOVSX, $FF);
  2461. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2462. taicpu(p).opsize := S_L;
  2463. end;
  2464. S_WL:
  2465. begin
  2466. convert_mov_value(A_MOVSX, $FFFF);
  2467. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2468. taicpu(p).opsize := S_L;
  2469. end;
  2470. {$ifdef x86_64}
  2471. S_BQ:
  2472. begin
  2473. convert_mov_value(A_MOVSX, $FF);
  2474. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2475. taicpu(p).opsize := S_Q;
  2476. end;
  2477. S_WQ:
  2478. begin
  2479. convert_mov_value(A_MOVSX, $FFFF);
  2480. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2481. taicpu(p).opsize := S_Q;
  2482. end;
  2483. S_LQ:
  2484. begin
  2485. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2486. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2487. taicpu(p).opsize := S_Q;
  2488. end;
  2489. {$endif x86_64}
  2490. else
  2491. { If hp1 was a MOV instruction, it should have been
  2492. optimised already }
  2493. InternalError(2020021001);
  2494. end;
  2495. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2496. RemoveInstruction(hp1);
  2497. Result := True;
  2498. Exit;
  2499. end;
  2500. top_ref:
  2501. begin
  2502. { We have something like:
  2503. movb mem, %regb
  2504. movzbl %regb,%regd
  2505. Change to:
  2506. movzbl mem, %regd
  2507. }
  2508. ThisRef := taicpu(p).oper[0]^.ref^;
  2509. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2510. begin
  2511. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2512. taicpu(hp1).loadref(0, ThisRef);
  2513. { Make sure any registers in the references are properly tracked }
  2514. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2515. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2516. if (ThisRef.index <> NR_NO) then
  2517. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2518. RemoveCurrentP(p, hp1);
  2519. Result := True;
  2520. Exit;
  2521. end;
  2522. end;
  2523. else
  2524. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2525. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2526. Exit;
  2527. end;
  2528. end
  2529. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2530. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2531. optimised }
  2532. else
  2533. begin
  2534. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2535. RemoveCurrentP(p, hp1);
  2536. Result := True;
  2537. Exit;
  2538. end;
  2539. end;
  2540. if (taicpu(hp1).opcode = A_AND) and
  2541. (taicpu(p).oper[1]^.typ = top_reg) and
  2542. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2543. begin
  2544. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2545. begin
  2546. case taicpu(p).opsize of
  2547. S_L:
  2548. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2549. begin
  2550. { Optimize out:
  2551. mov x, %reg
  2552. and ffffffffh, %reg
  2553. }
  2554. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2555. RemoveInstruction(hp1);
  2556. Result:=true;
  2557. exit;
  2558. end;
  2559. S_Q: { TODO: Confirm if this is even possible }
  2560. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2561. begin
  2562. { Optimize out:
  2563. mov x, %reg
  2564. and ffffffffffffffffh, %reg
  2565. }
  2566. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2567. RemoveInstruction(hp1);
  2568. Result:=true;
  2569. exit;
  2570. end;
  2571. else
  2572. ;
  2573. end;
  2574. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2575. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2576. GetNextInstruction(hp1,hp2) and
  2577. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2578. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2579. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2580. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2581. GetNextInstruction(hp2,hp3) and
  2582. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2583. (taicpu(hp3).condition in [C_E,C_NE]) then
  2584. begin
  2585. TransferUsedRegs(TmpUsedRegs);
  2586. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2587. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2588. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2589. begin
  2590. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2591. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2592. taicpu(hp1).opcode:=A_TEST;
  2593. RemoveInstruction(hp2);
  2594. RemoveCurrentP(p, hp1);
  2595. Result:=true;
  2596. exit;
  2597. end;
  2598. end;
  2599. end
  2600. else if IsMOVZXAcceptable and
  2601. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2602. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2603. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2604. then
  2605. begin
  2606. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2607. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2608. case taicpu(p).opsize of
  2609. S_B:
  2610. if (taicpu(hp1).oper[0]^.val = $ff) then
  2611. begin
  2612. { Convert:
  2613. movb x, %regl movb x, %regl
  2614. andw ffh, %regw andl ffh, %regd
  2615. To:
  2616. movzbw x, %regd movzbl x, %regd
  2617. (Identical registers, just different sizes)
  2618. }
  2619. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2620. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2621. case taicpu(hp1).opsize of
  2622. S_W: NewSize := S_BW;
  2623. S_L: NewSize := S_BL;
  2624. {$ifdef x86_64}
  2625. S_Q: NewSize := S_BQ;
  2626. {$endif x86_64}
  2627. else
  2628. InternalError(2018011510);
  2629. end;
  2630. end
  2631. else
  2632. NewSize := S_NO;
  2633. S_W:
  2634. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2635. begin
  2636. { Convert:
  2637. movw x, %regw
  2638. andl ffffh, %regd
  2639. To:
  2640. movzwl x, %regd
  2641. (Identical registers, just different sizes)
  2642. }
  2643. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2644. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2645. case taicpu(hp1).opsize of
  2646. S_L: NewSize := S_WL;
  2647. {$ifdef x86_64}
  2648. S_Q: NewSize := S_WQ;
  2649. {$endif x86_64}
  2650. else
  2651. InternalError(2018011511);
  2652. end;
  2653. end
  2654. else
  2655. NewSize := S_NO;
  2656. else
  2657. NewSize := S_NO;
  2658. end;
  2659. if NewSize <> S_NO then
  2660. begin
  2661. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2662. { The actual optimization }
  2663. taicpu(p).opcode := A_MOVZX;
  2664. taicpu(p).changeopsize(NewSize);
  2665. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2666. { Safeguard if "and" is followed by a conditional command }
  2667. TransferUsedRegs(TmpUsedRegs);
  2668. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2669. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2670. begin
  2671. { At this point, the "and" command is effectively equivalent to
  2672. "test %reg,%reg". This will be handled separately by the
  2673. Peephole Optimizer. [Kit] }
  2674. DebugMsg(SPeepholeOptimization + PreMessage +
  2675. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2676. end
  2677. else
  2678. begin
  2679. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2680. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2681. RemoveInstruction(hp1);
  2682. end;
  2683. Result := True;
  2684. Exit;
  2685. end;
  2686. end;
  2687. end;
  2688. if (taicpu(hp1).opcode = A_OR) and
  2689. (taicpu(p).oper[1]^.typ = top_reg) and
  2690. MatchOperand(taicpu(p).oper[0]^, 0) and
  2691. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2692. begin
  2693. { mov 0, %reg
  2694. or ###,%reg
  2695. Change to (only if the flags are not used):
  2696. mov ###,%reg
  2697. }
  2698. TransferUsedRegs(TmpUsedRegs);
  2699. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2700. DoOptimisation := True;
  2701. { Even if the flags are used, we might be able to do the optimisation
  2702. if the conditions are predictable }
  2703. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2704. begin
  2705. { Only perform if ### = %reg (the same register) or equal to 0,
  2706. so %reg is guaranteed to still have a value of zero }
  2707. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2708. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2709. begin
  2710. hp2 := hp1;
  2711. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2712. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2713. GetNextInstruction(hp2, hp3) do
  2714. begin
  2715. { Don't continue modifying if the flags state is getting changed }
  2716. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2717. Break;
  2718. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2719. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2720. begin
  2721. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2722. begin
  2723. { Condition is always true }
  2724. case taicpu(hp3).opcode of
  2725. A_Jcc:
  2726. begin
  2727. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2728. { Check for jump shortcuts before we destroy the condition }
  2729. DoJumpOptimizations(hp3, TempBool);
  2730. MakeUnconditional(taicpu(hp3));
  2731. Result := True;
  2732. end;
  2733. A_CMOVcc:
  2734. begin
  2735. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2736. taicpu(hp3).opcode := A_MOV;
  2737. taicpu(hp3).condition := C_None;
  2738. Result := True;
  2739. end;
  2740. A_SETcc:
  2741. begin
  2742. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2743. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2744. taicpu(hp3).opcode := A_MOV;
  2745. taicpu(hp3).ops := 2;
  2746. taicpu(hp3).condition := C_None;
  2747. taicpu(hp3).opsize := S_B;
  2748. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2749. taicpu(hp3).loadconst(0, 1);
  2750. Result := True;
  2751. end;
  2752. else
  2753. InternalError(2021090701);
  2754. end;
  2755. end
  2756. 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
  2757. begin
  2758. { Condition is always false }
  2759. case taicpu(hp3).opcode of
  2760. A_Jcc:
  2761. begin
  2762. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2763. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2764. RemoveInstruction(hp3);
  2765. Result := True;
  2766. { Since hp3 was deleted, hp2 must not be updated }
  2767. Continue;
  2768. end;
  2769. A_CMOVcc:
  2770. begin
  2771. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2772. RemoveInstruction(hp3);
  2773. Result := True;
  2774. { Since hp3 was deleted, hp2 must not be updated }
  2775. Continue;
  2776. end;
  2777. A_SETcc:
  2778. begin
  2779. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2780. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2781. taicpu(hp3).opcode := A_MOV;
  2782. taicpu(hp3).ops := 2;
  2783. taicpu(hp3).condition := C_None;
  2784. taicpu(hp3).opsize := S_B;
  2785. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2786. taicpu(hp3).loadconst(0, 0);
  2787. Result := True;
  2788. end;
  2789. else
  2790. InternalError(2021090702);
  2791. end;
  2792. end
  2793. else
  2794. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2795. DoOptimisation := False;
  2796. end;
  2797. hp2 := hp3;
  2798. end;
  2799. { Flags are still in use - don't optimise }
  2800. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2801. DoOptimisation := False;
  2802. end
  2803. else
  2804. DoOptimisation := False;
  2805. end;
  2806. if DoOptimisation then
  2807. begin
  2808. {$ifdef x86_64}
  2809. { OR only supports 32-bit sign-extended constants for 64-bit
  2810. instructions, so compensate for this if the constant is
  2811. encoded as a value greater than or equal to 2^31 }
  2812. if (taicpu(hp1).opsize = S_Q) and
  2813. (taicpu(hp1).oper[0]^.typ = top_const) and
  2814. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2815. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2816. {$endif x86_64}
  2817. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2818. taicpu(hp1).opcode := A_MOV;
  2819. RemoveCurrentP(p, hp1);
  2820. Result := True;
  2821. Exit;
  2822. end;
  2823. end;
  2824. { Next instruction is also a MOV ? }
  2825. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2826. begin
  2827. if MatchOpType(taicpu(p), top_const, top_ref) and
  2828. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2829. TryConstMerge(p, hp1) then
  2830. begin
  2831. Result := True;
  2832. { In case we have four byte writes in a row, check for 2 more
  2833. right now so we don't have to wait for another iteration of
  2834. pass 1
  2835. }
  2836. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2837. case taicpu(p).opsize of
  2838. S_W:
  2839. begin
  2840. if GetNextInstruction(p, hp1) and
  2841. MatchInstruction(hp1, A_MOV, [S_B]) and
  2842. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2843. GetNextInstruction(hp1, hp2) and
  2844. MatchInstruction(hp2, A_MOV, [S_B]) and
  2845. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2846. { Try to merge the two bytes }
  2847. TryConstMerge(hp1, hp2) then
  2848. { Now try to merge the two words (hp2 will get deleted) }
  2849. TryConstMerge(p, hp1);
  2850. end;
  2851. S_L:
  2852. begin
  2853. { Though this only really benefits x86_64 and not i386, it
  2854. gets a potential optimisation done faster and hence
  2855. reduces the number of times OptPass1MOV is entered }
  2856. if GetNextInstruction(p, hp1) and
  2857. MatchInstruction(hp1, A_MOV, [S_W]) and
  2858. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2859. GetNextInstruction(hp1, hp2) and
  2860. MatchInstruction(hp2, A_MOV, [S_W]) and
  2861. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2862. { Try to merge the two words }
  2863. TryConstMerge(hp1, hp2) then
  2864. { This will always fail on i386, so don't bother
  2865. calling it unless we're doing x86_64 }
  2866. {$ifdef x86_64}
  2867. { Now try to merge the two longwords (hp2 will get deleted) }
  2868. TryConstMerge(p, hp1)
  2869. {$endif x86_64}
  2870. ;
  2871. end;
  2872. else
  2873. ;
  2874. end;
  2875. Exit;
  2876. end;
  2877. if (taicpu(p).oper[1]^.typ = top_reg) and
  2878. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2879. begin
  2880. CurrentReg := taicpu(p).oper[1]^.reg;
  2881. TransferUsedRegs(TmpUsedRegs);
  2882. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2883. { we have
  2884. mov x, %treg
  2885. mov %treg, y
  2886. }
  2887. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2888. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2889. { we've got
  2890. mov x, %treg
  2891. mov %treg, y
  2892. with %treg is not used after }
  2893. case taicpu(p).oper[0]^.typ Of
  2894. { top_reg is covered by DeepMOVOpt }
  2895. top_const:
  2896. begin
  2897. { change
  2898. mov const, %treg
  2899. mov %treg, y
  2900. to
  2901. mov const, y
  2902. }
  2903. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2904. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2905. begin
  2906. if taicpu(hp1).oper[1]^.typ=top_reg then
  2907. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2908. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2909. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2910. RemoveInstruction(hp1);
  2911. Result:=true;
  2912. Exit;
  2913. end;
  2914. end;
  2915. top_ref:
  2916. case taicpu(hp1).oper[1]^.typ of
  2917. top_reg:
  2918. begin
  2919. { change
  2920. mov mem, %treg
  2921. mov %treg, %reg
  2922. to
  2923. mov mem, %reg"
  2924. }
  2925. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2926. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2927. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2928. RemoveInstruction(hp1);
  2929. Result:=true;
  2930. Exit;
  2931. end;
  2932. top_ref:
  2933. begin
  2934. {$ifdef x86_64}
  2935. { Look for the following to simplify:
  2936. mov x(mem1), %reg
  2937. mov %reg, y(mem2)
  2938. mov x+8(mem1), %reg
  2939. mov %reg, y+8(mem2)
  2940. Change to:
  2941. movdqu x(mem1), %xmmreg
  2942. movdqu %xmmreg, y(mem2)
  2943. }
  2944. SourceRef := taicpu(p).oper[0]^.ref^;
  2945. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2946. if (taicpu(p).opsize = S_Q) and
  2947. GetNextInstruction(hp1, hp2) and
  2948. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2949. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2950. begin
  2951. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2952. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2953. Inc(SourceRef.offset, 8);
  2954. if UseAVX then
  2955. begin
  2956. MovAligned := A_VMOVDQA;
  2957. MovUnaligned := A_VMOVDQU;
  2958. end
  2959. else
  2960. begin
  2961. MovAligned := A_MOVDQA;
  2962. MovUnaligned := A_MOVDQU;
  2963. end;
  2964. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2965. begin
  2966. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2967. Inc(TargetRef.offset, 8);
  2968. if GetNextInstruction(hp2, hp3) and
  2969. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2970. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2971. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2972. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2973. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2974. begin
  2975. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2976. if CurrentReg <> NR_NO then
  2977. begin
  2978. { Remember that the offsets are 8 ahead }
  2979. if ((SourceRef.offset mod 16) = 8) and
  2980. (
  2981. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2982. (SourceRef.base = current_procinfo.framepointer) or
  2983. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2984. ) then
  2985. taicpu(p).opcode := MovAligned
  2986. else
  2987. taicpu(p).opcode := MovUnaligned;
  2988. taicpu(p).opsize := S_XMM;
  2989. taicpu(p).oper[1]^.reg := CurrentReg;
  2990. if ((TargetRef.offset mod 16) = 8) and
  2991. (
  2992. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2993. (TargetRef.base = current_procinfo.framepointer) or
  2994. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2995. ) then
  2996. taicpu(hp1).opcode := MovAligned
  2997. else
  2998. taicpu(hp1).opcode := MovUnaligned;
  2999. taicpu(hp1).opsize := S_XMM;
  3000. taicpu(hp1).oper[0]^.reg := CurrentReg;
  3001. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3002. RemoveInstruction(hp2);
  3003. RemoveInstruction(hp3);
  3004. Result := True;
  3005. Exit;
  3006. end;
  3007. end;
  3008. end
  3009. else
  3010. begin
  3011. { See if the next references are 8 less rather than 8 greater }
  3012. Dec(SourceRef.offset, 16); { -8 the other way }
  3013. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3014. begin
  3015. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3016. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3017. if GetNextInstruction(hp2, hp3) and
  3018. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3019. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3020. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3021. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3022. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3023. begin
  3024. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3025. if CurrentReg <> NR_NO then
  3026. begin
  3027. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3028. if ((SourceRef.offset mod 16) = 0) and
  3029. (
  3030. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3031. (SourceRef.base = current_procinfo.framepointer) or
  3032. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3033. ) then
  3034. taicpu(hp2).opcode := MovAligned
  3035. else
  3036. taicpu(hp2).opcode := MovUnaligned;
  3037. taicpu(hp2).opsize := S_XMM;
  3038. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3039. if ((TargetRef.offset mod 16) = 0) and
  3040. (
  3041. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3042. (TargetRef.base = current_procinfo.framepointer) or
  3043. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3044. ) then
  3045. taicpu(hp3).opcode := MovAligned
  3046. else
  3047. taicpu(hp3).opcode := MovUnaligned;
  3048. taicpu(hp3).opsize := S_XMM;
  3049. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3050. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3051. RemoveInstruction(hp1);
  3052. RemoveCurrentP(p, hp2);
  3053. Result := True;
  3054. Exit;
  3055. end;
  3056. end;
  3057. end;
  3058. end;
  3059. end;
  3060. {$endif x86_64}
  3061. end;
  3062. else
  3063. { The write target should be a reg or a ref }
  3064. InternalError(2021091601);
  3065. end;
  3066. else
  3067. ;
  3068. end
  3069. else
  3070. { %treg is used afterwards, but all eventualities
  3071. other than the first MOV instruction being a constant
  3072. are covered by DeepMOVOpt, so only check for that }
  3073. if (taicpu(p).oper[0]^.typ = top_const) and
  3074. (
  3075. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3076. not (cs_opt_size in current_settings.optimizerswitches) or
  3077. (taicpu(hp1).opsize = S_B)
  3078. ) and
  3079. (
  3080. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3081. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3082. ) then
  3083. begin
  3084. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3085. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3086. end;
  3087. end;
  3088. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3089. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3090. { mov reg1, mem1 or mov mem1, reg1
  3091. mov mem2, reg2 mov reg2, mem2}
  3092. begin
  3093. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3094. { mov reg1, mem1 or mov mem1, reg1
  3095. mov mem2, reg1 mov reg2, mem1}
  3096. begin
  3097. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3098. { Removes the second statement from
  3099. mov reg1, mem1/reg2
  3100. mov mem1/reg2, reg1 }
  3101. begin
  3102. if taicpu(p).oper[0]^.typ=top_reg then
  3103. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3104. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3105. RemoveInstruction(hp1);
  3106. Result:=true;
  3107. exit;
  3108. end
  3109. else
  3110. begin
  3111. TransferUsedRegs(TmpUsedRegs);
  3112. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3113. if (taicpu(p).oper[1]^.typ = top_ref) and
  3114. { mov reg1, mem1
  3115. mov mem2, reg1 }
  3116. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3117. GetNextInstruction(hp1, hp2) and
  3118. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3119. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3120. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3121. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3122. { change to
  3123. mov reg1, mem1 mov reg1, mem1
  3124. mov mem2, reg1 cmp reg1, mem2
  3125. cmp mem1, reg1
  3126. }
  3127. begin
  3128. RemoveInstruction(hp2);
  3129. taicpu(hp1).opcode := A_CMP;
  3130. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3131. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3132. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3133. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3134. end;
  3135. end;
  3136. end
  3137. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3138. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3139. begin
  3140. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3141. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3142. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3143. end
  3144. else
  3145. begin
  3146. TransferUsedRegs(TmpUsedRegs);
  3147. if GetNextInstruction(hp1, hp2) and
  3148. MatchOpType(taicpu(p),top_ref,top_reg) and
  3149. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3150. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3151. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3152. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3153. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3154. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3155. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3156. { mov mem1, %reg1
  3157. mov %reg1, mem2
  3158. mov mem2, reg2
  3159. to:
  3160. mov mem1, reg2
  3161. mov reg2, mem2}
  3162. begin
  3163. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3164. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3165. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3166. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3167. RemoveInstruction(hp2);
  3168. Result := True;
  3169. end
  3170. {$ifdef i386}
  3171. { this is enabled for i386 only, as the rules to create the reg sets below
  3172. are too complicated for x86-64, so this makes this code too error prone
  3173. on x86-64
  3174. }
  3175. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3176. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3177. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3178. { mov mem1, reg1 mov mem1, reg1
  3179. mov reg1, mem2 mov reg1, mem2
  3180. mov mem2, reg2 mov mem2, reg1
  3181. to: to:
  3182. mov mem1, reg1 mov mem1, reg1
  3183. mov mem1, reg2 mov reg1, mem2
  3184. mov reg1, mem2
  3185. or (if mem1 depends on reg1
  3186. and/or if mem2 depends on reg2)
  3187. to:
  3188. mov mem1, reg1
  3189. mov reg1, mem2
  3190. mov reg1, reg2
  3191. }
  3192. begin
  3193. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3194. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3195. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3196. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3197. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3198. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3199. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3200. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3201. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3202. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3203. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3204. end
  3205. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3206. begin
  3207. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3208. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3209. end
  3210. else
  3211. begin
  3212. RemoveInstruction(hp2);
  3213. end
  3214. {$endif i386}
  3215. ;
  3216. end;
  3217. end
  3218. { movl [mem1],reg1
  3219. movl [mem1],reg2
  3220. to
  3221. movl [mem1],reg1
  3222. movl reg1,reg2
  3223. }
  3224. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3225. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3226. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3227. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3228. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3229. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3230. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3231. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3232. begin
  3233. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3234. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3235. end;
  3236. { movl const1,[mem1]
  3237. movl [mem1],reg1
  3238. to
  3239. movl const1,reg1
  3240. movl reg1,[mem1]
  3241. }
  3242. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3243. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3244. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3245. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3246. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3247. begin
  3248. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3249. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3250. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3251. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3252. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3253. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3254. Result:=true;
  3255. exit;
  3256. end;
  3257. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3258. { Change:
  3259. movl %reg1,%reg2
  3260. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3261. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3262. To:
  3263. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3264. movl x(%reg1),%reg1
  3265. movl %reg1,%regX
  3266. }
  3267. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3268. begin
  3269. CurrentReg := taicpu(p).oper[0]^.reg;
  3270. ActiveReg := taicpu(p).oper[1]^.reg;
  3271. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3272. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3273. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3274. GetNextInstruction(hp1, hp2) and
  3275. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3276. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3277. begin
  3278. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3279. if RegInRef(ActiveReg, SourceRef) and
  3280. { If %reg1 also appears in the second reference, then it will
  3281. not refer to the same memory block as the first reference }
  3282. not RegInRef(CurrentReg, SourceRef) then
  3283. begin
  3284. { Check to see if the references match if %reg2 is changed to %reg1 }
  3285. if SourceRef.base = ActiveReg then
  3286. SourceRef.base := CurrentReg;
  3287. if SourceRef.index = ActiveReg then
  3288. SourceRef.index := CurrentReg;
  3289. { RefsEqual also checks to ensure both references are non-volatile }
  3290. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3291. begin
  3292. taicpu(hp2).loadreg(0, CurrentReg);
  3293. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3294. Result := True;
  3295. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3296. begin
  3297. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3298. RemoveCurrentP(p, hp1);
  3299. Exit;
  3300. end
  3301. else
  3302. begin
  3303. { Check to see if %reg2 is no longer in use }
  3304. TransferUsedRegs(TmpUsedRegs);
  3305. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3306. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3307. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3308. begin
  3309. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3310. RemoveCurrentP(p, hp1);
  3311. Exit;
  3312. end;
  3313. end;
  3314. { If we reach this point, p and hp1 weren't actually modified,
  3315. so we can do a bit more work on this pass }
  3316. end;
  3317. end;
  3318. end;
  3319. end;
  3320. end;
  3321. { search further than the next instruction for a mov (as long as it's not a jump) }
  3322. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3323. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3324. (taicpu(p).oper[1]^.typ = top_reg) and
  3325. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3326. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3327. begin
  3328. { we work with hp2 here, so hp1 can be still used later on when
  3329. checking for GetNextInstruction_p }
  3330. hp3 := hp1;
  3331. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3332. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3333. { Saves on a large number of dereferences }
  3334. ActiveReg := taicpu(p).oper[1]^.reg;
  3335. TransferUsedRegs(TmpUsedRegs);
  3336. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3337. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3338. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3339. (hp2.typ=ait_instruction) do
  3340. begin
  3341. case taicpu(hp2).opcode of
  3342. A_POP:
  3343. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3344. begin
  3345. if not CrossJump and
  3346. not RegUsedBetween(ActiveReg, p, hp2) then
  3347. begin
  3348. { We can remove the original MOV since the register
  3349. wasn't used between it and its popping from the stack }
  3350. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3351. RemoveCurrentp(p, hp1);
  3352. Result := True;
  3353. Exit;
  3354. end;
  3355. { Can't go any further }
  3356. Break;
  3357. end;
  3358. A_MOV:
  3359. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3360. ((taicpu(p).oper[0]^.typ=top_const) or
  3361. ((taicpu(p).oper[0]^.typ=top_reg) and
  3362. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3363. )
  3364. ) then
  3365. begin
  3366. { we have
  3367. mov x, %treg
  3368. mov %treg, y
  3369. }
  3370. { We don't need to call UpdateUsedRegs for every instruction between
  3371. p and hp2 because the register we're concerned about will not
  3372. become deallocated (otherwise GetNextInstructionUsingReg would
  3373. have stopped at an earlier instruction). [Kit] }
  3374. TempRegUsed :=
  3375. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3376. RegReadByInstruction(ActiveReg, hp3) or
  3377. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3378. case taicpu(p).oper[0]^.typ Of
  3379. top_reg:
  3380. begin
  3381. { change
  3382. mov %reg, %treg
  3383. mov %treg, y
  3384. to
  3385. mov %reg, y
  3386. }
  3387. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3388. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3389. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3390. begin
  3391. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3392. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3393. if TempRegUsed then
  3394. begin
  3395. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3396. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3397. { Set the start of the next GetNextInstructionUsingRegCond search
  3398. to start at the entry right before hp2 (which is about to be removed) }
  3399. hp3 := tai(hp2.Previous);
  3400. RemoveInstruction(hp2);
  3401. { See if there's more we can optimise }
  3402. Continue;
  3403. end
  3404. else
  3405. begin
  3406. RemoveInstruction(hp2);
  3407. { We can remove the original MOV too }
  3408. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3409. RemoveCurrentP(p, hp1);
  3410. Result:=true;
  3411. Exit;
  3412. end;
  3413. end
  3414. else
  3415. begin
  3416. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3417. taicpu(hp2).loadReg(0, CurrentReg);
  3418. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3419. { Check to see if the register also appears in the reference }
  3420. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3421. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3422. { Don't remove the first instruction if the temporary register is in use }
  3423. if not TempRegUsed and
  3424. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3425. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3426. begin
  3427. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3428. RemoveCurrentP(p, hp1);
  3429. Result:=true;
  3430. Exit;
  3431. end;
  3432. { No need to set Result to True here. If there's another instruction later
  3433. on that can be optimised, it will be detected when the main Pass 1 loop
  3434. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3435. end;
  3436. end;
  3437. top_const:
  3438. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3439. begin
  3440. { change
  3441. mov const, %treg
  3442. mov %treg, y
  3443. to
  3444. mov const, y
  3445. }
  3446. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3447. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3448. begin
  3449. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3450. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3451. if TempRegUsed then
  3452. begin
  3453. { Don't remove the first instruction if the temporary register is in use }
  3454. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3455. { No need to set Result to True. If there's another instruction later on
  3456. that can be optimised, it will be detected when the main Pass 1 loop
  3457. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3458. end
  3459. else
  3460. begin
  3461. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3462. RemoveCurrentP(p, hp1);
  3463. Result:=true;
  3464. Exit;
  3465. end;
  3466. end;
  3467. end;
  3468. else
  3469. Internalerror(2019103001);
  3470. end;
  3471. end
  3472. else
  3473. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3474. begin
  3475. if not CrossJump and
  3476. not RegUsedBetween(ActiveReg, p, hp2) and
  3477. not RegReadByInstruction(ActiveReg, hp2) then
  3478. begin
  3479. { Register is not used before it is overwritten }
  3480. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3481. RemoveCurrentp(p, hp1);
  3482. Result := True;
  3483. Exit;
  3484. end;
  3485. if (taicpu(p).oper[0]^.typ = top_const) and
  3486. (taicpu(hp2).oper[0]^.typ = top_const) then
  3487. begin
  3488. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3489. begin
  3490. { Same value - register hasn't changed }
  3491. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3492. RemoveInstruction(hp2);
  3493. Result := True;
  3494. { See if there's more we can optimise }
  3495. Continue;
  3496. end;
  3497. end;
  3498. end;
  3499. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3500. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3501. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3502. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3503. begin
  3504. {
  3505. Change from:
  3506. mov ###, %reg
  3507. ...
  3508. movs/z %reg,%reg (Same register, just different sizes)
  3509. To:
  3510. movs/z ###, %reg (Longer version)
  3511. ...
  3512. (remove)
  3513. }
  3514. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3515. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3516. { Keep the first instruction as mov if ### is a constant }
  3517. if taicpu(p).oper[0]^.typ = top_const then
  3518. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3519. else
  3520. begin
  3521. taicpu(p).opcode := taicpu(hp2).opcode;
  3522. taicpu(p).opsize := taicpu(hp2).opsize;
  3523. end;
  3524. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3525. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3526. RemoveInstruction(hp2);
  3527. Result := True;
  3528. Exit;
  3529. end;
  3530. else
  3531. { Move down to the MatchOpType if-block below };
  3532. end;
  3533. { Also catches MOV/S/Z instructions that aren't modified }
  3534. if taicpu(p).oper[0]^.typ = top_reg then
  3535. begin
  3536. CurrentReg := taicpu(p).oper[0]^.reg;
  3537. if
  3538. not RegModifiedByInstruction(CurrentReg, hp3) and
  3539. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3540. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3541. begin
  3542. Result := True;
  3543. { Just in case something didn't get modified (e.g. an
  3544. implicit register). Also, if it does read from this
  3545. register, then there's no longer an advantage to
  3546. changing the register on subsequent instructions.}
  3547. if not RegReadByInstruction(ActiveReg, hp2) then
  3548. begin
  3549. { If a conditional jump was crossed, do not delete
  3550. the original MOV no matter what }
  3551. if not CrossJump and
  3552. { RegEndOfLife returns True if the register is
  3553. deallocated before the next instruction or has
  3554. been loaded with a new value }
  3555. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3556. begin
  3557. { We can remove the original MOV }
  3558. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3559. RemoveCurrentp(p, hp1);
  3560. Exit;
  3561. end;
  3562. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3563. begin
  3564. { See if there's more we can optimise }
  3565. hp3 := hp2;
  3566. Continue;
  3567. end;
  3568. end;
  3569. end;
  3570. end;
  3571. { Break out of the while loop under normal circumstances }
  3572. Break;
  3573. end;
  3574. end;
  3575. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3576. (taicpu(p).oper[1]^.typ = top_reg) and
  3577. (taicpu(p).opsize = S_L) and
  3578. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3579. (taicpu(hp2).opcode = A_AND) and
  3580. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3581. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3582. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3583. ) then
  3584. begin
  3585. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3586. begin
  3587. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3588. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3589. begin
  3590. { Optimize out:
  3591. mov x, %reg
  3592. and ffffffffh, %reg
  3593. }
  3594. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3595. RemoveInstruction(hp2);
  3596. Result:=true;
  3597. exit;
  3598. end;
  3599. end;
  3600. end;
  3601. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3602. x >= RetOffset) as it doesn't do anything (it writes either to a
  3603. parameter or to the temporary storage room for the function
  3604. result)
  3605. }
  3606. if IsExitCode(hp1) and
  3607. (taicpu(p).oper[1]^.typ = top_ref) and
  3608. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3609. (
  3610. (
  3611. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3612. not (
  3613. assigned(current_procinfo.procdef.funcretsym) and
  3614. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3615. )
  3616. ) or
  3617. { Also discard writes to the stack that are below the base pointer,
  3618. as this is temporary storage rather than a function result on the
  3619. stack, say. }
  3620. (
  3621. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3622. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3623. )
  3624. ) then
  3625. begin
  3626. RemoveCurrentp(p, hp1);
  3627. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3628. RemoveLastDeallocForFuncRes(p);
  3629. Result:=true;
  3630. exit;
  3631. end;
  3632. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3633. begin
  3634. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3635. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3636. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3637. begin
  3638. { change
  3639. mov reg1, mem1
  3640. test/cmp x, mem1
  3641. to
  3642. mov reg1, mem1
  3643. test/cmp x, reg1
  3644. }
  3645. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3646. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3647. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3648. Result := True;
  3649. Exit;
  3650. end;
  3651. if DoMovCmpMemOpt(p, hp1, True) then
  3652. begin
  3653. Result := True;
  3654. Exit;
  3655. end;
  3656. end;
  3657. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3658. { If the flags register is in use, don't change the instruction to an
  3659. ADD otherwise this will scramble the flags. [Kit] }
  3660. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3661. begin
  3662. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3663. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3664. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3665. ) or
  3666. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3667. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3668. )
  3669. ) then
  3670. { mov reg1,ref
  3671. lea reg2,[reg1,reg2]
  3672. to
  3673. add reg2,ref}
  3674. begin
  3675. TransferUsedRegs(TmpUsedRegs);
  3676. { reg1 may not be used afterwards }
  3677. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3678. begin
  3679. Taicpu(hp1).opcode:=A_ADD;
  3680. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3681. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3682. RemoveCurrentp(p, hp1);
  3683. result:=true;
  3684. exit;
  3685. end;
  3686. end;
  3687. { If the LEA instruction can be converted into an arithmetic instruction,
  3688. it may be possible to then fold it in the next optimisation, otherwise
  3689. there's nothing more that can be optimised here. }
  3690. if not ConvertLEA(taicpu(hp1)) then
  3691. Exit;
  3692. end;
  3693. if (taicpu(p).oper[1]^.typ = top_reg) and
  3694. (hp1.typ = ait_instruction) and
  3695. GetNextInstruction(hp1, hp2) and
  3696. MatchInstruction(hp2,A_MOV,[]) and
  3697. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3698. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3699. (
  3700. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3701. {$ifdef x86_64}
  3702. or
  3703. (
  3704. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3705. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3706. )
  3707. {$endif x86_64}
  3708. ) then
  3709. begin
  3710. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3711. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3712. { change movsX/movzX reg/ref, reg2
  3713. add/sub/or/... reg3/$const, reg2
  3714. mov reg2 reg/ref
  3715. dealloc reg2
  3716. to
  3717. add/sub/or/... reg3/$const, reg/ref }
  3718. begin
  3719. TransferUsedRegs(TmpUsedRegs);
  3720. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3721. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3722. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3723. begin
  3724. { by example:
  3725. movswl %si,%eax movswl %si,%eax p
  3726. decl %eax addl %edx,%eax hp1
  3727. movw %ax,%si movw %ax,%si hp2
  3728. ->
  3729. movswl %si,%eax movswl %si,%eax p
  3730. decw %eax addw %edx,%eax hp1
  3731. movw %ax,%si movw %ax,%si hp2
  3732. }
  3733. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3734. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3735. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3736. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3737. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3738. {
  3739. ->
  3740. movswl %si,%eax movswl %si,%eax p
  3741. decw %si addw %dx,%si hp1
  3742. movw %ax,%si movw %ax,%si hp2
  3743. }
  3744. case taicpu(hp1).ops of
  3745. 1:
  3746. begin
  3747. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3748. if taicpu(hp1).oper[0]^.typ=top_reg then
  3749. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3750. end;
  3751. 2:
  3752. begin
  3753. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3754. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3755. (taicpu(hp1).opcode<>A_SHL) and
  3756. (taicpu(hp1).opcode<>A_SHR) and
  3757. (taicpu(hp1).opcode<>A_SAR) then
  3758. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3759. end;
  3760. else
  3761. internalerror(2008042701);
  3762. end;
  3763. {
  3764. ->
  3765. decw %si addw %dx,%si p
  3766. }
  3767. RemoveInstruction(hp2);
  3768. RemoveCurrentP(p, hp1);
  3769. Result:=True;
  3770. Exit;
  3771. end;
  3772. end;
  3773. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3774. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3775. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3776. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3777. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3778. )
  3779. {$ifdef i386}
  3780. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3781. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3782. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3783. {$endif i386}
  3784. then
  3785. { change movsX/movzX reg/ref, reg2
  3786. add/sub/or/... regX/$const, reg2
  3787. mov reg2, reg3
  3788. dealloc reg2
  3789. to
  3790. movsX/movzX reg/ref, reg3
  3791. add/sub/or/... reg3/$const, reg3
  3792. }
  3793. begin
  3794. TransferUsedRegs(TmpUsedRegs);
  3795. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3796. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3797. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3798. begin
  3799. { by example:
  3800. movswl %si,%eax movswl %si,%eax p
  3801. decl %eax addl %edx,%eax hp1
  3802. movw %ax,%si movw %ax,%si hp2
  3803. ->
  3804. movswl %si,%eax movswl %si,%eax p
  3805. decw %eax addw %edx,%eax hp1
  3806. movw %ax,%si movw %ax,%si hp2
  3807. }
  3808. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3809. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3810. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3811. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3812. { limit size of constants as well to avoid assembler errors, but
  3813. check opsize to avoid overflow when left shifting the 1 }
  3814. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3815. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3816. {$ifdef x86_64}
  3817. { Be careful of, for example:
  3818. movl %reg1,%reg2
  3819. addl %reg3,%reg2
  3820. movq %reg2,%reg4
  3821. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3822. }
  3823. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3824. begin
  3825. taicpu(hp2).changeopsize(S_L);
  3826. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3827. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3828. end;
  3829. {$endif x86_64}
  3830. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3831. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3832. if taicpu(p).oper[0]^.typ=top_reg then
  3833. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3834. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3835. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3836. {
  3837. ->
  3838. movswl %si,%eax movswl %si,%eax p
  3839. decw %si addw %dx,%si hp1
  3840. movw %ax,%si movw %ax,%si hp2
  3841. }
  3842. case taicpu(hp1).ops of
  3843. 1:
  3844. begin
  3845. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3846. if taicpu(hp1).oper[0]^.typ=top_reg then
  3847. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3848. end;
  3849. 2:
  3850. begin
  3851. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3852. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3853. (taicpu(hp1).opcode<>A_SHL) and
  3854. (taicpu(hp1).opcode<>A_SHR) and
  3855. (taicpu(hp1).opcode<>A_SAR) then
  3856. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3857. end;
  3858. else
  3859. internalerror(2018111801);
  3860. end;
  3861. {
  3862. ->
  3863. decw %si addw %dx,%si p
  3864. }
  3865. RemoveInstruction(hp2);
  3866. end;
  3867. end;
  3868. end;
  3869. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3870. GetNextInstruction(hp1, hp2) and
  3871. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3872. MatchOperand(Taicpu(p).oper[0]^,0) and
  3873. (Taicpu(p).oper[1]^.typ = top_reg) and
  3874. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3875. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3876. { mov reg1,0
  3877. bts reg1,operand1 --> mov reg1,operand2
  3878. or reg1,operand2 bts reg1,operand1}
  3879. begin
  3880. Taicpu(hp2).opcode:=A_MOV;
  3881. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3882. asml.remove(hp1);
  3883. insertllitem(hp2,hp2.next,hp1);
  3884. RemoveCurrentp(p, hp1);
  3885. Result:=true;
  3886. exit;
  3887. end;
  3888. {
  3889. mov ref,reg0
  3890. <op> reg0,reg1
  3891. dealloc reg0
  3892. to
  3893. <op> ref,reg1
  3894. }
  3895. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3896. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3897. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3898. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3899. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3900. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3901. begin
  3902. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3903. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3904. RemoveCurrentp(p, hp1);
  3905. Result:=true;
  3906. exit;
  3907. end;
  3908. {$ifdef x86_64}
  3909. { Convert:
  3910. movq x(ref),%reg64
  3911. shrq y,%reg64
  3912. To:
  3913. movl x+4(ref),%reg32
  3914. shrl y-32,%reg32 (Remove if y = 32)
  3915. }
  3916. if (taicpu(p).opsize = S_Q) and
  3917. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3918. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3919. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3920. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3921. (taicpu(hp1).oper[0]^.val >= 32) and
  3922. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3923. begin
  3924. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3925. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3926. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3927. { Convert to 32-bit }
  3928. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3929. taicpu(p).opsize := S_L;
  3930. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3931. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3932. if (taicpu(hp1).oper[0]^.val = 32) then
  3933. begin
  3934. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3935. RemoveInstruction(hp1);
  3936. end
  3937. else
  3938. begin
  3939. { This will potentially open up more arithmetic operations since
  3940. the peephole optimizer now has a big hint that only the lower
  3941. 32 bits are currently in use (and opcodes are smaller in size) }
  3942. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3943. taicpu(hp1).opsize := S_L;
  3944. Dec(taicpu(hp1).oper[0]^.val, 32);
  3945. DebugMsg(SPeepholeOptimization + PreMessage +
  3946. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3947. end;
  3948. Result := True;
  3949. Exit;
  3950. end;
  3951. {$endif x86_64}
  3952. { Backward optimisation. If we have:
  3953. func. %reg1,%reg2
  3954. mov %reg2,%reg3
  3955. (dealloc %reg2)
  3956. Change to:
  3957. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3958. }
  3959. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3960. begin
  3961. CurrentReg := taicpu(p).oper[0]^.reg;
  3962. ActiveReg := taicpu(p).oper[1]^.reg;
  3963. TransferUsedRegs(TmpUsedRegs);
  3964. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3965. GetLastInstruction(p, hp2) and
  3966. (hp2.typ = ait_instruction) and
  3967. { Have to make sure it's an instruction that only reads from
  3968. operand 1 and only writes (not reads or modifies) from operand 2;
  3969. in essence, a one-operand pure function such as BSR or POPCNT }
  3970. (taicpu(hp2).ops = 2) and
  3971. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3972. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3973. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3974. begin
  3975. case taicpu(hp2).opcode of
  3976. A_FSTSW, A_FNSTSW,
  3977. A_IN, A_INS, A_OUT, A_OUTS,
  3978. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3979. { These routines have explicit operands, but they are restricted in
  3980. what they can be (e.g. IN and OUT can only read from AL, AX or
  3981. EAX. }
  3982. A_CMOVcc:
  3983. { CMOV is not valid either because then CurrentReg will depend
  3984. on an unknown value if the condition is False and hence is
  3985. not a pure write }
  3986. ;
  3987. else
  3988. begin
  3989. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3990. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3991. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3992. RemoveCurrentp(p, hp1);
  3993. Result := True;
  3994. Exit;
  3995. end;
  3996. end;
  3997. end;
  3998. end;
  3999. end;
  4000. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4001. var
  4002. hp1 : tai;
  4003. begin
  4004. Result:=false;
  4005. if taicpu(p).ops <> 2 then
  4006. exit;
  4007. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4008. GetNextInstruction(p,hp1) then
  4009. begin
  4010. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4011. (taicpu(hp1).ops = 2) then
  4012. begin
  4013. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4014. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4015. { movXX reg1, mem1 or movXX mem1, reg1
  4016. movXX mem2, reg2 movXX reg2, mem2}
  4017. begin
  4018. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4019. { movXX reg1, mem1 or movXX mem1, reg1
  4020. movXX mem2, reg1 movXX reg2, mem1}
  4021. begin
  4022. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4023. begin
  4024. { Removes the second statement from
  4025. movXX reg1, mem1/reg2
  4026. movXX mem1/reg2, reg1
  4027. }
  4028. if taicpu(p).oper[0]^.typ=top_reg then
  4029. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4030. { Removes the second statement from
  4031. movXX mem1/reg1, reg2
  4032. movXX reg2, mem1/reg1
  4033. }
  4034. if (taicpu(p).oper[1]^.typ=top_reg) and
  4035. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4036. begin
  4037. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4038. RemoveInstruction(hp1);
  4039. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4040. Result:=true;
  4041. exit;
  4042. end
  4043. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4044. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4045. begin
  4046. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4047. RemoveInstruction(hp1);
  4048. Result:=true;
  4049. exit;
  4050. end;
  4051. end
  4052. end;
  4053. end;
  4054. end;
  4055. end;
  4056. end;
  4057. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4058. var
  4059. hp1 : tai;
  4060. begin
  4061. result:=false;
  4062. { replace
  4063. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4064. MovX %mreg2,%mreg1
  4065. dealloc %mreg2
  4066. by
  4067. <Op>X %mreg2,%mreg1
  4068. ?
  4069. }
  4070. if GetNextInstruction(p,hp1) and
  4071. { we mix single and double opperations here because we assume that the compiler
  4072. generates vmovapd only after double operations and vmovaps only after single operations }
  4073. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4074. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4075. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4076. (taicpu(p).oper[0]^.typ=top_reg) then
  4077. begin
  4078. TransferUsedRegs(TmpUsedRegs);
  4079. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4080. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4081. begin
  4082. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4083. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4084. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4085. RemoveInstruction(hp1);
  4086. result:=true;
  4087. end;
  4088. end;
  4089. end;
  4090. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4091. var
  4092. hp1, p_label, p_dist, hp1_dist: tai;
  4093. JumpLabel, JumpLabel_dist: TAsmLabel;
  4094. FirstValue, SecondValue: TCGInt;
  4095. begin
  4096. Result := False;
  4097. if (taicpu(p).oper[0]^.typ = top_const) and
  4098. (taicpu(p).oper[0]^.val <> -1) then
  4099. begin
  4100. { Convert unsigned maximum constants to -1 to aid optimisation }
  4101. case taicpu(p).opsize of
  4102. S_B:
  4103. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4104. begin
  4105. taicpu(p).oper[0]^.val := -1;
  4106. Result := True;
  4107. Exit;
  4108. end;
  4109. S_W:
  4110. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4111. begin
  4112. taicpu(p).oper[0]^.val := -1;
  4113. Result := True;
  4114. Exit;
  4115. end;
  4116. S_L:
  4117. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4118. begin
  4119. taicpu(p).oper[0]^.val := -1;
  4120. Result := True;
  4121. Exit;
  4122. end;
  4123. {$ifdef x86_64}
  4124. S_Q:
  4125. { Storing anything greater than $7FFFFFFF is not possible so do
  4126. nothing };
  4127. {$endif x86_64}
  4128. else
  4129. InternalError(2021121001);
  4130. end;
  4131. end;
  4132. if GetNextInstruction(p, hp1) and
  4133. TrySwapMovCmp(p, hp1) then
  4134. begin
  4135. Result := True;
  4136. Exit;
  4137. end;
  4138. { Search for:
  4139. test $x,(reg/ref)
  4140. jne @lbl1
  4141. test $y,(reg/ref) (same register or reference)
  4142. jne @lbl1
  4143. Change to:
  4144. test $(x or y),(reg/ref)
  4145. jne @lbl1
  4146. (Note, this doesn't work with je instead of jne)
  4147. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4148. Also search for:
  4149. test $x,(reg/ref)
  4150. je @lbl1
  4151. test $y,(reg/ref)
  4152. je/jne @lbl2
  4153. If (x or y) = x, then the second jump is deterministic
  4154. }
  4155. if (
  4156. (
  4157. (taicpu(p).oper[0]^.typ = top_const) or
  4158. (
  4159. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4160. (taicpu(p).oper[0]^.typ = top_reg) and
  4161. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4162. )
  4163. ) and
  4164. MatchInstruction(hp1, A_JCC, [])
  4165. ) then
  4166. begin
  4167. if (taicpu(p).oper[0]^.typ = top_reg) and
  4168. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4169. FirstValue := -1
  4170. else
  4171. FirstValue := taicpu(p).oper[0]^.val;
  4172. { If we have several test/jne's in a row, it might be the case that
  4173. the second label doesn't go to the same location, but the one
  4174. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4175. so accommodate for this with a while loop.
  4176. }
  4177. hp1_dist := hp1;
  4178. if GetNextInstruction(hp1, p_dist) and
  4179. (p_dist.typ = ait_instruction) and
  4180. (
  4181. (
  4182. (taicpu(p_dist).opcode = A_TEST) and
  4183. (
  4184. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4185. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4186. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4187. )
  4188. ) or
  4189. (
  4190. { cmp 0,%reg = test %reg,%reg }
  4191. (taicpu(p_dist).opcode = A_CMP) and
  4192. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4193. )
  4194. ) and
  4195. { Make sure the destination operands are actually the same }
  4196. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4197. GetNextInstruction(p_dist, hp1_dist) and
  4198. MatchInstruction(hp1_dist, A_JCC, []) then
  4199. begin
  4200. if
  4201. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4202. (
  4203. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4204. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4205. ) then
  4206. SecondValue := -1
  4207. else
  4208. SecondValue := taicpu(p_dist).oper[0]^.val;
  4209. { If both of the TEST constants are identical, delete the second
  4210. TEST that is unnecessary. }
  4211. if (FirstValue = SecondValue) then
  4212. begin
  4213. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4214. RemoveInstruction(p_dist);
  4215. { Don't let the flags register become deallocated and reallocated between the jumps }
  4216. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4217. Result := True;
  4218. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4219. begin
  4220. { Since the second jump's condition is a subset of the first, we
  4221. know it will never branch because the first jump dominates it.
  4222. Get it out of the way now rather than wait for the jump
  4223. optimisations for a speed boost. }
  4224. if IsJumpToLabel(taicpu(hp1_dist)) then
  4225. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4226. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4227. RemoveInstruction(hp1_dist);
  4228. end
  4229. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4230. begin
  4231. { If the inverse of the first condition is a subset of the second,
  4232. the second one will definitely branch if the first one doesn't }
  4233. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4234. MakeUnconditional(taicpu(hp1_dist));
  4235. RemoveDeadCodeAfterJump(hp1_dist);
  4236. end;
  4237. Exit;
  4238. end;
  4239. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4240. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4241. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4242. then the second jump will never branch, so it can also be
  4243. removed regardless of where it goes }
  4244. (
  4245. (FirstValue = -1) or
  4246. (SecondValue = -1) or
  4247. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4248. ) then
  4249. begin
  4250. { Same jump location... can be a register since nothing's changed }
  4251. { If any of the entries are equivalent to test %reg,%reg, then the
  4252. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4253. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4254. if IsJumpToLabel(taicpu(hp1_dist)) then
  4255. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4256. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4257. RemoveInstruction(hp1_dist);
  4258. { Only remove the second test if no jumps or other conditional instructions follow }
  4259. TransferUsedRegs(TmpUsedRegs);
  4260. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4262. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4263. RemoveInstruction(p_dist);
  4264. Result := True;
  4265. Exit;
  4266. end;
  4267. end;
  4268. end;
  4269. { Search for:
  4270. test %reg,%reg
  4271. j(c1) @lbl1
  4272. ...
  4273. @lbl:
  4274. test %reg,%reg (same register)
  4275. j(c2) @lbl2
  4276. If c2 is a subset of c1, change to:
  4277. test %reg,%reg
  4278. j(c1) @lbl2
  4279. (@lbl1 may become a dead label as a result)
  4280. }
  4281. if (taicpu(p).oper[1]^.typ = top_reg) and
  4282. (taicpu(p).oper[0]^.typ = top_reg) and
  4283. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4284. MatchInstruction(hp1, A_JCC, []) and
  4285. IsJumpToLabel(taicpu(hp1)) then
  4286. begin
  4287. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4288. p_label := nil;
  4289. if Assigned(JumpLabel) then
  4290. p_label := getlabelwithsym(JumpLabel);
  4291. if Assigned(p_label) and
  4292. GetNextInstruction(p_label, p_dist) and
  4293. MatchInstruction(p_dist, A_TEST, []) and
  4294. { It's fine if the second test uses smaller sub-registers }
  4295. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4296. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4297. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4298. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4299. GetNextInstruction(p_dist, hp1_dist) and
  4300. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4301. begin
  4302. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4303. if JumpLabel = JumpLabel_dist then
  4304. { This is an infinite loop }
  4305. Exit;
  4306. { Best optimisation when the first condition is a subset (or equal) of the second }
  4307. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4308. begin
  4309. { Any registers used here will already be allocated }
  4310. if Assigned(JumpLabel_dist) then
  4311. JumpLabel_dist.IncRefs;
  4312. if Assigned(JumpLabel) then
  4313. JumpLabel.DecRefs;
  4314. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4315. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4316. Result := True;
  4317. Exit;
  4318. end;
  4319. end;
  4320. end;
  4321. end;
  4322. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4323. var
  4324. hp1, hp2: tai;
  4325. ActiveReg: TRegister;
  4326. OldOffset: asizeint;
  4327. ThisConst: TCGInt;
  4328. function RegDeallocated: Boolean;
  4329. begin
  4330. TransferUsedRegs(TmpUsedRegs);
  4331. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4332. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4333. end;
  4334. begin
  4335. result:=false;
  4336. hp1 := nil;
  4337. { replace
  4338. addX const,%reg1
  4339. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4340. dealloc %reg1
  4341. by
  4342. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4343. }
  4344. if MatchOpType(taicpu(p),top_const,top_reg) then
  4345. begin
  4346. ActiveReg := taicpu(p).oper[1]^.reg;
  4347. { Ensures the entire register was updated }
  4348. if (taicpu(p).opsize >= S_L) and
  4349. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4350. MatchInstruction(hp1,A_LEA,[]) and
  4351. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4352. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4353. (
  4354. { Cover the case where the register in the reference is also the destination register }
  4355. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4356. (
  4357. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4358. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4359. RegDeallocated
  4360. )
  4361. ) then
  4362. begin
  4363. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4364. {$push}
  4365. {$R-}{$Q-}
  4366. { Explicitly disable overflow checking for these offset calculation
  4367. as those do not matter for the final result }
  4368. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4369. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4370. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4371. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4372. {$pop}
  4373. {$ifdef x86_64}
  4374. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4375. begin
  4376. { Overflow; abort }
  4377. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4378. end
  4379. else
  4380. {$endif x86_64}
  4381. begin
  4382. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4383. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4384. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4385. RemoveCurrentP(p, hp1)
  4386. else
  4387. RemoveCurrentP(p);
  4388. result:=true;
  4389. Exit;
  4390. end;
  4391. end;
  4392. if (
  4393. { Save calling GetNextInstructionUsingReg again }
  4394. Assigned(hp1) or
  4395. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4396. ) and
  4397. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4398. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4399. begin
  4400. if taicpu(hp1).oper[0]^.typ = top_const then
  4401. begin
  4402. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4403. if taicpu(hp1).opcode = A_ADD then
  4404. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4405. else
  4406. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4407. Result := True;
  4408. { Handle any overflows }
  4409. case taicpu(p).opsize of
  4410. S_B:
  4411. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4412. S_W:
  4413. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4414. S_L:
  4415. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4416. {$ifdef x86_64}
  4417. S_Q:
  4418. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4419. { Overflow; abort }
  4420. Result := False
  4421. else
  4422. taicpu(p).oper[0]^.val := ThisConst;
  4423. {$endif x86_64}
  4424. else
  4425. InternalError(2021102610);
  4426. end;
  4427. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4428. if Result then
  4429. begin
  4430. if (taicpu(p).oper[0]^.val < 0) and
  4431. (
  4432. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4433. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4434. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4435. ) then
  4436. begin
  4437. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4438. taicpu(p).opcode := A_SUB;
  4439. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4440. end
  4441. else
  4442. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4443. RemoveInstruction(hp1);
  4444. end;
  4445. end
  4446. else
  4447. begin
  4448. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4449. TransferUsedRegs(TmpUsedRegs);
  4450. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4451. hp2 := p;
  4452. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4453. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4454. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4455. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4456. begin
  4457. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4458. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4459. Asml.Remove(p);
  4460. Asml.InsertAfter(p, hp1);
  4461. p := hp1;
  4462. Result := True;
  4463. end;
  4464. end;
  4465. end;
  4466. end;
  4467. end;
  4468. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4469. var
  4470. hp1: tai;
  4471. ref: Integer;
  4472. saveref: treference;
  4473. TempReg: TRegister;
  4474. Multiple: TCGInt;
  4475. begin
  4476. Result:=false;
  4477. { play save and throw an error if LEA uses a seg register prefix,
  4478. this is most likely an error somewhere else }
  4479. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4480. internalerror(2022022001);
  4481. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4482. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4483. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4484. (
  4485. { do not mess with leas accessing the stack pointer
  4486. unless it's a null operation }
  4487. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4488. (
  4489. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4490. (taicpu(p).oper[0]^.ref^.offset = 0)
  4491. )
  4492. ) and
  4493. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4494. begin
  4495. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4496. begin
  4497. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4498. begin
  4499. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4500. taicpu(p).oper[1]^.reg);
  4501. InsertLLItem(p.previous,p.next, hp1);
  4502. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4503. p.free;
  4504. p:=hp1;
  4505. end
  4506. else
  4507. begin
  4508. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4509. RemoveCurrentP(p);
  4510. end;
  4511. Result:=true;
  4512. exit;
  4513. end
  4514. else if (
  4515. { continue to use lea to adjust the stack pointer,
  4516. it is the recommended way, but only if not optimizing for size }
  4517. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4518. (cs_opt_size in current_settings.optimizerswitches)
  4519. ) and
  4520. { If the flags register is in use, don't change the instruction
  4521. to an ADD otherwise this will scramble the flags. [Kit] }
  4522. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4523. ConvertLEA(taicpu(p)) then
  4524. begin
  4525. Result:=true;
  4526. exit;
  4527. end;
  4528. end;
  4529. if GetNextInstruction(p,hp1) and
  4530. (hp1.typ=ait_instruction) then
  4531. begin
  4532. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4533. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4534. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4535. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4536. begin
  4537. TransferUsedRegs(TmpUsedRegs);
  4538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4539. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4540. begin
  4541. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4542. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4543. RemoveInstruction(hp1);
  4544. result:=true;
  4545. exit;
  4546. end;
  4547. end;
  4548. { changes
  4549. lea <ref1>, reg1
  4550. <op> ...,<ref. with reg1>,...
  4551. to
  4552. <op> ...,<ref1>,... }
  4553. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4554. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4555. not(MatchInstruction(hp1,A_LEA,[])) then
  4556. begin
  4557. { find a reference which uses reg1 }
  4558. 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
  4559. ref:=0
  4560. 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
  4561. ref:=1
  4562. else
  4563. ref:=-1;
  4564. if (ref<>-1) and
  4565. { reg1 must be either the base or the index }
  4566. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4567. begin
  4568. { reg1 can be removed from the reference }
  4569. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4570. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4571. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4572. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4573. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4574. else
  4575. Internalerror(2019111201);
  4576. { check if the can insert all data of the lea into the second instruction }
  4577. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4578. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4579. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4580. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4581. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4582. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4583. { Segment register of p.oper[0]^.ref will be NR_NO already }
  4584. (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4585. {$ifdef x86_64}
  4586. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4587. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4588. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4589. )
  4590. {$endif x86_64}
  4591. then
  4592. begin
  4593. { reg1 might not used by the second instruction after it is remove from the reference }
  4594. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4595. begin
  4596. TransferUsedRegs(TmpUsedRegs);
  4597. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4598. { reg1 is not updated so it might not be used afterwards }
  4599. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4600. begin
  4601. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4602. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4603. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4604. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4605. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4606. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4607. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4608. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4609. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4610. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4611. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4612. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4613. RemoveCurrentP(p, hp1);
  4614. result:=true;
  4615. exit;
  4616. end
  4617. end;
  4618. end;
  4619. { recover }
  4620. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4621. end;
  4622. end;
  4623. end;
  4624. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4625. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4626. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4627. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4628. begin
  4629. { Check common LEA/LEA conditions }
  4630. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4631. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4632. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4633. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4634. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4635. { Since we're merging two LEA instructions, the segment registers don't matter }
  4636. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4637. (
  4638. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4639. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4640. ) and (
  4641. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4642. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4643. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4644. ) then
  4645. begin
  4646. { changes
  4647. lea (regX,scale), reg1
  4648. lea offset(reg1,reg1), reg1
  4649. to
  4650. lea offset(regX,scale*2), reg1
  4651. and
  4652. lea (regX,scale1), reg1
  4653. lea offset(reg1,scale2), reg1
  4654. to
  4655. lea offset(regX,scale1*scale2), reg1
  4656. ... so long as the final scale does not exceed 8
  4657. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4658. }
  4659. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4660. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4661. (
  4662. (
  4663. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4664. ) or (
  4665. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4666. (
  4667. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4668. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4669. )
  4670. )
  4671. ) and (
  4672. (
  4673. { lea (reg1,scale2), reg1 variant }
  4674. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4675. (
  4676. (
  4677. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4678. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4679. ) or (
  4680. { lea (regX,regX), reg1 variant }
  4681. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4682. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4683. )
  4684. )
  4685. ) or (
  4686. { lea (reg1,reg1), reg1 variant }
  4687. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4688. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4689. )
  4690. ) then
  4691. begin
  4692. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4693. { Make everything homogeneous to make calculations easier }
  4694. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4695. begin
  4696. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4697. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4698. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4699. else
  4700. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4701. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4702. end;
  4703. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4704. begin
  4705. { Just to prevent miscalculations }
  4706. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4707. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4708. else
  4709. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4710. end
  4711. else
  4712. begin
  4713. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4714. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4715. end;
  4716. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4717. RemoveCurrentP(p);
  4718. result:=true;
  4719. exit;
  4720. end
  4721. { changes
  4722. lea offset1(regX), reg1
  4723. lea offset2(reg1), reg1
  4724. to
  4725. lea offset1+offset2(regX), reg1 }
  4726. else if
  4727. (
  4728. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4729. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4730. ) or (
  4731. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4732. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4733. (
  4734. (
  4735. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4736. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4737. ) or (
  4738. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4739. (
  4740. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4741. (
  4742. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4743. (
  4744. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4745. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4746. )
  4747. )
  4748. )
  4749. )
  4750. )
  4751. ) then
  4752. begin
  4753. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4754. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4755. begin
  4756. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4757. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4758. { if the register is used as index and base, we have to increase for base as well
  4759. and adapt base }
  4760. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4761. begin
  4762. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4763. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4764. end;
  4765. end
  4766. else
  4767. begin
  4768. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4769. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4770. end;
  4771. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4772. begin
  4773. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4774. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4775. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4776. end;
  4777. RemoveCurrentP(p);
  4778. result:=true;
  4779. exit;
  4780. end;
  4781. end;
  4782. { Change:
  4783. leal/q $x(%reg1),%reg2
  4784. ...
  4785. shll/q $y,%reg2
  4786. To:
  4787. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4788. }
  4789. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4790. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4791. (taicpu(hp1).oper[0]^.val <= 3) then
  4792. begin
  4793. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4794. TransferUsedRegs(TmpUsedRegs);
  4795. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4796. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4797. if
  4798. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4799. (this works even if scalefactor is zero) }
  4800. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4801. { Ensure offset doesn't go out of bounds }
  4802. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4803. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4804. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4805. (
  4806. (
  4807. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4808. (
  4809. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4810. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4811. (
  4812. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4813. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4814. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4815. )
  4816. )
  4817. ) or (
  4818. (
  4819. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4820. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4821. ) and
  4822. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4823. )
  4824. ) then
  4825. begin
  4826. repeat
  4827. with taicpu(p).oper[0]^.ref^ do
  4828. begin
  4829. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4830. if index = base then
  4831. begin
  4832. if Multiple > 4 then
  4833. { Optimisation will no longer work because resultant
  4834. scale factor will exceed 8 }
  4835. Break;
  4836. base := NR_NO;
  4837. scalefactor := 2;
  4838. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4839. end
  4840. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4841. begin
  4842. { Scale factor only works on the index register }
  4843. index := base;
  4844. base := NR_NO;
  4845. end;
  4846. { For safety }
  4847. if scalefactor <= 1 then
  4848. begin
  4849. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4850. scalefactor := Multiple;
  4851. end
  4852. else
  4853. begin
  4854. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4855. scalefactor := scalefactor * Multiple;
  4856. end;
  4857. offset := offset * Multiple;
  4858. end;
  4859. RemoveInstruction(hp1);
  4860. Result := True;
  4861. Exit;
  4862. { This repeat..until loop exists for the benefit of Break }
  4863. until True;
  4864. end;
  4865. end;
  4866. end;
  4867. end;
  4868. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4869. var
  4870. hp1 : tai;
  4871. begin
  4872. DoSubAddOpt := False;
  4873. if taicpu(p).oper[0]^.typ <> top_const then
  4874. { Should have been confirmed before calling }
  4875. InternalError(2021102601);
  4876. if GetLastInstruction(p, hp1) and
  4877. (hp1.typ = ait_instruction) and
  4878. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4879. case taicpu(hp1).opcode Of
  4880. A_DEC:
  4881. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4882. begin
  4883. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4884. RemoveInstruction(hp1);
  4885. end;
  4886. A_SUB:
  4887. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4888. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4889. begin
  4890. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4891. RemoveInstruction(hp1);
  4892. end;
  4893. A_ADD:
  4894. begin
  4895. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4896. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4897. begin
  4898. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4899. RemoveInstruction(hp1);
  4900. if (taicpu(p).oper[0]^.val = 0) then
  4901. begin
  4902. hp1 := tai(p.next);
  4903. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4904. if not GetLastInstruction(hp1, p) then
  4905. p := hp1;
  4906. DoSubAddOpt := True;
  4907. end
  4908. end;
  4909. end;
  4910. else
  4911. ;
  4912. end;
  4913. end;
  4914. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4915. begin
  4916. Result := False;
  4917. if UpdateTmpUsedRegs then
  4918. TransferUsedRegs(TmpUsedRegs);
  4919. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4920. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4921. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4922. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4923. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4924. (
  4925. (
  4926. (taicpu(hp1).opcode = A_TEST)
  4927. ) or (
  4928. (taicpu(hp1).opcode = A_CMP) and
  4929. { A sanity check more than anything }
  4930. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4931. )
  4932. ) then
  4933. begin
  4934. { change
  4935. mov mem, %reg
  4936. cmp/test x, %reg / test %reg,%reg
  4937. (reg deallocated)
  4938. to
  4939. cmp/test x, mem / cmp 0, mem
  4940. }
  4941. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4942. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4943. begin
  4944. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4945. if (taicpu(hp1).opcode = A_TEST) and
  4946. (
  4947. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4948. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4949. ) then
  4950. begin
  4951. taicpu(hp1).opcode := A_CMP;
  4952. taicpu(hp1).loadconst(0, 0);
  4953. end;
  4954. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4955. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4956. RemoveCurrentP(p, hp1);
  4957. Result := True;
  4958. Exit;
  4959. end;
  4960. end;
  4961. end;
  4962. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  4963. var
  4964. hp2, hp3, hp4, hp5, hp6: tai;
  4965. ThisReg: TRegister;
  4966. JumpLoc: TAsmLabel;
  4967. begin
  4968. Result := False;
  4969. {
  4970. Convert:
  4971. j<c> .L1
  4972. .L2:
  4973. mov 1,reg
  4974. jmp .L3 (or ret, although it might not be a RET yet)
  4975. .L1:
  4976. mov 0,reg
  4977. jmp .L3 (or ret)
  4978. ( As long as .L3 <> .L1 or .L2)
  4979. To:
  4980. mov 0,reg
  4981. set<not(c)> reg
  4982. jmp .L3 (or ret)
  4983. .L2:
  4984. mov 1,reg
  4985. jmp .L3 (or ret)
  4986. .L1:
  4987. mov 0,reg
  4988. jmp .L3 (or ret)
  4989. }
  4990. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  4991. Exit;
  4992. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  4993. if GetNextInstruction(hp_label, hp2) and
  4994. MatchInstruction(hp2,A_MOV,[]) and
  4995. (taicpu(hp2).oper[0]^.typ = top_const) and
  4996. (
  4997. (
  4998. (taicpu(hp2).oper[1]^.typ = top_reg)
  4999. {$ifdef i386}
  5000. { Under i386, ESI, EDI, EBP and ESP
  5001. don't have an 8-bit representation }
  5002. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5003. {$endif i386}
  5004. ) or (
  5005. {$ifdef i386}
  5006. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5007. {$endif i386}
  5008. (taicpu(hp2).opsize = S_B)
  5009. )
  5010. ) and
  5011. GetNextInstruction(hp2, hp3) and
  5012. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5013. (
  5014. (taicpu(hp3).opcode=A_RET) or
  5015. (
  5016. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5017. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5018. )
  5019. ) and
  5020. GetNextInstruction(hp3, hp4) and
  5021. SkipAligns(hp4, hp4) and
  5022. (hp4.typ=ait_label) and
  5023. (tai_label(hp4).labsym=JumpLoc) and
  5024. (
  5025. not (cs_opt_size in current_settings.optimizerswitches) or
  5026. { If the initial jump is the label's only reference, then it will
  5027. become a dead label if the other conditions are met and hence
  5028. remove at least 2 instructions, including a jump }
  5029. (JumpLoc.getrefs = 1)
  5030. ) and
  5031. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5032. that will be optimised out }
  5033. GetNextInstruction(hp4, hp5) and
  5034. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5035. (taicpu(hp5).oper[0]^.typ = top_const) and
  5036. (
  5037. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5038. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5039. ) and
  5040. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5041. GetNextInstruction(hp5,hp6) and
  5042. (
  5043. (hp6.typ<>ait_label) or
  5044. SkipLabels(hp6, hp6)
  5045. ) and
  5046. (hp6.typ=ait_instruction) then
  5047. begin
  5048. { First, let's look at the two jumps that are hp3 and hp6 }
  5049. if not
  5050. (
  5051. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5052. (
  5053. (taicpu(hp6).opcode=A_RET) or
  5054. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5055. )
  5056. ) then
  5057. { If condition is False, then the JMP/RET instructions matched conventionally }
  5058. begin
  5059. { See if one of the jumps can be instantly converted into a RET }
  5060. if (taicpu(hp3).opcode=A_JMP) then
  5061. begin
  5062. { Reuse hp5 }
  5063. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5064. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5065. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5066. Exit;
  5067. if MatchInstruction(hp5, A_RET, []) then
  5068. begin
  5069. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5070. ConvertJumpToRET(hp3, hp5);
  5071. Result := True;
  5072. end
  5073. else
  5074. Exit;
  5075. end;
  5076. if (taicpu(hp6).opcode=A_JMP) then
  5077. begin
  5078. { Reuse hp5 }
  5079. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5080. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5081. Exit;
  5082. if MatchInstruction(hp5, A_RET, []) then
  5083. begin
  5084. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5085. ConvertJumpToRET(hp6, hp5);
  5086. Result := True;
  5087. end
  5088. else
  5089. Exit;
  5090. end;
  5091. if not
  5092. (
  5093. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5094. (
  5095. (taicpu(hp6).opcode=A_RET) or
  5096. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5097. )
  5098. ) then
  5099. { Still doesn't match }
  5100. Exit;
  5101. end;
  5102. if (taicpu(hp2).oper[0]^.val = 1) then
  5103. begin
  5104. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5105. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5106. end
  5107. else
  5108. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5109. if taicpu(hp2).opsize=S_B then
  5110. begin
  5111. if taicpu(hp2).oper[1]^.typ = top_reg then
  5112. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5113. else
  5114. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5115. hp2 := p;
  5116. end
  5117. else
  5118. begin
  5119. { Will be a register because the size can't be S_B otherwise }
  5120. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5121. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5122. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5123. { Inserting it right before p will guarantee that the flags are also tracked }
  5124. Asml.InsertBefore(hp2, p);
  5125. end;
  5126. taicpu(hp4).condition:=taicpu(p).condition;
  5127. asml.InsertBefore(hp4, hp2);
  5128. JumpLoc.decrefs;
  5129. if taicpu(hp3).opcode = A_JMP then
  5130. begin
  5131. MakeUnconditional(taicpu(p));
  5132. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5133. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5134. end
  5135. else
  5136. begin
  5137. taicpu(p).condition := C_None;
  5138. taicpu(p).opcode := A_RET;
  5139. taicpu(p).clearop(0);
  5140. taicpu(p).ops := 0;
  5141. end;
  5142. if (JumpLoc.getrefs = 0) then
  5143. RemoveDeadCodeAfterJump(hp3);
  5144. Result:=true;
  5145. exit;
  5146. end;
  5147. end;
  5148. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5149. var
  5150. hp1, hp2: tai;
  5151. ActiveReg: TRegister;
  5152. OldOffset: asizeint;
  5153. ThisConst: TCGInt;
  5154. function RegDeallocated: Boolean;
  5155. begin
  5156. TransferUsedRegs(TmpUsedRegs);
  5157. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5158. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5159. end;
  5160. begin
  5161. Result:=false;
  5162. hp1 := nil;
  5163. { replace
  5164. subX const,%reg1
  5165. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5166. dealloc %reg1
  5167. by
  5168. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5169. }
  5170. if MatchOpType(taicpu(p),top_const,top_reg) then
  5171. begin
  5172. ActiveReg := taicpu(p).oper[1]^.reg;
  5173. { Ensures the entire register was updated }
  5174. if (taicpu(p).opsize >= S_L) and
  5175. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5176. MatchInstruction(hp1,A_LEA,[]) and
  5177. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5178. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5179. (
  5180. { Cover the case where the register in the reference is also the destination register }
  5181. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5182. (
  5183. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5184. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5185. RegDeallocated
  5186. )
  5187. ) then
  5188. begin
  5189. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5190. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5191. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5192. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5193. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5194. {$ifdef x86_64}
  5195. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5196. begin
  5197. { Overflow; abort }
  5198. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5199. end
  5200. else
  5201. {$endif x86_64}
  5202. begin
  5203. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5204. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5205. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5206. RemoveCurrentP(p, hp1)
  5207. else
  5208. RemoveCurrentP(p);
  5209. result:=true;
  5210. Exit;
  5211. end;
  5212. end;
  5213. if (
  5214. { Save calling GetNextInstructionUsingReg again }
  5215. Assigned(hp1) or
  5216. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5217. ) and
  5218. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5219. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5220. begin
  5221. if taicpu(hp1).oper[0]^.typ = top_const then
  5222. begin
  5223. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5224. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5225. Result := True;
  5226. { Handle any overflows }
  5227. case taicpu(p).opsize of
  5228. S_B:
  5229. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5230. S_W:
  5231. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5232. S_L:
  5233. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5234. {$ifdef x86_64}
  5235. S_Q:
  5236. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5237. { Overflow; abort }
  5238. Result := False
  5239. else
  5240. taicpu(p).oper[0]^.val := ThisConst;
  5241. {$endif x86_64}
  5242. else
  5243. InternalError(2021102610);
  5244. end;
  5245. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5246. if Result then
  5247. begin
  5248. if (taicpu(p).oper[0]^.val < 0) and
  5249. (
  5250. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5251. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5252. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5253. ) then
  5254. begin
  5255. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5256. taicpu(p).opcode := A_SUB;
  5257. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5258. end
  5259. else
  5260. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5261. RemoveInstruction(hp1);
  5262. end;
  5263. end
  5264. else
  5265. begin
  5266. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5267. TransferUsedRegs(TmpUsedRegs);
  5268. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5269. hp2 := p;
  5270. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5271. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5272. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5273. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5274. begin
  5275. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5276. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5277. Asml.Remove(p);
  5278. Asml.InsertAfter(p, hp1);
  5279. p := hp1;
  5280. Result := True;
  5281. Exit;
  5282. end;
  5283. end;
  5284. end;
  5285. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5286. { * change "sub/add const1, reg" or "dec reg" followed by
  5287. "sub const2, reg" to one "sub ..., reg" }
  5288. {$ifdef i386}
  5289. if (taicpu(p).oper[0]^.val = 2) and
  5290. (ActiveReg = NR_ESP) and
  5291. { Don't do the sub/push optimization if the sub }
  5292. { comes from setting up the stack frame (JM) }
  5293. (not(GetLastInstruction(p,hp1)) or
  5294. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5295. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5296. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5297. begin
  5298. hp1 := tai(p.next);
  5299. while Assigned(hp1) and
  5300. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5301. not RegReadByInstruction(NR_ESP,hp1) and
  5302. not RegModifiedByInstruction(NR_ESP,hp1) do
  5303. hp1 := tai(hp1.next);
  5304. if Assigned(hp1) and
  5305. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5306. begin
  5307. taicpu(hp1).changeopsize(S_L);
  5308. if taicpu(hp1).oper[0]^.typ=top_reg then
  5309. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5310. hp1 := tai(p.next);
  5311. RemoveCurrentp(p, hp1);
  5312. Result:=true;
  5313. exit;
  5314. end;
  5315. end;
  5316. {$endif i386}
  5317. if DoSubAddOpt(p) then
  5318. Result:=true;
  5319. end;
  5320. end;
  5321. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5322. var
  5323. TmpBool1,TmpBool2 : Boolean;
  5324. tmpref : treference;
  5325. hp1,hp2: tai;
  5326. mask: tcgint;
  5327. begin
  5328. Result:=false;
  5329. { All these optimisations work on "shl/sal const,%reg" }
  5330. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5331. Exit;
  5332. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5333. (taicpu(p).oper[0]^.val <= 3) then
  5334. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5335. begin
  5336. { should we check the next instruction? }
  5337. TmpBool1 := True;
  5338. { have we found an add/sub which could be
  5339. integrated in the lea? }
  5340. TmpBool2 := False;
  5341. reference_reset(tmpref,2,[]);
  5342. TmpRef.index := taicpu(p).oper[1]^.reg;
  5343. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5344. while TmpBool1 and
  5345. GetNextInstruction(p, hp1) and
  5346. (tai(hp1).typ = ait_instruction) and
  5347. ((((taicpu(hp1).opcode = A_ADD) or
  5348. (taicpu(hp1).opcode = A_SUB)) and
  5349. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5350. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5351. (((taicpu(hp1).opcode = A_INC) or
  5352. (taicpu(hp1).opcode = A_DEC)) and
  5353. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5354. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5355. ((taicpu(hp1).opcode = A_LEA) and
  5356. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5357. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5358. (not GetNextInstruction(hp1,hp2) or
  5359. not instrReadsFlags(hp2)) Do
  5360. begin
  5361. TmpBool1 := False;
  5362. if taicpu(hp1).opcode=A_LEA then
  5363. begin
  5364. if (TmpRef.base = NR_NO) and
  5365. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5366. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5367. { Segment register isn't a concern here }
  5368. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5369. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5370. begin
  5371. TmpBool1 := True;
  5372. TmpBool2 := True;
  5373. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5374. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5375. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5376. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5377. RemoveInstruction(hp1);
  5378. end
  5379. end
  5380. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5381. begin
  5382. TmpBool1 := True;
  5383. TmpBool2 := True;
  5384. case taicpu(hp1).opcode of
  5385. A_ADD:
  5386. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5387. A_SUB:
  5388. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5389. else
  5390. internalerror(2019050536);
  5391. end;
  5392. RemoveInstruction(hp1);
  5393. end
  5394. else
  5395. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5396. (((taicpu(hp1).opcode = A_ADD) and
  5397. (TmpRef.base = NR_NO)) or
  5398. (taicpu(hp1).opcode = A_INC) or
  5399. (taicpu(hp1).opcode = A_DEC)) then
  5400. begin
  5401. TmpBool1 := True;
  5402. TmpBool2 := True;
  5403. case taicpu(hp1).opcode of
  5404. A_ADD:
  5405. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5406. A_INC:
  5407. inc(TmpRef.offset);
  5408. A_DEC:
  5409. dec(TmpRef.offset);
  5410. else
  5411. internalerror(2019050535);
  5412. end;
  5413. RemoveInstruction(hp1);
  5414. end;
  5415. end;
  5416. if TmpBool2
  5417. {$ifndef x86_64}
  5418. or
  5419. ((current_settings.optimizecputype < cpu_Pentium2) and
  5420. (taicpu(p).oper[0]^.val <= 3) and
  5421. not(cs_opt_size in current_settings.optimizerswitches))
  5422. {$endif x86_64}
  5423. then
  5424. begin
  5425. if not(TmpBool2) and
  5426. (taicpu(p).oper[0]^.val=1) then
  5427. begin
  5428. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5429. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5430. end
  5431. else
  5432. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5433. taicpu(p).oper[1]^.reg);
  5434. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5435. InsertLLItem(p.previous, p.next, hp1);
  5436. p.free;
  5437. p := hp1;
  5438. end;
  5439. end
  5440. {$ifndef x86_64}
  5441. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5442. begin
  5443. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5444. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5445. (unlike shl, which is only Tairable in the U pipe) }
  5446. if taicpu(p).oper[0]^.val=1 then
  5447. begin
  5448. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5449. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5450. InsertLLItem(p.previous, p.next, hp1);
  5451. p.free;
  5452. p := hp1;
  5453. end
  5454. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5455. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5456. else if (taicpu(p).opsize = S_L) and
  5457. (taicpu(p).oper[0]^.val<= 3) then
  5458. begin
  5459. reference_reset(tmpref,2,[]);
  5460. TmpRef.index := taicpu(p).oper[1]^.reg;
  5461. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5462. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5463. InsertLLItem(p.previous, p.next, hp1);
  5464. p.free;
  5465. p := hp1;
  5466. end;
  5467. end
  5468. {$endif x86_64}
  5469. else if
  5470. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5471. (
  5472. (
  5473. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5474. SetAndTest(hp1, hp2)
  5475. {$ifdef x86_64}
  5476. ) or
  5477. (
  5478. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5479. GetNextInstruction(hp1, hp2) and
  5480. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5481. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5482. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5483. {$endif x86_64}
  5484. )
  5485. ) and
  5486. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5487. begin
  5488. { Change:
  5489. shl x, %reg1
  5490. mov -(1<<x), %reg2
  5491. and %reg2, %reg1
  5492. Or:
  5493. shl x, %reg1
  5494. and -(1<<x), %reg1
  5495. To just:
  5496. shl x, %reg1
  5497. Since the and operation only zeroes bits that are already zero from the shl operation
  5498. }
  5499. case taicpu(p).oper[0]^.val of
  5500. 8:
  5501. mask:=$FFFFFFFFFFFFFF00;
  5502. 16:
  5503. mask:=$FFFFFFFFFFFF0000;
  5504. 32:
  5505. mask:=$FFFFFFFF00000000;
  5506. 63:
  5507. { Constant pre-calculated to prevent overflow errors with Int64 }
  5508. mask:=$8000000000000000;
  5509. else
  5510. begin
  5511. if taicpu(p).oper[0]^.val >= 64 then
  5512. { Shouldn't happen realistically, since the register
  5513. is guaranteed to be set to zero at this point }
  5514. mask := 0
  5515. else
  5516. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5517. end;
  5518. end;
  5519. if taicpu(hp1).oper[0]^.val = mask then
  5520. begin
  5521. { Everything checks out, perform the optimisation, as long as
  5522. the FLAGS register isn't being used}
  5523. TransferUsedRegs(TmpUsedRegs);
  5524. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5525. {$ifdef x86_64}
  5526. if (hp1 <> hp2) then
  5527. begin
  5528. { "shl/mov/and" version }
  5529. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5530. { Don't do the optimisation if the FLAGS register is in use }
  5531. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5532. begin
  5533. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5534. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5535. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5536. begin
  5537. RemoveInstruction(hp1);
  5538. Result := True;
  5539. end;
  5540. { Only set Result to True if the 'mov' instruction was removed }
  5541. RemoveInstruction(hp2);
  5542. end;
  5543. end
  5544. else
  5545. {$endif x86_64}
  5546. begin
  5547. { "shl/and" version }
  5548. { Don't do the optimisation if the FLAGS register is in use }
  5549. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5550. begin
  5551. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5552. RemoveInstruction(hp1);
  5553. Result := True;
  5554. end;
  5555. end;
  5556. Exit;
  5557. end
  5558. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5559. begin
  5560. { Even if the mask doesn't allow for its removal, we might be
  5561. able to optimise the mask for the "shl/and" version, which
  5562. may permit other peephole optimisations }
  5563. {$ifdef DEBUG_AOPTCPU}
  5564. mask := taicpu(hp1).oper[0]^.val and mask;
  5565. if taicpu(hp1).oper[0]^.val <> mask then
  5566. begin
  5567. DebugMsg(
  5568. SPeepholeOptimization +
  5569. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5570. ' to $' + debug_tostr(mask) +
  5571. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5572. taicpu(hp1).oper[0]^.val := mask;
  5573. end;
  5574. {$else DEBUG_AOPTCPU}
  5575. { If debugging is off, just set the operand even if it's the same }
  5576. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5577. {$endif DEBUG_AOPTCPU}
  5578. end;
  5579. end;
  5580. {
  5581. change
  5582. shl/sal const,reg
  5583. <op> ...(...,reg,1),...
  5584. into
  5585. <op> ...(...,reg,1 shl const),...
  5586. if const in 1..3
  5587. }
  5588. if MatchOpType(taicpu(p), top_const, top_reg) and
  5589. (taicpu(p).oper[0]^.val in [1..3]) and
  5590. GetNextInstruction(p, hp1) and
  5591. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5592. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5593. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5594. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5595. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5596. begin
  5597. TransferUsedRegs(TmpUsedRegs);
  5598. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5599. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5600. begin
  5601. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5602. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5603. RemoveCurrentP(p);
  5604. Result:=true;
  5605. end;
  5606. end;
  5607. end;
  5608. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5609. var
  5610. CurrentRef: TReference;
  5611. FullReg: TRegister;
  5612. hp1, hp2: tai;
  5613. begin
  5614. Result := False;
  5615. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5616. Exit;
  5617. { We assume you've checked if the operand is actually a reference by
  5618. this point. If it isn't, you'll most likely get an access violation }
  5619. CurrentRef := first_mov.oper[1]^.ref^;
  5620. { Memory must be aligned }
  5621. if (CurrentRef.offset mod 4) <> 0 then
  5622. Exit;
  5623. Inc(CurrentRef.offset);
  5624. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5625. if MatchOperand(second_mov.oper[0]^, 0) and
  5626. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5627. GetNextInstruction(second_mov, hp1) and
  5628. (hp1.typ = ait_instruction) and
  5629. (taicpu(hp1).opcode = A_MOV) and
  5630. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5631. (taicpu(hp1).oper[0]^.val = 0) then
  5632. begin
  5633. Inc(CurrentRef.offset);
  5634. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5635. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5636. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5637. begin
  5638. case taicpu(hp1).opsize of
  5639. S_B:
  5640. if GetNextInstruction(hp1, hp2) and
  5641. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5642. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5643. (taicpu(hp2).oper[0]^.val = 0) then
  5644. begin
  5645. Inc(CurrentRef.offset);
  5646. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5647. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5648. (taicpu(hp2).opsize = S_B) then
  5649. begin
  5650. RemoveInstruction(hp1);
  5651. RemoveInstruction(hp2);
  5652. first_mov.opsize := S_L;
  5653. if first_mov.oper[0]^.typ = top_reg then
  5654. begin
  5655. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5656. { Reuse second_mov as a MOVZX instruction }
  5657. second_mov.opcode := A_MOVZX;
  5658. second_mov.opsize := S_BL;
  5659. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5660. second_mov.loadreg(1, FullReg);
  5661. first_mov.oper[0]^.reg := FullReg;
  5662. asml.Remove(second_mov);
  5663. asml.InsertBefore(second_mov, first_mov);
  5664. end
  5665. else
  5666. { It's a value }
  5667. begin
  5668. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5669. RemoveInstruction(second_mov);
  5670. end;
  5671. Result := True;
  5672. Exit;
  5673. end;
  5674. end;
  5675. S_W:
  5676. begin
  5677. RemoveInstruction(hp1);
  5678. first_mov.opsize := S_L;
  5679. if first_mov.oper[0]^.typ = top_reg then
  5680. begin
  5681. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5682. { Reuse second_mov as a MOVZX instruction }
  5683. second_mov.opcode := A_MOVZX;
  5684. second_mov.opsize := S_BL;
  5685. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5686. second_mov.loadreg(1, FullReg);
  5687. first_mov.oper[0]^.reg := FullReg;
  5688. asml.Remove(second_mov);
  5689. asml.InsertBefore(second_mov, first_mov);
  5690. end
  5691. else
  5692. { It's a value }
  5693. begin
  5694. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5695. RemoveInstruction(second_mov);
  5696. end;
  5697. Result := True;
  5698. Exit;
  5699. end;
  5700. else
  5701. ;
  5702. end;
  5703. end;
  5704. end;
  5705. end;
  5706. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5707. { returns true if a "continue" should be done after this optimization }
  5708. var
  5709. hp1, hp2: tai;
  5710. begin
  5711. Result := false;
  5712. if MatchOpType(taicpu(p),top_ref) and
  5713. GetNextInstruction(p, hp1) and
  5714. (hp1.typ = ait_instruction) and
  5715. (((taicpu(hp1).opcode = A_FLD) and
  5716. (taicpu(p).opcode = A_FSTP)) or
  5717. ((taicpu(p).opcode = A_FISTP) and
  5718. (taicpu(hp1).opcode = A_FILD))) and
  5719. MatchOpType(taicpu(hp1),top_ref) and
  5720. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5721. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5722. begin
  5723. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5724. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5725. GetNextInstruction(hp1, hp2) and
  5726. (hp2.typ = ait_instruction) and
  5727. IsExitCode(hp2) and
  5728. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5729. not(assigned(current_procinfo.procdef.funcretsym) and
  5730. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5731. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5732. begin
  5733. RemoveInstruction(hp1);
  5734. RemoveCurrentP(p, hp2);
  5735. RemoveLastDeallocForFuncRes(p);
  5736. Result := true;
  5737. end
  5738. else
  5739. { we can do this only in fast math mode as fstp is rounding ...
  5740. ... still disabled as it breaks the compiler and/or rtl }
  5741. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5742. { ... or if another fstp equal to the first one follows }
  5743. (GetNextInstruction(hp1,hp2) and
  5744. (hp2.typ = ait_instruction) and
  5745. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5746. (taicpu(p).opsize=taicpu(hp2).opsize))
  5747. ) and
  5748. { fst can't store an extended/comp value }
  5749. (taicpu(p).opsize <> S_FX) and
  5750. (taicpu(p).opsize <> S_IQ) then
  5751. begin
  5752. if (taicpu(p).opcode = A_FSTP) then
  5753. taicpu(p).opcode := A_FST
  5754. else
  5755. taicpu(p).opcode := A_FIST;
  5756. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5757. RemoveInstruction(hp1);
  5758. end;
  5759. end;
  5760. end;
  5761. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5762. var
  5763. hp1, hp2: tai;
  5764. begin
  5765. result:=false;
  5766. if MatchOpType(taicpu(p),top_reg) and
  5767. GetNextInstruction(p, hp1) and
  5768. (hp1.typ = Ait_Instruction) and
  5769. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5770. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5771. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5772. { change to
  5773. fld reg fxxx reg,st
  5774. fxxxp st, st1 (hp1)
  5775. Remark: non commutative operations must be reversed!
  5776. }
  5777. begin
  5778. case taicpu(hp1).opcode Of
  5779. A_FMULP,A_FADDP,
  5780. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5781. begin
  5782. case taicpu(hp1).opcode Of
  5783. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5784. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5785. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5786. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5787. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5788. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5789. else
  5790. internalerror(2019050534);
  5791. end;
  5792. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5793. taicpu(hp1).oper[1]^.reg := NR_ST;
  5794. RemoveCurrentP(p, hp1);
  5795. Result:=true;
  5796. exit;
  5797. end;
  5798. else
  5799. ;
  5800. end;
  5801. end
  5802. else
  5803. if MatchOpType(taicpu(p),top_ref) and
  5804. GetNextInstruction(p, hp2) and
  5805. (hp2.typ = Ait_Instruction) and
  5806. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5807. (taicpu(p).opsize in [S_FS, S_FL]) and
  5808. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5809. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5810. if GetLastInstruction(p, hp1) and
  5811. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5812. MatchOpType(taicpu(hp1),top_ref) and
  5813. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5814. if ((taicpu(hp2).opcode = A_FMULP) or
  5815. (taicpu(hp2).opcode = A_FADDP)) then
  5816. { change to
  5817. fld/fst mem1 (hp1) fld/fst mem1
  5818. fld mem1 (p) fadd/
  5819. faddp/ fmul st, st
  5820. fmulp st, st1 (hp2) }
  5821. begin
  5822. RemoveCurrentP(p, hp1);
  5823. if (taicpu(hp2).opcode = A_FADDP) then
  5824. taicpu(hp2).opcode := A_FADD
  5825. else
  5826. taicpu(hp2).opcode := A_FMUL;
  5827. taicpu(hp2).oper[1]^.reg := NR_ST;
  5828. end
  5829. else
  5830. { change to
  5831. fld/fst mem1 (hp1) fld/fst mem1
  5832. fld mem1 (p) fld st}
  5833. begin
  5834. taicpu(p).changeopsize(S_FL);
  5835. taicpu(p).loadreg(0,NR_ST);
  5836. end
  5837. else
  5838. begin
  5839. case taicpu(hp2).opcode Of
  5840. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5841. { change to
  5842. fld/fst mem1 (hp1) fld/fst mem1
  5843. fld mem2 (p) fxxx mem2
  5844. fxxxp st, st1 (hp2) }
  5845. begin
  5846. case taicpu(hp2).opcode Of
  5847. A_FADDP: taicpu(p).opcode := A_FADD;
  5848. A_FMULP: taicpu(p).opcode := A_FMUL;
  5849. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5850. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5851. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5852. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5853. else
  5854. internalerror(2019050533);
  5855. end;
  5856. RemoveInstruction(hp2);
  5857. end
  5858. else
  5859. ;
  5860. end
  5861. end
  5862. end;
  5863. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5864. begin
  5865. Result := condition_in(cond1, cond2) or
  5866. { Not strictly subsets due to the actual flags checked, but because we're
  5867. comparing integers, E is a subset of AE and GE and their aliases }
  5868. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5869. end;
  5870. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5871. var
  5872. v: TCGInt;
  5873. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5874. FirstMatch: Boolean;
  5875. NewReg: TRegister;
  5876. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5877. begin
  5878. Result:=false;
  5879. { All these optimisations need a next instruction }
  5880. if not GetNextInstruction(p, hp1) then
  5881. Exit;
  5882. { Search for:
  5883. cmp ###,###
  5884. j(c1) @lbl1
  5885. ...
  5886. @lbl:
  5887. cmp ###.### (same comparison as above)
  5888. j(c2) @lbl2
  5889. If c1 is a subset of c2, change to:
  5890. cmp ###,###
  5891. j(c2) @lbl2
  5892. (@lbl1 may become a dead label as a result)
  5893. }
  5894. { Also handle cases where there are multiple jumps in a row }
  5895. p_jump := hp1;
  5896. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5897. begin
  5898. if IsJumpToLabel(taicpu(p_jump)) then
  5899. begin
  5900. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5901. p_label := nil;
  5902. if Assigned(JumpLabel) then
  5903. p_label := getlabelwithsym(JumpLabel);
  5904. if Assigned(p_label) and
  5905. GetNextInstruction(p_label, p_dist) and
  5906. MatchInstruction(p_dist, A_CMP, []) and
  5907. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5908. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5909. GetNextInstruction(p_dist, hp1_dist) and
  5910. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5911. begin
  5912. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5913. if JumpLabel = JumpLabel_dist then
  5914. { This is an infinite loop }
  5915. Exit;
  5916. { Best optimisation when the first condition is a subset (or equal) of the second }
  5917. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5918. begin
  5919. { Any registers used here will already be allocated }
  5920. if Assigned(JumpLabel_dist) then
  5921. JumpLabel_dist.IncRefs;
  5922. if Assigned(JumpLabel) then
  5923. JumpLabel.DecRefs;
  5924. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5925. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5926. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5927. Result := True;
  5928. { Don't exit yet. Since p and p_jump haven't actually been
  5929. removed, we can check for more on this iteration }
  5930. end
  5931. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5932. GetNextInstruction(hp1_dist, hp1_label) and
  5933. SkipAligns(hp1_label, hp1_label) and
  5934. (hp1_label.typ = ait_label) then
  5935. begin
  5936. JumpLabel_far := tai_label(hp1_label).labsym;
  5937. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5938. { This is an infinite loop }
  5939. Exit;
  5940. if Assigned(JumpLabel_far) then
  5941. begin
  5942. { In this situation, if the first jump branches, the second one will never,
  5943. branch so change the destination label to after the second jump }
  5944. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5945. if Assigned(JumpLabel) then
  5946. JumpLabel.DecRefs;
  5947. JumpLabel_far.IncRefs;
  5948. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5949. Result := True;
  5950. { Don't exit yet. Since p and p_jump haven't actually been
  5951. removed, we can check for more on this iteration }
  5952. Continue;
  5953. end;
  5954. end;
  5955. end;
  5956. end;
  5957. { Search for:
  5958. cmp ###,###
  5959. j(c1) @lbl1
  5960. cmp ###,### (same as first)
  5961. Remove second cmp
  5962. }
  5963. if GetNextInstruction(p_jump, hp2) and
  5964. (
  5965. (
  5966. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5967. (
  5968. (
  5969. MatchOpType(taicpu(p), top_const, top_reg) and
  5970. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5971. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5972. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5973. ) or (
  5974. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5975. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5976. )
  5977. )
  5978. ) or (
  5979. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5980. MatchOperand(taicpu(p).oper[0]^, 0) and
  5981. (taicpu(p).oper[1]^.typ = top_reg) and
  5982. MatchInstruction(hp2, A_TEST, []) and
  5983. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5984. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5985. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5986. )
  5987. ) then
  5988. begin
  5989. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5990. RemoveInstruction(hp2);
  5991. Result := True;
  5992. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5993. end;
  5994. GetNextInstruction(p_jump, p_jump);
  5995. end;
  5996. {
  5997. Try to optimise the following:
  5998. cmp $x,### ($x and $y can be registers or constants)
  5999. je @lbl1 (only reference)
  6000. cmp $y,### (### are identical)
  6001. @Lbl:
  6002. sete %reg1
  6003. Change to:
  6004. cmp $x,###
  6005. sete %reg2 (allocate new %reg2)
  6006. cmp $y,###
  6007. sete %reg1
  6008. orb %reg2,%reg1
  6009. (dealloc %reg2)
  6010. This adds an instruction (so don't perform under -Os), but it removes
  6011. a conditional branch.
  6012. }
  6013. if not (cs_opt_size in current_settings.optimizerswitches) and
  6014. (
  6015. (hp1 = p_jump) or
  6016. GetNextInstruction(p, hp1)
  6017. ) and
  6018. MatchInstruction(hp1, A_Jcc, []) and
  6019. IsJumpToLabel(taicpu(hp1)) and
  6020. (taicpu(hp1).condition in [C_E, C_Z]) and
  6021. GetNextInstruction(hp1, hp2) and
  6022. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6023. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6024. { The first operand of CMP instructions can only be a register or
  6025. immediate anyway, so no need to check }
  6026. GetNextInstruction(hp2, p_label) and
  6027. (p_label.typ = ait_label) and
  6028. (tai_label(p_label).labsym.getrefs = 1) and
  6029. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6030. GetNextInstruction(p_label, p_dist) and
  6031. MatchInstruction(p_dist, A_SETcc, []) and
  6032. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6033. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6034. begin
  6035. TransferUsedRegs(TmpUsedRegs);
  6036. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6037. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6038. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6039. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6040. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6041. { Get the instruction after the SETcc instruction so we can
  6042. allocate a new register over the entire range }
  6043. GetNextInstruction(p_dist, hp1_dist) then
  6044. begin
  6045. { Register can appear in p if it's not used afterwards, so only
  6046. allocate between hp1 and hp1_dist }
  6047. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6048. if NewReg <> NR_NO then
  6049. begin
  6050. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6051. { Change the jump instruction into a SETcc instruction }
  6052. taicpu(hp1).opcode := A_SETcc;
  6053. taicpu(hp1).opsize := S_B;
  6054. taicpu(hp1).loadreg(0, NewReg);
  6055. { This is now a dead label }
  6056. tai_label(p_label).labsym.decrefs;
  6057. { Prefer adding before the next instruction so the FLAGS
  6058. register is deallicated first }
  6059. AsmL.InsertBefore(
  6060. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6061. hp1_dist
  6062. );
  6063. Result := True;
  6064. { Don't exit yet, as p wasn't changed and hp1, while
  6065. modified, is still intact and might be optimised by the
  6066. SETcc optimisation below }
  6067. end;
  6068. end;
  6069. end;
  6070. if taicpu(p).oper[0]^.typ = top_const then
  6071. begin
  6072. if (taicpu(p).oper[0]^.val = 0) and
  6073. (taicpu(p).oper[1]^.typ = top_reg) and
  6074. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6075. begin
  6076. hp2 := p;
  6077. FirstMatch := True;
  6078. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6079. anything meaningful once it's converted to "test %reg,%reg";
  6080. additionally, some jumps will always (or never) branch, so
  6081. evaluate every jump immediately following the
  6082. comparison, optimising the conditions if possible.
  6083. Similarly with SETcc... those that are always set to 0 or 1
  6084. are changed to MOV instructions }
  6085. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6086. (
  6087. GetNextInstruction(hp2, hp1) and
  6088. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6089. ) do
  6090. begin
  6091. FirstMatch := False;
  6092. case taicpu(hp1).condition of
  6093. C_B, C_C, C_NAE, C_O:
  6094. { For B/NAE:
  6095. Will never branch since an unsigned integer can never be below zero
  6096. For C/O:
  6097. Result cannot overflow because 0 is being subtracted
  6098. }
  6099. begin
  6100. if taicpu(hp1).opcode = A_Jcc then
  6101. begin
  6102. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6103. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6104. RemoveInstruction(hp1);
  6105. { Since hp1 was deleted, hp2 must not be updated }
  6106. Continue;
  6107. end
  6108. else
  6109. begin
  6110. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6111. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6112. taicpu(hp1).opcode := A_MOV;
  6113. taicpu(hp1).ops := 2;
  6114. taicpu(hp1).condition := C_None;
  6115. taicpu(hp1).opsize := S_B;
  6116. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6117. taicpu(hp1).loadconst(0, 0);
  6118. end;
  6119. end;
  6120. C_BE, C_NA:
  6121. begin
  6122. { Will only branch if equal to zero }
  6123. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6124. taicpu(hp1).condition := C_E;
  6125. end;
  6126. C_A, C_NBE:
  6127. begin
  6128. { Will only branch if not equal to zero }
  6129. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6130. taicpu(hp1).condition := C_NE;
  6131. end;
  6132. C_AE, C_NB, C_NC, C_NO:
  6133. begin
  6134. { Will always branch }
  6135. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6136. if taicpu(hp1).opcode = A_Jcc then
  6137. begin
  6138. MakeUnconditional(taicpu(hp1));
  6139. { Any jumps/set that follow will now be dead code }
  6140. RemoveDeadCodeAfterJump(taicpu(hp1));
  6141. Break;
  6142. end
  6143. else
  6144. begin
  6145. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6146. taicpu(hp1).opcode := A_MOV;
  6147. taicpu(hp1).ops := 2;
  6148. taicpu(hp1).condition := C_None;
  6149. taicpu(hp1).opsize := S_B;
  6150. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6151. taicpu(hp1).loadconst(0, 1);
  6152. end;
  6153. end;
  6154. C_None:
  6155. InternalError(2020012201);
  6156. C_P, C_PE, C_NP, C_PO:
  6157. { We can't handle parity checks and they should never be generated
  6158. after a general-purpose CMP (it's used in some floating-point
  6159. comparisons that don't use CMP) }
  6160. InternalError(2020012202);
  6161. else
  6162. { Zero/Equality, Sign, their complements and all of the
  6163. signed comparisons do not need to be converted };
  6164. end;
  6165. hp2 := hp1;
  6166. end;
  6167. { Convert the instruction to a TEST }
  6168. taicpu(p).opcode := A_TEST;
  6169. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6170. Result := True;
  6171. Exit;
  6172. end
  6173. else if (taicpu(p).oper[0]^.val = 1) and
  6174. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6175. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6176. begin
  6177. { Convert; To:
  6178. cmp $1,r/m cmp $0,r/m
  6179. jl @lbl jle @lbl
  6180. }
  6181. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6182. taicpu(p).oper[0]^.val := 0;
  6183. taicpu(hp1).condition := C_LE;
  6184. { If the instruction is now "cmp $0,%reg", convert it to a
  6185. TEST (and effectively do the work of the "cmp $0,%reg" in
  6186. the block above)
  6187. If it's a reference, we can get away with not setting
  6188. Result to True because he haven't evaluated the jump
  6189. in this pass yet.
  6190. }
  6191. if (taicpu(p).oper[1]^.typ = top_reg) then
  6192. begin
  6193. taicpu(p).opcode := A_TEST;
  6194. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6195. Result := True;
  6196. end;
  6197. Exit;
  6198. end
  6199. else if (taicpu(p).oper[1]^.typ = top_reg)
  6200. {$ifdef x86_64}
  6201. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6202. {$endif x86_64}
  6203. then
  6204. begin
  6205. { cmp register,$8000 neg register
  6206. je target --> jo target
  6207. .... only if register is deallocated before jump.}
  6208. case Taicpu(p).opsize of
  6209. S_B: v:=$80;
  6210. S_W: v:=$8000;
  6211. S_L: v:=qword($80000000);
  6212. else
  6213. internalerror(2013112905);
  6214. end;
  6215. if (taicpu(p).oper[0]^.val=v) and
  6216. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6217. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6218. begin
  6219. TransferUsedRegs(TmpUsedRegs);
  6220. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6221. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6222. begin
  6223. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6224. Taicpu(p).opcode:=A_NEG;
  6225. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6226. Taicpu(p).clearop(1);
  6227. Taicpu(p).ops:=1;
  6228. if Taicpu(hp1).condition=C_E then
  6229. Taicpu(hp1).condition:=C_O
  6230. else
  6231. Taicpu(hp1).condition:=C_NO;
  6232. Result:=true;
  6233. exit;
  6234. end;
  6235. end;
  6236. end;
  6237. end;
  6238. if TrySwapMovCmp(p, hp1) then
  6239. begin
  6240. Result := True;
  6241. Exit;
  6242. end;
  6243. end;
  6244. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6245. var
  6246. hp1: tai;
  6247. begin
  6248. {
  6249. remove the second (v)pxor from
  6250. pxor reg,reg
  6251. ...
  6252. pxor reg,reg
  6253. }
  6254. Result:=false;
  6255. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6256. MatchOpType(taicpu(p),top_reg,top_reg) and
  6257. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6258. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6259. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6260. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6261. begin
  6262. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6263. RemoveInstruction(hp1);
  6264. Result:=true;
  6265. Exit;
  6266. end
  6267. {
  6268. replace
  6269. pxor reg1,reg1
  6270. movapd/s reg1,reg2
  6271. dealloc reg1
  6272. by
  6273. pxor reg2,reg2
  6274. }
  6275. else if GetNextInstruction(p,hp1) and
  6276. { we mix single and double opperations here because we assume that the compiler
  6277. generates vmovapd only after double operations and vmovaps only after single operations }
  6278. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6279. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6280. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6281. (taicpu(p).oper[0]^.typ=top_reg) then
  6282. begin
  6283. TransferUsedRegs(TmpUsedRegs);
  6284. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6285. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6286. begin
  6287. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6288. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6289. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6290. RemoveInstruction(hp1);
  6291. result:=true;
  6292. end;
  6293. end;
  6294. end;
  6295. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6296. var
  6297. hp1: tai;
  6298. begin
  6299. {
  6300. remove the second (v)pxor from
  6301. (v)pxor reg,reg
  6302. ...
  6303. (v)pxor reg,reg
  6304. }
  6305. Result:=false;
  6306. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6307. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6308. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6309. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6310. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6311. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6312. begin
  6313. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6314. RemoveInstruction(hp1);
  6315. Result:=true;
  6316. Exit;
  6317. end
  6318. else
  6319. Result:=OptPass1VOP(p);
  6320. end;
  6321. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6322. var
  6323. hp1 : tai;
  6324. begin
  6325. result:=false;
  6326. { replace
  6327. IMul const,%mreg1,%mreg2
  6328. Mov %reg2,%mreg3
  6329. dealloc %mreg3
  6330. by
  6331. Imul const,%mreg1,%mreg23
  6332. }
  6333. if (taicpu(p).ops=3) and
  6334. GetNextInstruction(p,hp1) and
  6335. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6336. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6337. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6338. begin
  6339. TransferUsedRegs(TmpUsedRegs);
  6340. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6341. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6342. begin
  6343. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6344. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6345. RemoveInstruction(hp1);
  6346. result:=true;
  6347. end;
  6348. end;
  6349. end;
  6350. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6351. var
  6352. hp1 : tai;
  6353. begin
  6354. result:=false;
  6355. { replace
  6356. IMul %reg0,%reg1,%reg2
  6357. Mov %reg2,%reg3
  6358. dealloc %reg2
  6359. by
  6360. Imul %reg0,%reg1,%reg3
  6361. }
  6362. if GetNextInstruction(p,hp1) and
  6363. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6364. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6365. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6366. begin
  6367. TransferUsedRegs(TmpUsedRegs);
  6368. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6369. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6370. begin
  6371. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6372. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6373. RemoveInstruction(hp1);
  6374. result:=true;
  6375. end;
  6376. end;
  6377. end;
  6378. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6379. var
  6380. hp1: tai;
  6381. begin
  6382. Result:=false;
  6383. { get rid of
  6384. (v)cvtss2sd reg0,<reg1,>reg2
  6385. (v)cvtss2sd reg2,<reg2,>reg0
  6386. }
  6387. if GetNextInstruction(p,hp1) and
  6388. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6389. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6390. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6391. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6392. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6393. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6394. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6395. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6396. )
  6397. ) then
  6398. begin
  6399. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6400. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6401. begin
  6402. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6403. RemoveCurrentP(p);
  6404. RemoveInstruction(hp1);
  6405. end
  6406. else
  6407. begin
  6408. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6409. if taicpu(hp1).opcode=A_CVTSD2SS then
  6410. begin
  6411. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6412. taicpu(p).opcode:=A_MOVAPS;
  6413. end
  6414. else
  6415. begin
  6416. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6417. taicpu(p).opcode:=A_VMOVAPS;
  6418. end;
  6419. taicpu(p).ops:=2;
  6420. RemoveInstruction(hp1);
  6421. end;
  6422. Result:=true;
  6423. Exit;
  6424. end;
  6425. end;
  6426. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6427. var
  6428. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6429. ThisReg: TRegister;
  6430. begin
  6431. Result := False;
  6432. if not GetNextInstruction(p,hp1) then
  6433. Exit;
  6434. {
  6435. convert
  6436. j<c> .L1
  6437. mov 1,reg
  6438. jmp .L2
  6439. .L1
  6440. mov 0,reg
  6441. .L2
  6442. into
  6443. mov 0,reg
  6444. set<not(c)> reg
  6445. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6446. would destroy the flag contents
  6447. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6448. executed at the same time as a previous comparison.
  6449. set<not(c)> reg
  6450. movzx reg, reg
  6451. }
  6452. if MatchInstruction(hp1,A_MOV,[]) and
  6453. (taicpu(hp1).oper[0]^.typ = top_const) and
  6454. (
  6455. (
  6456. (taicpu(hp1).oper[1]^.typ = top_reg)
  6457. {$ifdef i386}
  6458. { Under i386, ESI, EDI, EBP and ESP
  6459. don't have an 8-bit representation }
  6460. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6461. {$endif i386}
  6462. ) or (
  6463. {$ifdef i386}
  6464. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6465. {$endif i386}
  6466. (taicpu(hp1).opsize = S_B)
  6467. )
  6468. ) and
  6469. GetNextInstruction(hp1,hp2) and
  6470. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6471. GetNextInstruction(hp2,hp3) and
  6472. SkipAligns(hp3, hp3) and
  6473. (hp3.typ=ait_label) and
  6474. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6475. GetNextInstruction(hp3,hp4) and
  6476. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6477. (taicpu(hp4).oper[0]^.typ = top_const) and
  6478. (
  6479. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6480. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6481. ) and
  6482. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6483. GetNextInstruction(hp4,hp5) and
  6484. SkipAligns(hp5, hp5) and
  6485. (hp5.typ=ait_label) and
  6486. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6487. begin
  6488. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6489. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6490. tai_label(hp3).labsym.DecRefs;
  6491. { If this isn't the only reference to the middle label, we can
  6492. still make a saving - only that the first jump and everything
  6493. that follows will remain. }
  6494. if (tai_label(hp3).labsym.getrefs = 0) then
  6495. begin
  6496. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6497. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6498. else
  6499. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6500. { remove jump, first label and second MOV (also catching any aligns) }
  6501. repeat
  6502. if not GetNextInstruction(hp2, hp3) then
  6503. InternalError(2021040810);
  6504. RemoveInstruction(hp2);
  6505. hp2 := hp3;
  6506. until hp2 = hp5;
  6507. { Don't decrement reference count before the removal loop
  6508. above, otherwise GetNextInstruction won't stop on the
  6509. the label }
  6510. tai_label(hp5).labsym.DecRefs;
  6511. end
  6512. else
  6513. begin
  6514. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6515. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6516. else
  6517. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6518. end;
  6519. taicpu(p).opcode:=A_SETcc;
  6520. taicpu(p).opsize:=S_B;
  6521. taicpu(p).is_jmp:=False;
  6522. if taicpu(hp1).opsize=S_B then
  6523. begin
  6524. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6525. if taicpu(hp1).oper[1]^.typ = top_reg then
  6526. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6527. RemoveInstruction(hp1);
  6528. end
  6529. else
  6530. begin
  6531. { Will be a register because the size can't be S_B otherwise }
  6532. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6533. taicpu(p).loadreg(0, ThisReg);
  6534. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6535. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6536. begin
  6537. case taicpu(hp1).opsize of
  6538. S_W:
  6539. taicpu(hp1).opsize := S_BW;
  6540. S_L:
  6541. taicpu(hp1).opsize := S_BL;
  6542. {$ifdef x86_64}
  6543. S_Q:
  6544. begin
  6545. taicpu(hp1).opsize := S_BL;
  6546. { Change the destination register to 32-bit }
  6547. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6548. end;
  6549. {$endif x86_64}
  6550. else
  6551. InternalError(2021040820);
  6552. end;
  6553. taicpu(hp1).opcode := A_MOVZX;
  6554. taicpu(hp1).loadreg(0, ThisReg);
  6555. end
  6556. else
  6557. begin
  6558. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6559. { hp1 is already a MOV instruction with the correct register }
  6560. taicpu(hp1).loadconst(0, 0);
  6561. { Inserting it right before p will guarantee that the flags are also tracked }
  6562. asml.Remove(hp1);
  6563. asml.InsertBefore(hp1, p);
  6564. end;
  6565. end;
  6566. Result:=true;
  6567. exit;
  6568. end
  6569. else if (hp1.typ = ait_label) then
  6570. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6571. end;
  6572. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6573. var
  6574. hp1, hp2, hp3: tai;
  6575. SourceRef, TargetRef: TReference;
  6576. CurrentReg: TRegister;
  6577. begin
  6578. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6579. if not UseAVX then
  6580. InternalError(2021100501);
  6581. Result := False;
  6582. { Look for the following to simplify:
  6583. vmovdqa/u x(mem1), %xmmreg
  6584. vmovdqa/u %xmmreg, y(mem2)
  6585. vmovdqa/u x+16(mem1), %xmmreg
  6586. vmovdqa/u %xmmreg, y+16(mem2)
  6587. Change to:
  6588. vmovdqa/u x(mem1), %ymmreg
  6589. vmovdqa/u %ymmreg, y(mem2)
  6590. vpxor %ymmreg, %ymmreg, %ymmreg
  6591. ( The VPXOR instruction is to zero the upper half, thus removing the
  6592. need to call the potentially expensive VZEROUPPER instruction. Other
  6593. peephole optimisations can remove VPXOR if it's unnecessary )
  6594. }
  6595. TransferUsedRegs(TmpUsedRegs);
  6596. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6597. { NOTE: In the optimisations below, if the references dictate that an
  6598. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6599. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6600. if (taicpu(p).opsize = S_XMM) and
  6601. MatchOpType(taicpu(p), top_ref, top_reg) and
  6602. GetNextInstruction(p, hp1) and
  6603. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6604. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6605. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6606. begin
  6607. SourceRef := taicpu(p).oper[0]^.ref^;
  6608. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6609. if GetNextInstruction(hp1, hp2) and
  6610. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6611. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6612. begin
  6613. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6614. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6615. Inc(SourceRef.offset, 16);
  6616. { Reuse the register in the first block move }
  6617. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6618. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6619. begin
  6620. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6621. Inc(TargetRef.offset, 16);
  6622. if GetNextInstruction(hp2, hp3) and
  6623. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6624. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6625. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6626. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6627. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6628. begin
  6629. { Update the register tracking to the new size }
  6630. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6631. { Remember that the offsets are 16 ahead }
  6632. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6633. if not (
  6634. ((SourceRef.offset mod 32) = 16) and
  6635. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6636. ) then
  6637. taicpu(p).opcode := A_VMOVDQU;
  6638. taicpu(p).opsize := S_YMM;
  6639. taicpu(p).oper[1]^.reg := CurrentReg;
  6640. if not (
  6641. ((TargetRef.offset mod 32) = 16) and
  6642. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6643. ) then
  6644. taicpu(hp1).opcode := A_VMOVDQU;
  6645. taicpu(hp1).opsize := S_YMM;
  6646. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6647. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6648. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6649. if (pi_uses_ymm in current_procinfo.flags) then
  6650. RemoveInstruction(hp2)
  6651. else
  6652. begin
  6653. taicpu(hp2).opcode := A_VPXOR;
  6654. taicpu(hp2).opsize := S_YMM;
  6655. taicpu(hp2).loadreg(0, CurrentReg);
  6656. taicpu(hp2).loadreg(1, CurrentReg);
  6657. taicpu(hp2).loadreg(2, CurrentReg);
  6658. taicpu(hp2).ops := 3;
  6659. end;
  6660. RemoveInstruction(hp3);
  6661. Result := True;
  6662. Exit;
  6663. end;
  6664. end
  6665. else
  6666. begin
  6667. { See if the next references are 16 less rather than 16 greater }
  6668. Dec(SourceRef.offset, 32); { -16 the other way }
  6669. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6670. begin
  6671. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6672. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6673. if GetNextInstruction(hp2, hp3) and
  6674. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6675. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6676. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6677. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6678. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6679. begin
  6680. { Update the register tracking to the new size }
  6681. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6682. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6683. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6684. if not(
  6685. ((SourceRef.offset mod 32) = 0) and
  6686. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6687. ) then
  6688. taicpu(hp2).opcode := A_VMOVDQU;
  6689. taicpu(hp2).opsize := S_YMM;
  6690. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6691. if not (
  6692. ((TargetRef.offset mod 32) = 0) and
  6693. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6694. ) then
  6695. taicpu(hp3).opcode := A_VMOVDQU;
  6696. taicpu(hp3).opsize := S_YMM;
  6697. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6698. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6699. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6700. if (pi_uses_ymm in current_procinfo.flags) then
  6701. RemoveInstruction(hp1)
  6702. else
  6703. begin
  6704. taicpu(hp1).opcode := A_VPXOR;
  6705. taicpu(hp1).opsize := S_YMM;
  6706. taicpu(hp1).loadreg(0, CurrentReg);
  6707. taicpu(hp1).loadreg(1, CurrentReg);
  6708. taicpu(hp1).loadreg(2, CurrentReg);
  6709. taicpu(hp1).ops := 3;
  6710. Asml.Remove(hp1);
  6711. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6712. end;
  6713. RemoveCurrentP(p, hp2);
  6714. Result := True;
  6715. Exit;
  6716. end;
  6717. end;
  6718. end;
  6719. end;
  6720. end;
  6721. end;
  6722. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6723. var
  6724. hp2, hp3, first_assignment: tai;
  6725. IncCount, OperIdx: Integer;
  6726. OrigLabel: TAsmLabel;
  6727. begin
  6728. Count := 0;
  6729. Result := False;
  6730. first_assignment := nil;
  6731. if (LoopCount >= 20) then
  6732. begin
  6733. { Guard against infinite loops }
  6734. Exit;
  6735. end;
  6736. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6737. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6738. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6739. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6740. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6741. Exit;
  6742. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6743. {
  6744. change
  6745. jmp .L1
  6746. ...
  6747. .L1:
  6748. mov ##, ## ( multiple movs possible )
  6749. jmp/ret
  6750. into
  6751. mov ##, ##
  6752. jmp/ret
  6753. }
  6754. if not Assigned(hp1) then
  6755. begin
  6756. hp1 := GetLabelWithSym(OrigLabel);
  6757. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6758. Exit;
  6759. end;
  6760. hp2 := hp1;
  6761. while Assigned(hp2) do
  6762. begin
  6763. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6764. SkipLabels(hp2,hp2);
  6765. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6766. Break;
  6767. case taicpu(hp2).opcode of
  6768. A_MOVSS:
  6769. begin
  6770. if taicpu(hp2).ops = 0 then
  6771. { Wrong MOVSS }
  6772. Break;
  6773. Inc(Count);
  6774. if Count >= 5 then
  6775. { Too many to be worthwhile }
  6776. Break;
  6777. GetNextInstruction(hp2, hp2);
  6778. Continue;
  6779. end;
  6780. A_MOV,
  6781. A_MOVD,
  6782. A_MOVQ,
  6783. A_MOVSX,
  6784. {$ifdef x86_64}
  6785. A_MOVSXD,
  6786. {$endif x86_64}
  6787. A_MOVZX,
  6788. A_MOVAPS,
  6789. A_MOVUPS,
  6790. A_MOVSD,
  6791. A_MOVAPD,
  6792. A_MOVUPD,
  6793. A_MOVDQA,
  6794. A_MOVDQU,
  6795. A_VMOVSS,
  6796. A_VMOVAPS,
  6797. A_VMOVUPS,
  6798. A_VMOVSD,
  6799. A_VMOVAPD,
  6800. A_VMOVUPD,
  6801. A_VMOVDQA,
  6802. A_VMOVDQU:
  6803. begin
  6804. Inc(Count);
  6805. if Count >= 5 then
  6806. { Too many to be worthwhile }
  6807. Break;
  6808. GetNextInstruction(hp2, hp2);
  6809. Continue;
  6810. end;
  6811. A_JMP:
  6812. begin
  6813. { Guard against infinite loops }
  6814. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6815. Exit;
  6816. { Analyse this jump first in case it also duplicates assignments }
  6817. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6818. begin
  6819. { Something did change! }
  6820. Result := True;
  6821. Inc(Count, IncCount);
  6822. if Count >= 5 then
  6823. begin
  6824. { Too many to be worthwhile }
  6825. Exit;
  6826. end;
  6827. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6828. Break;
  6829. end;
  6830. Result := True;
  6831. Break;
  6832. end;
  6833. A_RET:
  6834. begin
  6835. Result := True;
  6836. Break;
  6837. end;
  6838. else
  6839. Break;
  6840. end;
  6841. end;
  6842. if Result then
  6843. begin
  6844. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6845. if Count = 0 then
  6846. begin
  6847. Result := False;
  6848. Exit;
  6849. end;
  6850. hp3 := p;
  6851. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6852. while True do
  6853. begin
  6854. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6855. SkipLabels(hp1,hp1);
  6856. if (hp1.typ <> ait_instruction) then
  6857. InternalError(2021040720);
  6858. case taicpu(hp1).opcode of
  6859. A_JMP:
  6860. begin
  6861. { Change the original jump to the new destination }
  6862. OrigLabel.decrefs;
  6863. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6864. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6865. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6866. if not Assigned(first_assignment) then
  6867. InternalError(2021040810)
  6868. else
  6869. p := first_assignment;
  6870. Exit;
  6871. end;
  6872. A_RET:
  6873. begin
  6874. { Now change the jump into a RET instruction }
  6875. ConvertJumpToRET(p, hp1);
  6876. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6877. if not Assigned(first_assignment) then
  6878. InternalError(2021040811)
  6879. else
  6880. p := first_assignment;
  6881. Exit;
  6882. end;
  6883. else
  6884. begin
  6885. { Duplicate the MOV instruction }
  6886. hp3:=tai(hp1.getcopy);
  6887. if first_assignment = nil then
  6888. first_assignment := hp3;
  6889. asml.InsertBefore(hp3, p);
  6890. { Make sure the compiler knows about any final registers written here }
  6891. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6892. with taicpu(hp3).oper[OperIdx]^ do
  6893. begin
  6894. case typ of
  6895. top_ref:
  6896. begin
  6897. if (ref^.base <> NR_NO) and
  6898. (getsupreg(ref^.base) <> RS_ESP) and
  6899. (getsupreg(ref^.base) <> RS_EBP)
  6900. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6901. then
  6902. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6903. if (ref^.index <> NR_NO) and
  6904. (getsupreg(ref^.index) <> RS_ESP) and
  6905. (getsupreg(ref^.index) <> RS_EBP)
  6906. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6907. (ref^.index <> ref^.base) then
  6908. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6909. end;
  6910. top_reg:
  6911. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6912. else
  6913. ;
  6914. end;
  6915. end;
  6916. end;
  6917. end;
  6918. if not GetNextInstruction(hp1, hp1) then
  6919. { Should have dropped out earlier }
  6920. InternalError(2021040710);
  6921. end;
  6922. end;
  6923. end;
  6924. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6925. var
  6926. hp2: tai;
  6927. X: Integer;
  6928. const
  6929. WriteOp: array[0..3] of set of TInsChange = (
  6930. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6931. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6932. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6933. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6934. RegWriteFlags: array[0..7] of set of TInsChange = (
  6935. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6936. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6937. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6938. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6939. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6940. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6941. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6942. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6943. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6944. begin
  6945. { If we have something like:
  6946. cmp ###,%reg1
  6947. mov 0,%reg2
  6948. And no modified registers are shared, move the instruction to before
  6949. the comparison as this means it can be optimised without worrying
  6950. about the FLAGS register. (CMP/MOV is generated by
  6951. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6952. As long as the second instruction doesn't use the flags or one of the
  6953. registers used by CMP or TEST (also check any references that use the
  6954. registers), then it can be moved prior to the comparison.
  6955. }
  6956. Result := False;
  6957. if (hp1.typ <> ait_instruction) or
  6958. taicpu(hp1).is_jmp or
  6959. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6960. Exit;
  6961. { NOP is a pipeline fence, likely marking the beginning of the function
  6962. epilogue, so drop out. Similarly, drop out if POP or RET are
  6963. encountered }
  6964. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6965. Exit;
  6966. if (taicpu(hp1).opcode = A_MOVSS) and
  6967. (taicpu(hp1).ops = 0) then
  6968. { Wrong MOVSS }
  6969. Exit;
  6970. { Check for writes to specific registers first }
  6971. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6972. for X := 0 to 7 do
  6973. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6974. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6975. Exit;
  6976. for X := 0 to taicpu(hp1).ops - 1 do
  6977. begin
  6978. { Check to see if this operand writes to something }
  6979. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6980. { And matches something in the CMP/TEST instruction }
  6981. (
  6982. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6983. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6984. (
  6985. { If it's a register, make sure the register written to doesn't
  6986. appear in the cmp instruction as part of a reference }
  6987. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6988. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6989. )
  6990. ) then
  6991. Exit;
  6992. end;
  6993. { The instruction can be safely moved }
  6994. asml.Remove(hp1);
  6995. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6996. if not GetLastInstruction(p, hp2) then
  6997. asml.InsertBefore(hp1, p)
  6998. else
  6999. asml.InsertAfter(hp1, hp2);
  7000. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7001. for X := 0 to taicpu(hp1).ops - 1 do
  7002. case taicpu(hp1).oper[X]^.typ of
  7003. top_reg:
  7004. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7005. top_ref:
  7006. begin
  7007. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7008. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7009. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7010. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7011. end;
  7012. else
  7013. ;
  7014. end;
  7015. if taicpu(hp1).opcode = A_LEA then
  7016. { The flags will be overwritten by the CMP/TEST instruction }
  7017. ConvertLEA(taicpu(hp1));
  7018. Result := True;
  7019. end;
  7020. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7021. function IsXCHGAcceptable: Boolean; inline;
  7022. begin
  7023. { Always accept if optimising for size }
  7024. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7025. (
  7026. {$ifdef x86_64}
  7027. { XCHG takes 3 cycles on AMD Athlon64 }
  7028. (current_settings.optimizecputype >= cpu_core_i)
  7029. {$else x86_64}
  7030. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7031. than 3, so it becomes a saving compared to three MOVs with two of
  7032. them able to execute simultaneously. [Kit] }
  7033. (current_settings.optimizecputype >= cpu_PentiumM)
  7034. {$endif x86_64}
  7035. );
  7036. end;
  7037. var
  7038. NewRef: TReference;
  7039. hp1, hp2, hp3, hp4: Tai;
  7040. {$ifndef x86_64}
  7041. OperIdx: Integer;
  7042. {$endif x86_64}
  7043. NewInstr : Taicpu;
  7044. NewAligh : Tai_align;
  7045. DestLabel: TAsmLabel;
  7046. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7047. var
  7048. NextInstr: tai;
  7049. begin
  7050. Result := False;
  7051. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7052. if not GetNextInstruction(InputInstr, NextInstr) or
  7053. (
  7054. { The FLAGS register isn't always tracked properly, so do not
  7055. perform this optimisation if a conditional statement follows }
  7056. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7057. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7058. ) then
  7059. begin
  7060. reference_reset(NewRef, 1, []);
  7061. NewRef.base := taicpu(p).oper[0]^.reg;
  7062. NewRef.scalefactor := 1;
  7063. if taicpu(InputInstr).opcode = A_ADD then
  7064. begin
  7065. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7066. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7067. end
  7068. else
  7069. begin
  7070. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7071. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7072. end;
  7073. taicpu(p).opcode := A_LEA;
  7074. taicpu(p).loadref(0, NewRef);
  7075. RemoveInstruction(InputInstr);
  7076. Result := True;
  7077. end;
  7078. end;
  7079. begin
  7080. Result:=false;
  7081. { This optimisation adds an instruction, so only do it for speed }
  7082. if not (cs_opt_size in current_settings.optimizerswitches) and
  7083. MatchOpType(taicpu(p), top_const, top_reg) and
  7084. (taicpu(p).oper[0]^.val = 0) then
  7085. begin
  7086. { To avoid compiler warning }
  7087. DestLabel := nil;
  7088. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7089. InternalError(2021040750);
  7090. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7091. Exit;
  7092. case hp1.typ of
  7093. ait_label:
  7094. begin
  7095. { Change:
  7096. mov $0,%reg mov $0,%reg
  7097. @Lbl1: @Lbl1:
  7098. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7099. je @Lbl2 jne @Lbl2
  7100. To: To:
  7101. mov $0,%reg mov $0,%reg
  7102. jmp @Lbl2 jmp @Lbl3
  7103. (align) (align)
  7104. @Lbl1: @Lbl1:
  7105. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7106. je @Lbl2 je @Lbl2
  7107. @Lbl3: <-- Only if label exists
  7108. (Not if it's optimised for size)
  7109. }
  7110. if not GetNextInstruction(hp1, hp2) then
  7111. Exit;
  7112. if not (cs_opt_size in current_settings.optimizerswitches) and
  7113. (hp2.typ = ait_instruction) and
  7114. (
  7115. { Register sizes must exactly match }
  7116. (
  7117. (taicpu(hp2).opcode = A_CMP) and
  7118. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7119. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7120. ) or (
  7121. (taicpu(hp2).opcode = A_TEST) and
  7122. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7123. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7124. )
  7125. ) and GetNextInstruction(hp2, hp3) and
  7126. (hp3.typ = ait_instruction) and
  7127. (taicpu(hp3).opcode = A_JCC) and
  7128. (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
  7129. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7130. begin
  7131. { Check condition of jump }
  7132. { Always true? }
  7133. if condition_in(C_E, taicpu(hp3).condition) then
  7134. begin
  7135. { Copy label symbol and obtain matching label entry for the
  7136. conditional jump, as this will be our destination}
  7137. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7138. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7139. Result := True;
  7140. end
  7141. { Always false? }
  7142. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7143. begin
  7144. { This is only worth it if there's a jump to take }
  7145. case hp2.typ of
  7146. ait_instruction:
  7147. begin
  7148. if taicpu(hp2).opcode = A_JMP then
  7149. begin
  7150. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7151. { An unconditional jump follows the conditional jump which will always be false,
  7152. so use this jump's destination for the new jump }
  7153. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7154. Result := True;
  7155. end
  7156. else if taicpu(hp2).opcode = A_JCC then
  7157. begin
  7158. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7159. if condition_in(C_E, taicpu(hp2).condition) then
  7160. begin
  7161. { A second conditional jump follows the conditional jump which will always be false,
  7162. while the second jump is always True, so use this jump's destination for the new jump }
  7163. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7164. Result := True;
  7165. end;
  7166. { Don't risk it if the jump isn't always true (Result remains False) }
  7167. end;
  7168. end;
  7169. else
  7170. { If anything else don't optimise };
  7171. end;
  7172. end;
  7173. if Result then
  7174. begin
  7175. { Just so we have something to insert as a paremeter}
  7176. reference_reset(NewRef, 1, []);
  7177. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7178. { Now actually load the correct parameter }
  7179. NewInstr.loadsymbol(0, DestLabel, 0);
  7180. { Get instruction before original label (may not be p under -O3) }
  7181. if not GetLastInstruction(hp1, hp2) then
  7182. { Shouldn't fail here }
  7183. InternalError(2021040701);
  7184. DestLabel.increfs;
  7185. AsmL.InsertAfter(NewInstr, hp2);
  7186. { Add new alignment field }
  7187. (* AsmL.InsertAfter(
  7188. cai_align.create_max(
  7189. current_settings.alignment.jumpalign,
  7190. current_settings.alignment.jumpalignskipmax
  7191. ),
  7192. NewInstr
  7193. ); *)
  7194. end;
  7195. Exit;
  7196. end;
  7197. end;
  7198. else
  7199. ;
  7200. end;
  7201. end;
  7202. if not GetNextInstruction(p, hp1) then
  7203. Exit;
  7204. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7205. and DoMovCmpMemOpt(p, hp1, True) then
  7206. begin
  7207. Result := True;
  7208. Exit;
  7209. end
  7210. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7211. begin
  7212. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7213. further, but we can't just put this jump optimisation in pass 1
  7214. because it tends to perform worse when conditional jumps are
  7215. nearby (e.g. when converting CMOV instructions). [Kit] }
  7216. if OptPass2JMP(hp1) then
  7217. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7218. Result := OptPass1MOV(p)
  7219. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7220. returned True and the instruction is still a MOV, thus checking
  7221. the optimisations below }
  7222. { If OptPass2JMP returned False, no optimisations were done to
  7223. the jump and there are no further optimisations that can be done
  7224. to the MOV instruction on this pass }
  7225. end
  7226. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7227. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7228. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7229. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7230. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7231. begin
  7232. { Change:
  7233. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7234. addl/q $x,%reg2 subl/q $x,%reg2
  7235. To:
  7236. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7237. }
  7238. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7239. { be lazy, checking separately for sub would be slightly better }
  7240. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7241. begin
  7242. TransferUsedRegs(TmpUsedRegs);
  7243. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7244. if TryMovArith2Lea(hp1) then
  7245. begin
  7246. Result := True;
  7247. Exit;
  7248. end
  7249. end
  7250. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7251. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7252. { Same as above, but also adds or subtracts to %reg2 in between.
  7253. It's still valid as long as the flags aren't in use }
  7254. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7255. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7256. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7257. { be lazy, checking separately for sub would be slightly better }
  7258. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7259. begin
  7260. TransferUsedRegs(TmpUsedRegs);
  7261. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7262. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7263. if TryMovArith2Lea(hp2) then
  7264. begin
  7265. Result := True;
  7266. Exit;
  7267. end;
  7268. end;
  7269. end
  7270. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7271. {$ifdef x86_64}
  7272. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7273. {$else x86_64}
  7274. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7275. {$endif x86_64}
  7276. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7277. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7278. { mov reg1, reg2 mov reg1, reg2
  7279. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7280. begin
  7281. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7282. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7283. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7284. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7285. TransferUsedRegs(TmpUsedRegs);
  7286. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7287. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7288. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7289. then
  7290. begin
  7291. RemoveCurrentP(p, hp1);
  7292. Result:=true;
  7293. end;
  7294. exit;
  7295. end
  7296. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7297. IsXCHGAcceptable and
  7298. { XCHG doesn't support 8-byte registers }
  7299. (taicpu(p).opsize <> S_B) and
  7300. MatchInstruction(hp1, A_MOV, []) and
  7301. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7302. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7303. GetNextInstruction(hp1, hp2) and
  7304. MatchInstruction(hp2, A_MOV, []) and
  7305. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7306. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7307. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7308. begin
  7309. { mov %reg1,%reg2
  7310. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7311. mov %reg2,%reg3
  7312. (%reg2 not used afterwards)
  7313. Note that xchg takes 3 cycles to execute, and generally mov's take
  7314. only one cycle apiece, but the first two mov's can be executed in
  7315. parallel, only taking 2 cycles overall. Older processors should
  7316. therefore only optimise for size. [Kit]
  7317. }
  7318. TransferUsedRegs(TmpUsedRegs);
  7319. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7320. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7321. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7322. begin
  7323. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7324. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7325. taicpu(hp1).opcode := A_XCHG;
  7326. RemoveCurrentP(p, hp1);
  7327. RemoveInstruction(hp2);
  7328. Result := True;
  7329. Exit;
  7330. end;
  7331. end
  7332. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7333. MatchInstruction(hp1, A_SAR, []) then
  7334. begin
  7335. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7336. begin
  7337. { the use of %edx also covers the opsize being S_L }
  7338. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7339. begin
  7340. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7341. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7342. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7343. begin
  7344. { Change:
  7345. movl %eax,%edx
  7346. sarl $31,%edx
  7347. To:
  7348. cltd
  7349. }
  7350. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7351. RemoveInstruction(hp1);
  7352. taicpu(p).opcode := A_CDQ;
  7353. taicpu(p).opsize := S_NO;
  7354. taicpu(p).clearop(1);
  7355. taicpu(p).clearop(0);
  7356. taicpu(p).ops:=0;
  7357. Result := True;
  7358. end
  7359. else if (cs_opt_size in current_settings.optimizerswitches) and
  7360. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7361. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7362. begin
  7363. { Change:
  7364. movl %edx,%eax
  7365. sarl $31,%edx
  7366. To:
  7367. movl %edx,%eax
  7368. cltd
  7369. Note that this creates a dependency between the two instructions,
  7370. so only perform if optimising for size.
  7371. }
  7372. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7373. taicpu(hp1).opcode := A_CDQ;
  7374. taicpu(hp1).opsize := S_NO;
  7375. taicpu(hp1).clearop(1);
  7376. taicpu(hp1).clearop(0);
  7377. taicpu(hp1).ops:=0;
  7378. end;
  7379. {$ifndef x86_64}
  7380. end
  7381. { Don't bother if CMOV is supported, because a more optimal
  7382. sequence would have been generated for the Abs() intrinsic }
  7383. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7384. { the use of %eax also covers the opsize being S_L }
  7385. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7386. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7387. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7388. GetNextInstruction(hp1, hp2) and
  7389. MatchInstruction(hp2, A_XOR, [S_L]) and
  7390. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7391. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7392. GetNextInstruction(hp2, hp3) and
  7393. MatchInstruction(hp3, A_SUB, [S_L]) and
  7394. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7395. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7396. begin
  7397. { Change:
  7398. movl %eax,%edx
  7399. sarl $31,%eax
  7400. xorl %eax,%edx
  7401. subl %eax,%edx
  7402. (Instruction that uses %edx)
  7403. (%eax deallocated)
  7404. (%edx deallocated)
  7405. To:
  7406. cltd
  7407. xorl %edx,%eax <-- Note the registers have swapped
  7408. subl %edx,%eax
  7409. (Instruction that uses %eax) <-- %eax rather than %edx
  7410. }
  7411. TransferUsedRegs(TmpUsedRegs);
  7412. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7413. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7414. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7415. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7416. begin
  7417. if GetNextInstruction(hp3, hp4) and
  7418. not RegModifiedByInstruction(NR_EDX, hp4) and
  7419. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7420. begin
  7421. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7422. taicpu(p).opcode := A_CDQ;
  7423. taicpu(p).clearop(1);
  7424. taicpu(p).clearop(0);
  7425. taicpu(p).ops:=0;
  7426. RemoveInstruction(hp1);
  7427. taicpu(hp2).loadreg(0, NR_EDX);
  7428. taicpu(hp2).loadreg(1, NR_EAX);
  7429. taicpu(hp3).loadreg(0, NR_EDX);
  7430. taicpu(hp3).loadreg(1, NR_EAX);
  7431. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7432. { Convert references in the following instruction (hp4) from %edx to %eax }
  7433. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7434. with taicpu(hp4).oper[OperIdx]^ do
  7435. case typ of
  7436. top_reg:
  7437. if getsupreg(reg) = RS_EDX then
  7438. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7439. top_ref:
  7440. begin
  7441. if getsupreg(reg) = RS_EDX then
  7442. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7443. if getsupreg(reg) = RS_EDX then
  7444. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7445. end;
  7446. else
  7447. ;
  7448. end;
  7449. end;
  7450. end;
  7451. {$else x86_64}
  7452. end;
  7453. end
  7454. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7455. { the use of %rdx also covers the opsize being S_Q }
  7456. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7457. begin
  7458. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7459. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7460. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7461. begin
  7462. { Change:
  7463. movq %rax,%rdx
  7464. sarq $63,%rdx
  7465. To:
  7466. cqto
  7467. }
  7468. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7469. RemoveInstruction(hp1);
  7470. taicpu(p).opcode := A_CQO;
  7471. taicpu(p).opsize := S_NO;
  7472. taicpu(p).clearop(1);
  7473. taicpu(p).clearop(0);
  7474. taicpu(p).ops:=0;
  7475. Result := True;
  7476. end
  7477. else if (cs_opt_size in current_settings.optimizerswitches) and
  7478. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7479. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7480. begin
  7481. { Change:
  7482. movq %rdx,%rax
  7483. sarq $63,%rdx
  7484. To:
  7485. movq %rdx,%rax
  7486. cqto
  7487. Note that this creates a dependency between the two instructions,
  7488. so only perform if optimising for size.
  7489. }
  7490. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7491. taicpu(hp1).opcode := A_CQO;
  7492. taicpu(hp1).opsize := S_NO;
  7493. taicpu(hp1).clearop(1);
  7494. taicpu(hp1).clearop(0);
  7495. taicpu(hp1).ops:=0;
  7496. {$endif x86_64}
  7497. end;
  7498. end;
  7499. end
  7500. else if MatchInstruction(hp1, A_MOV, []) and
  7501. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7502. { Though "GetNextInstruction" could be factored out, along with
  7503. the instructions that depend on hp2, it is an expensive call that
  7504. should be delayed for as long as possible, hence we do cheaper
  7505. checks first that are likely to be False. [Kit] }
  7506. begin
  7507. if (
  7508. (
  7509. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7510. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7511. (
  7512. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7513. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7514. )
  7515. ) or
  7516. (
  7517. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7518. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7519. (
  7520. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7521. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7522. )
  7523. )
  7524. ) and
  7525. GetNextInstruction(hp1, hp2) and
  7526. MatchInstruction(hp2, A_SAR, []) and
  7527. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7528. begin
  7529. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7530. begin
  7531. { Change:
  7532. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7533. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7534. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7535. To:
  7536. movl r/m,%eax <- Note the change in register
  7537. cltd
  7538. }
  7539. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7540. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7541. taicpu(p).loadreg(1, NR_EAX);
  7542. taicpu(hp1).opcode := A_CDQ;
  7543. taicpu(hp1).clearop(1);
  7544. taicpu(hp1).clearop(0);
  7545. taicpu(hp1).ops:=0;
  7546. RemoveInstruction(hp2);
  7547. (*
  7548. {$ifdef x86_64}
  7549. end
  7550. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7551. { This code sequence does not get generated - however it might become useful
  7552. if and when 128-bit signed integer types make an appearance, so the code
  7553. is kept here for when it is eventually needed. [Kit] }
  7554. (
  7555. (
  7556. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7557. (
  7558. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7559. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7560. )
  7561. ) or
  7562. (
  7563. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7564. (
  7565. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7566. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7567. )
  7568. )
  7569. ) and
  7570. GetNextInstruction(hp1, hp2) and
  7571. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7572. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7573. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7574. begin
  7575. { Change:
  7576. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7577. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7578. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7579. To:
  7580. movq r/m,%rax <- Note the change in register
  7581. cqto
  7582. }
  7583. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7584. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7585. taicpu(p).loadreg(1, NR_RAX);
  7586. taicpu(hp1).opcode := A_CQO;
  7587. taicpu(hp1).clearop(1);
  7588. taicpu(hp1).clearop(0);
  7589. taicpu(hp1).ops:=0;
  7590. RemoveInstruction(hp2);
  7591. {$endif x86_64}
  7592. *)
  7593. end;
  7594. end;
  7595. {$ifdef x86_64}
  7596. end
  7597. else if (taicpu(p).opsize = S_L) and
  7598. (taicpu(p).oper[1]^.typ = top_reg) and
  7599. (
  7600. MatchInstruction(hp1, A_MOV,[]) and
  7601. (taicpu(hp1).opsize = S_L) and
  7602. (taicpu(hp1).oper[1]^.typ = top_reg)
  7603. ) and (
  7604. GetNextInstruction(hp1, hp2) and
  7605. (tai(hp2).typ=ait_instruction) and
  7606. (taicpu(hp2).opsize = S_Q) and
  7607. (
  7608. (
  7609. MatchInstruction(hp2, A_ADD,[]) and
  7610. (taicpu(hp2).opsize = S_Q) and
  7611. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7612. (
  7613. (
  7614. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7615. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7616. ) or (
  7617. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7618. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7619. )
  7620. )
  7621. ) or (
  7622. MatchInstruction(hp2, A_LEA,[]) and
  7623. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7624. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7625. (
  7626. (
  7627. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7628. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7629. ) or (
  7630. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7631. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7632. )
  7633. ) and (
  7634. (
  7635. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7636. ) or (
  7637. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7638. )
  7639. )
  7640. )
  7641. )
  7642. ) and (
  7643. GetNextInstruction(hp2, hp3) and
  7644. MatchInstruction(hp3, A_SHR,[]) and
  7645. (taicpu(hp3).opsize = S_Q) and
  7646. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7647. (taicpu(hp3).oper[0]^.val = 1) and
  7648. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7649. ) then
  7650. begin
  7651. { Change movl x, reg1d movl x, reg1d
  7652. movl y, reg2d movl y, reg2d
  7653. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7654. shrq $1, reg1q shrq $1, reg1q
  7655. ( reg1d and reg2d can be switched around in the first two instructions )
  7656. To movl x, reg1d
  7657. addl y, reg1d
  7658. rcrl $1, reg1d
  7659. This corresponds to the common expression (x + y) shr 1, where
  7660. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7661. smaller code, but won't account for x + y causing an overflow). [Kit]
  7662. }
  7663. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7664. { Change first MOV command to have the same register as the final output }
  7665. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7666. else
  7667. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7668. { Change second MOV command to an ADD command. This is easier than
  7669. converting the existing command because it means we don't have to
  7670. touch 'y', which might be a complicated reference, and also the
  7671. fact that the third command might either be ADD or LEA. [Kit] }
  7672. taicpu(hp1).opcode := A_ADD;
  7673. { Delete old ADD/LEA instruction }
  7674. RemoveInstruction(hp2);
  7675. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7676. taicpu(hp3).opcode := A_RCR;
  7677. taicpu(hp3).changeopsize(S_L);
  7678. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7679. {$endif x86_64}
  7680. end;
  7681. end;
  7682. {$push}
  7683. {$q-}{$r-}
  7684. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7685. var
  7686. ThisReg: TRegister;
  7687. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7688. TargetSubReg: TSubRegister;
  7689. hp1, hp2: tai;
  7690. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7691. { Store list of found instructions so we don't have to call
  7692. GetNextInstructionUsingReg multiple times }
  7693. InstrList: array of taicpu;
  7694. InstrMax, Index: Integer;
  7695. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7696. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7697. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7698. WorkingValue: TCgInt;
  7699. PreMessage: string;
  7700. { Data flow analysis }
  7701. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7702. BitwiseOnly, OrXorUsed,
  7703. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7704. function CheckOverflowConditions: Boolean;
  7705. begin
  7706. Result := True;
  7707. if (TestValSignedMax > SignedUpperLimit) then
  7708. UpperSignedOverflow := True;
  7709. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7710. LowerSignedOverflow := True;
  7711. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7712. LowerUnsignedOverflow := True;
  7713. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7714. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7715. begin
  7716. { Absolute overflow }
  7717. Result := False;
  7718. Exit;
  7719. end;
  7720. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7721. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7722. ShiftDownOverflow := True;
  7723. if (TestValMin < 0) or (TestValMax < 0) then
  7724. begin
  7725. LowerUnsignedOverflow := True;
  7726. UpperUnsignedOverflow := True;
  7727. end;
  7728. end;
  7729. function AdjustInitialLoadAndSize: Boolean;
  7730. begin
  7731. Result := False;
  7732. if not p_removed then
  7733. begin
  7734. if TargetSize = MinSize then
  7735. begin
  7736. { Convert the input MOVZX to a MOV }
  7737. if (taicpu(p).oper[0]^.typ = top_reg) and
  7738. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7739. begin
  7740. { Or remove it completely! }
  7741. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7742. RemoveCurrentP(p);
  7743. p_removed := True;
  7744. end
  7745. else
  7746. begin
  7747. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7748. taicpu(p).opcode := A_MOV;
  7749. taicpu(p).oper[1]^.reg := ThisReg;
  7750. taicpu(p).opsize := TargetSize;
  7751. end;
  7752. Result := True;
  7753. end
  7754. else if TargetSize <> MaxSize then
  7755. begin
  7756. case MaxSize of
  7757. S_L:
  7758. if TargetSize = S_W then
  7759. begin
  7760. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7761. taicpu(p).opsize := S_BW;
  7762. taicpu(p).oper[1]^.reg := ThisReg;
  7763. Result := True;
  7764. end
  7765. else
  7766. InternalError(2020112341);
  7767. S_W:
  7768. if TargetSize = S_L then
  7769. begin
  7770. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7771. taicpu(p).opsize := S_BL;
  7772. taicpu(p).oper[1]^.reg := ThisReg;
  7773. Result := True;
  7774. end
  7775. else
  7776. InternalError(2020112342);
  7777. else
  7778. ;
  7779. end;
  7780. end
  7781. else if not hp1_removed and not RegInUse then
  7782. begin
  7783. { If we have something like:
  7784. movzbl (oper),%regd
  7785. add x, %regd
  7786. movzbl %regb, %regd
  7787. We can reduce the register size to the input of the final
  7788. movzbl instruction. Overflows won't have any effect.
  7789. }
  7790. if (taicpu(p).opsize in [S_BW, S_BL]) and
  7791. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7792. begin
  7793. TargetSize := S_B;
  7794. setsubreg(ThisReg, R_SUBL);
  7795. Result := True;
  7796. end
  7797. else if (taicpu(p).opsize = S_WL) and
  7798. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7799. begin
  7800. TargetSize := S_W;
  7801. setsubreg(ThisReg, R_SUBW);
  7802. Result := True;
  7803. end;
  7804. if Result then
  7805. begin
  7806. { Convert the input MOVZX to a MOV }
  7807. if (taicpu(p).oper[0]^.typ = top_reg) and
  7808. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7809. begin
  7810. { Or remove it completely! }
  7811. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7812. RemoveCurrentP(p);
  7813. p_removed := True;
  7814. end
  7815. else
  7816. begin
  7817. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7818. taicpu(p).opcode := A_MOV;
  7819. taicpu(p).oper[1]^.reg := ThisReg;
  7820. taicpu(p).opsize := TargetSize;
  7821. end;
  7822. end;
  7823. end;
  7824. end;
  7825. end;
  7826. procedure AdjustFinalLoad;
  7827. begin
  7828. if not LowerUnsignedOverflow then
  7829. begin
  7830. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7831. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7832. begin
  7833. { Convert the output MOVZX to a MOV }
  7834. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7835. begin
  7836. { Or remove it completely! }
  7837. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7838. { Be careful; if p = hp1 and p was also removed, p
  7839. will become a dangling pointer }
  7840. if p = hp1 then
  7841. begin
  7842. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7843. p_removed := True;
  7844. end
  7845. else
  7846. RemoveInstruction(hp1);
  7847. hp1_removed := True;
  7848. end
  7849. else
  7850. begin
  7851. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7852. taicpu(hp1).opcode := A_MOV;
  7853. taicpu(hp1).oper[0]^.reg := ThisReg;
  7854. taicpu(hp1).opsize := TargetSize;
  7855. end;
  7856. end
  7857. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7858. begin
  7859. { Need to change the size of the output }
  7860. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7861. taicpu(hp1).oper[0]^.reg := ThisReg;
  7862. taicpu(hp1).opsize := S_BL;
  7863. end;
  7864. end;
  7865. end;
  7866. function CompressInstructions: Boolean;
  7867. var
  7868. LocalIndex: Integer;
  7869. begin
  7870. Result := False;
  7871. { The objective here is to try to find a combination that
  7872. removes one of the MOV/Z instructions. }
  7873. if (
  7874. (taicpu(p).oper[0]^.typ <> top_reg) or
  7875. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7876. ) and
  7877. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7878. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7879. begin
  7880. { Make a preference to remove the second MOVZX instruction }
  7881. case taicpu(hp1).opsize of
  7882. S_BL, S_WL:
  7883. begin
  7884. TargetSize := S_L;
  7885. TargetSubReg := R_SUBD;
  7886. end;
  7887. S_BW:
  7888. begin
  7889. TargetSize := S_W;
  7890. TargetSubReg := R_SUBW;
  7891. end;
  7892. else
  7893. InternalError(2020112302);
  7894. end;
  7895. end
  7896. else
  7897. begin
  7898. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7899. begin
  7900. { Exceeded lower bound but not upper bound }
  7901. TargetSize := MaxSize;
  7902. end
  7903. else if not LowerUnsignedOverflow then
  7904. begin
  7905. { Size didn't exceed lower bound }
  7906. TargetSize := MinSize;
  7907. end
  7908. else
  7909. Exit;
  7910. end;
  7911. case TargetSize of
  7912. S_B:
  7913. TargetSubReg := R_SUBL;
  7914. S_W:
  7915. TargetSubReg := R_SUBW;
  7916. S_L:
  7917. TargetSubReg := R_SUBD;
  7918. else
  7919. InternalError(2020112350);
  7920. end;
  7921. { Update the register to its new size }
  7922. setsubreg(ThisReg, TargetSubReg);
  7923. RegInUse := False;
  7924. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7925. begin
  7926. { Check to see if the active register is used afterwards;
  7927. if not, we can change it and make a saving. }
  7928. TransferUsedRegs(TmpUsedRegs);
  7929. { The target register may be marked as in use to cross
  7930. a jump to a distant label, so exclude it }
  7931. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7932. hp2 := p;
  7933. repeat
  7934. { Explicitly check for the excluded register (don't include the first
  7935. instruction as it may be reading from here }
  7936. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7937. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7938. begin
  7939. RegInUse := True;
  7940. Break;
  7941. end;
  7942. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7943. if not GetNextInstruction(hp2, hp2) then
  7944. InternalError(2020112340);
  7945. until (hp2 = hp1);
  7946. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7947. { We might still be able to get away with this }
  7948. RegInUse := not
  7949. (
  7950. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7951. (hp2.typ = ait_instruction) and
  7952. (
  7953. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7954. instruction that doesn't actually contain ThisReg }
  7955. (cs_opt_level3 in current_settings.optimizerswitches) or
  7956. RegInInstruction(ThisReg, hp2)
  7957. ) and
  7958. RegLoadedWithNewValue(ThisReg, hp2)
  7959. );
  7960. if not RegInUse then
  7961. begin
  7962. { Force the register size to the same as this instruction so it can be removed}
  7963. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7964. begin
  7965. TargetSize := S_L;
  7966. TargetSubReg := R_SUBD;
  7967. end
  7968. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7969. begin
  7970. TargetSize := S_W;
  7971. TargetSubReg := R_SUBW;
  7972. end;
  7973. ThisReg := taicpu(hp1).oper[1]^.reg;
  7974. setsubreg(ThisReg, TargetSubReg);
  7975. RegChanged := True;
  7976. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7977. TransferUsedRegs(TmpUsedRegs);
  7978. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7979. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7980. if p = hp1 then
  7981. begin
  7982. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7983. p_removed := True;
  7984. end
  7985. else
  7986. RemoveInstruction(hp1);
  7987. hp1_removed := True;
  7988. { Instruction will become "mov %reg,%reg" }
  7989. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7990. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7991. begin
  7992. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7993. RemoveCurrentP(p);
  7994. p_removed := True;
  7995. end
  7996. else
  7997. taicpu(p).oper[1]^.reg := ThisReg;
  7998. Result := True;
  7999. end
  8000. else
  8001. begin
  8002. if TargetSize <> MaxSize then
  8003. begin
  8004. { Since the register is in use, we have to force it to
  8005. MaxSize otherwise part of it may become undefined later on }
  8006. TargetSize := MaxSize;
  8007. case TargetSize of
  8008. S_B:
  8009. TargetSubReg := R_SUBL;
  8010. S_W:
  8011. TargetSubReg := R_SUBW;
  8012. S_L:
  8013. TargetSubReg := R_SUBD;
  8014. else
  8015. InternalError(2020112351);
  8016. end;
  8017. setsubreg(ThisReg, TargetSubReg);
  8018. end;
  8019. AdjustFinalLoad;
  8020. end;
  8021. end
  8022. else
  8023. AdjustFinalLoad;
  8024. Result := AdjustInitialLoadAndSize or Result;
  8025. { Now go through every instruction we found and change the
  8026. size. If TargetSize = MaxSize, then almost no changes are
  8027. needed and Result can remain False if it hasn't been set
  8028. yet.
  8029. If RegChanged is True, then the register requires changing
  8030. and so the point about TargetSize = MaxSize doesn't apply. }
  8031. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8032. begin
  8033. for LocalIndex := 0 to InstrMax do
  8034. begin
  8035. { If p_removed is true, then the original MOV/Z was removed
  8036. and removing the AND instruction may not be safe if it
  8037. appears first }
  8038. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8039. InternalError(2020112310);
  8040. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8041. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8042. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8043. InstrList[LocalIndex].opsize := TargetSize;
  8044. end;
  8045. Result := True;
  8046. end;
  8047. end;
  8048. begin
  8049. Result := False;
  8050. p_removed := False;
  8051. hp1_removed := False;
  8052. ThisReg := taicpu(p).oper[1]^.reg;
  8053. { Check for:
  8054. movs/z ###,%ecx (or %cx or %rcx)
  8055. ...
  8056. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8057. (dealloc %ecx)
  8058. Change to:
  8059. mov ###,%cl (if ### = %cl, then remove completely)
  8060. ...
  8061. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8062. }
  8063. if (getsupreg(ThisReg) = RS_ECX) and
  8064. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8065. (hp1.typ = ait_instruction) and
  8066. (
  8067. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8068. instruction that doesn't actually contain ECX }
  8069. (cs_opt_level3 in current_settings.optimizerswitches) or
  8070. RegInInstruction(NR_ECX, hp1) or
  8071. (
  8072. { It's common for the shift/rotate's read/write register to be
  8073. initialised in between, so under -O2 and under, search ahead
  8074. one more instruction
  8075. }
  8076. GetNextInstruction(hp1, hp1) and
  8077. (hp1.typ = ait_instruction) and
  8078. RegInInstruction(NR_ECX, hp1)
  8079. )
  8080. ) and
  8081. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8082. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8083. begin
  8084. TransferUsedRegs(TmpUsedRegs);
  8085. hp2 := p;
  8086. repeat
  8087. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8088. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8089. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8090. begin
  8091. case taicpu(p).opsize of
  8092. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8093. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8094. begin
  8095. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8096. RemoveCurrentP(p);
  8097. end
  8098. else
  8099. begin
  8100. taicpu(p).opcode := A_MOV;
  8101. taicpu(p).opsize := S_B;
  8102. taicpu(p).oper[1]^.reg := NR_CL;
  8103. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8104. end;
  8105. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8106. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8107. begin
  8108. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8109. RemoveCurrentP(p);
  8110. end
  8111. else
  8112. begin
  8113. taicpu(p).opcode := A_MOV;
  8114. taicpu(p).opsize := S_W;
  8115. taicpu(p).oper[1]^.reg := NR_CX;
  8116. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8117. end;
  8118. {$ifdef x86_64}
  8119. S_LQ:
  8120. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8121. begin
  8122. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8123. RemoveCurrentP(p);
  8124. end
  8125. else
  8126. begin
  8127. taicpu(p).opcode := A_MOV;
  8128. taicpu(p).opsize := S_L;
  8129. taicpu(p).oper[1]^.reg := NR_ECX;
  8130. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8131. end;
  8132. {$endif x86_64}
  8133. else
  8134. InternalError(2021120401);
  8135. end;
  8136. Result := True;
  8137. Exit;
  8138. end;
  8139. end;
  8140. { This is anything but quick! }
  8141. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8142. Exit;
  8143. SetLength(InstrList, 0);
  8144. InstrMax := -1;
  8145. case taicpu(p).opsize of
  8146. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8147. begin
  8148. {$if defined(i386) or defined(i8086)}
  8149. { If the target size is 8-bit, make sure we can actually encode it }
  8150. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8151. Exit;
  8152. {$endif i386 or i8086}
  8153. LowerLimit := $FF;
  8154. SignedLowerLimit := $7F;
  8155. SignedLowerLimitBottom := -128;
  8156. MinSize := S_B;
  8157. if taicpu(p).opsize = S_BW then
  8158. begin
  8159. MaxSize := S_W;
  8160. UpperLimit := $FFFF;
  8161. SignedUpperLimit := $7FFF;
  8162. SignedUpperLimitBottom := -32768;
  8163. end
  8164. else
  8165. begin
  8166. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8167. MaxSize := S_L;
  8168. UpperLimit := $FFFFFFFF;
  8169. SignedUpperLimit := $7FFFFFFF;
  8170. SignedUpperLimitBottom := -2147483648;
  8171. end;
  8172. end;
  8173. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8174. begin
  8175. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8176. LowerLimit := $FFFF;
  8177. SignedLowerLimit := $7FFF;
  8178. SignedLowerLimitBottom := -32768;
  8179. UpperLimit := $FFFFFFFF;
  8180. SignedUpperLimit := $7FFFFFFF;
  8181. SignedUpperLimitBottom := -2147483648;
  8182. MinSize := S_W;
  8183. MaxSize := S_L;
  8184. end;
  8185. {$ifdef x86_64}
  8186. S_LQ:
  8187. begin
  8188. { Both the lower and upper limits are set to 32-bit. If a limit
  8189. is breached, then optimisation is impossible }
  8190. LowerLimit := $FFFFFFFF;
  8191. SignedLowerLimit := $7FFFFFFF;
  8192. SignedLowerLimitBottom := -2147483648;
  8193. UpperLimit := $FFFFFFFF;
  8194. SignedUpperLimit := $7FFFFFFF;
  8195. SignedUpperLimitBottom := -2147483648;
  8196. MinSize := S_L;
  8197. MaxSize := S_L;
  8198. end;
  8199. {$endif x86_64}
  8200. else
  8201. InternalError(2020112301);
  8202. end;
  8203. TestValMin := 0;
  8204. TestValMax := LowerLimit;
  8205. TestValSignedMax := SignedLowerLimit;
  8206. TryShiftDownLimit := LowerLimit;
  8207. TryShiftDown := S_NO;
  8208. ShiftDownOverflow := False;
  8209. RegChanged := False;
  8210. BitwiseOnly := True;
  8211. OrXorUsed := False;
  8212. UpperSignedOverflow := False;
  8213. LowerSignedOverflow := False;
  8214. UpperUnsignedOverflow := False;
  8215. LowerUnsignedOverflow := False;
  8216. hp1 := p;
  8217. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8218. (hp1.typ = ait_instruction) and
  8219. (
  8220. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8221. instruction that doesn't actually contain ThisReg }
  8222. (cs_opt_level3 in current_settings.optimizerswitches) or
  8223. { This allows this Movx optimisation to work through the SETcc instructions
  8224. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8225. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8226. skip over these SETcc instructions). }
  8227. (taicpu(hp1).opcode = A_SETcc) or
  8228. RegInInstruction(ThisReg, hp1)
  8229. ) do
  8230. begin
  8231. case taicpu(hp1).opcode of
  8232. A_INC,A_DEC:
  8233. begin
  8234. { Has to be an exact match on the register }
  8235. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8236. Break;
  8237. if taicpu(hp1).opcode = A_INC then
  8238. begin
  8239. Inc(TestValMin);
  8240. Inc(TestValMax);
  8241. Inc(TestValSignedMax);
  8242. end
  8243. else
  8244. begin
  8245. Dec(TestValMin);
  8246. Dec(TestValMax);
  8247. Dec(TestValSignedMax);
  8248. end;
  8249. end;
  8250. A_TEST, A_CMP:
  8251. begin
  8252. if (
  8253. { Too high a risk of non-linear behaviour that breaks DFA
  8254. here, unless it's cmp $0,%reg, which is equivalent to
  8255. test %reg,%reg }
  8256. OrXorUsed and
  8257. (taicpu(hp1).opcode = A_CMP) and
  8258. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8259. ) or
  8260. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8261. { Has to be an exact match on the register }
  8262. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8263. (
  8264. { Permit "test %reg,%reg" }
  8265. (taicpu(hp1).opcode = A_TEST) and
  8266. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8267. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8268. ) or
  8269. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8270. { Make sure the comparison value is not smaller than the
  8271. smallest allowed signed value for the minimum size (e.g.
  8272. -128 for 8-bit) }
  8273. not (
  8274. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8275. { Is it in the negative range? }
  8276. (
  8277. (taicpu(hp1).oper[0]^.val < 0) and
  8278. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8279. )
  8280. ) then
  8281. Break;
  8282. { Check to see if the active register is used afterwards }
  8283. TransferUsedRegs(TmpUsedRegs);
  8284. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8285. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8286. begin
  8287. { Make sure the comparison or any previous instructions
  8288. hasn't pushed the test values outside of the range of
  8289. MinSize }
  8290. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8291. begin
  8292. { Exceeded lower bound but not upper bound }
  8293. Exit;
  8294. end
  8295. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8296. begin
  8297. { Size didn't exceed lower bound }
  8298. TargetSize := MinSize;
  8299. end
  8300. else
  8301. Break;
  8302. case TargetSize of
  8303. S_B:
  8304. TargetSubReg := R_SUBL;
  8305. S_W:
  8306. TargetSubReg := R_SUBW;
  8307. S_L:
  8308. TargetSubReg := R_SUBD;
  8309. else
  8310. InternalError(2021051002);
  8311. end;
  8312. if TargetSize <> MaxSize then
  8313. begin
  8314. { Update the register to its new size }
  8315. setsubreg(ThisReg, TargetSubReg);
  8316. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8317. taicpu(hp1).oper[1]^.reg := ThisReg;
  8318. taicpu(hp1).opsize := TargetSize;
  8319. { Convert the input MOVZX to a MOV if necessary }
  8320. AdjustInitialLoadAndSize;
  8321. if (InstrMax >= 0) then
  8322. begin
  8323. for Index := 0 to InstrMax do
  8324. begin
  8325. { If p_removed is true, then the original MOV/Z was removed
  8326. and removing the AND instruction may not be safe if it
  8327. appears first }
  8328. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8329. InternalError(2020112311);
  8330. if InstrList[Index].oper[0]^.typ = top_reg then
  8331. InstrList[Index].oper[0]^.reg := ThisReg;
  8332. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8333. InstrList[Index].opsize := MinSize;
  8334. end;
  8335. end;
  8336. Result := True;
  8337. end;
  8338. Exit;
  8339. end;
  8340. end;
  8341. A_SETcc:
  8342. begin
  8343. { This allows this Movx optimisation to work through the SETcc instructions
  8344. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8345. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8346. skip over these SETcc instructions). }
  8347. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8348. { Of course, break out if the current register is used }
  8349. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8350. Break
  8351. else
  8352. { We must use Continue so the instruction doesn't get added
  8353. to InstrList }
  8354. Continue;
  8355. end;
  8356. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8357. begin
  8358. if
  8359. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8360. { Has to be an exact match on the register }
  8361. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8362. (
  8363. (
  8364. (taicpu(hp1).oper[0]^.typ = top_const) and
  8365. (
  8366. (
  8367. (taicpu(hp1).opcode = A_SHL) and
  8368. (
  8369. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8370. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8371. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8372. )
  8373. ) or (
  8374. (taicpu(hp1).opcode <> A_SHL) and
  8375. (
  8376. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8377. { Is it in the negative range? }
  8378. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8379. )
  8380. )
  8381. )
  8382. ) or (
  8383. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8384. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8385. )
  8386. ) then
  8387. Break;
  8388. { Only process OR and XOR if there are only bitwise operations,
  8389. since otherwise they can too easily fool the data flow
  8390. analysis (they can cause non-linear behaviour) }
  8391. case taicpu(hp1).opcode of
  8392. A_ADD:
  8393. begin
  8394. if OrXorUsed then
  8395. { Too high a risk of non-linear behaviour that breaks DFA here }
  8396. Break
  8397. else
  8398. BitwiseOnly := False;
  8399. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8400. begin
  8401. TestValMin := TestValMin * 2;
  8402. TestValMax := TestValMax * 2;
  8403. TestValSignedMax := TestValSignedMax * 2;
  8404. end
  8405. else
  8406. begin
  8407. WorkingValue := taicpu(hp1).oper[0]^.val;
  8408. TestValMin := TestValMin + WorkingValue;
  8409. TestValMax := TestValMax + WorkingValue;
  8410. TestValSignedMax := TestValSignedMax + WorkingValue;
  8411. end;
  8412. end;
  8413. A_SUB:
  8414. begin
  8415. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8416. begin
  8417. TestValMin := 0;
  8418. TestValMax := 0;
  8419. TestValSignedMax := 0;
  8420. end
  8421. else
  8422. begin
  8423. if OrXorUsed then
  8424. { Too high a risk of non-linear behaviour that breaks DFA here }
  8425. Break
  8426. else
  8427. BitwiseOnly := False;
  8428. WorkingValue := taicpu(hp1).oper[0]^.val;
  8429. TestValMin := TestValMin - WorkingValue;
  8430. TestValMax := TestValMax - WorkingValue;
  8431. TestValSignedMax := TestValSignedMax - WorkingValue;
  8432. end;
  8433. end;
  8434. A_AND:
  8435. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8436. begin
  8437. { we might be able to go smaller if AND appears first }
  8438. if InstrMax = -1 then
  8439. case MinSize of
  8440. S_B:
  8441. ;
  8442. S_W:
  8443. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8444. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8445. begin
  8446. TryShiftDown := S_B;
  8447. TryShiftDownLimit := $FF;
  8448. end;
  8449. S_L:
  8450. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8451. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8452. begin
  8453. TryShiftDown := S_B;
  8454. TryShiftDownLimit := $FF;
  8455. end
  8456. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8457. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8458. begin
  8459. TryShiftDown := S_W;
  8460. TryShiftDownLimit := $FFFF;
  8461. end;
  8462. else
  8463. InternalError(2020112320);
  8464. end;
  8465. WorkingValue := taicpu(hp1).oper[0]^.val;
  8466. TestValMin := TestValMin and WorkingValue;
  8467. TestValMax := TestValMax and WorkingValue;
  8468. TestValSignedMax := TestValSignedMax and WorkingValue;
  8469. end;
  8470. A_OR:
  8471. begin
  8472. if not BitwiseOnly then
  8473. Break;
  8474. OrXorUsed := True;
  8475. WorkingValue := taicpu(hp1).oper[0]^.val;
  8476. TestValMin := TestValMin or WorkingValue;
  8477. TestValMax := TestValMax or WorkingValue;
  8478. TestValSignedMax := TestValSignedMax or WorkingValue;
  8479. end;
  8480. A_XOR:
  8481. begin
  8482. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8483. begin
  8484. TestValMin := 0;
  8485. TestValMax := 0;
  8486. TestValSignedMax := 0;
  8487. end
  8488. else
  8489. begin
  8490. if not BitwiseOnly then
  8491. Break;
  8492. OrXorUsed := True;
  8493. WorkingValue := taicpu(hp1).oper[0]^.val;
  8494. TestValMin := TestValMin xor WorkingValue;
  8495. TestValMax := TestValMax xor WorkingValue;
  8496. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8497. end;
  8498. end;
  8499. A_SHL:
  8500. begin
  8501. BitwiseOnly := False;
  8502. WorkingValue := taicpu(hp1).oper[0]^.val;
  8503. TestValMin := TestValMin shl WorkingValue;
  8504. TestValMax := TestValMax shl WorkingValue;
  8505. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8506. end;
  8507. A_SHR,
  8508. { The first instruction was MOVZX, so the value won't be negative }
  8509. A_SAR:
  8510. begin
  8511. if InstrMax <> -1 then
  8512. BitwiseOnly := False
  8513. else
  8514. { we might be able to go smaller if SHR appears first }
  8515. case MinSize of
  8516. S_B:
  8517. ;
  8518. S_W:
  8519. if (taicpu(hp1).oper[0]^.val >= 8) then
  8520. begin
  8521. TryShiftDown := S_B;
  8522. TryShiftDownLimit := $FF;
  8523. TryShiftDownSignedLimit := $7F;
  8524. TryShiftDownSignedLimitLower := -128;
  8525. end;
  8526. S_L:
  8527. if (taicpu(hp1).oper[0]^.val >= 24) then
  8528. begin
  8529. TryShiftDown := S_B;
  8530. TryShiftDownLimit := $FF;
  8531. TryShiftDownSignedLimit := $7F;
  8532. TryShiftDownSignedLimitLower := -128;
  8533. end
  8534. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8535. begin
  8536. TryShiftDown := S_W;
  8537. TryShiftDownLimit := $FFFF;
  8538. TryShiftDownSignedLimit := $7FFF;
  8539. TryShiftDownSignedLimitLower := -32768;
  8540. end;
  8541. else
  8542. InternalError(2020112321);
  8543. end;
  8544. WorkingValue := taicpu(hp1).oper[0]^.val;
  8545. if taicpu(hp1).opcode = A_SAR then
  8546. begin
  8547. TestValMin := SarInt64(TestValMin, WorkingValue);
  8548. TestValMax := SarInt64(TestValMax, WorkingValue);
  8549. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8550. end
  8551. else
  8552. begin
  8553. TestValMin := TestValMin shr WorkingValue;
  8554. TestValMax := TestValMax shr WorkingValue;
  8555. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8556. end;
  8557. end;
  8558. else
  8559. InternalError(2020112303);
  8560. end;
  8561. end;
  8562. (*
  8563. A_IMUL:
  8564. case taicpu(hp1).ops of
  8565. 2:
  8566. begin
  8567. if not MatchOpType(hp1, top_reg, top_reg) or
  8568. { Has to be an exact match on the register }
  8569. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8570. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8571. Break;
  8572. TestValMin := TestValMin * TestValMin;
  8573. TestValMax := TestValMax * TestValMax;
  8574. TestValSignedMax := TestValSignedMax * TestValMax;
  8575. end;
  8576. 3:
  8577. begin
  8578. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8579. { Has to be an exact match on the register }
  8580. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8581. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8582. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8583. { Is it in the negative range? }
  8584. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8585. Break;
  8586. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8587. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8588. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8589. end;
  8590. else
  8591. Break;
  8592. end;
  8593. A_IDIV:
  8594. case taicpu(hp1).ops of
  8595. 3:
  8596. begin
  8597. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8598. { Has to be an exact match on the register }
  8599. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8600. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8601. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8602. { Is it in the negative range? }
  8603. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8604. Break;
  8605. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8606. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8607. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8608. end;
  8609. else
  8610. Break;
  8611. end;
  8612. *)
  8613. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8614. begin
  8615. { If there are no instructions in between, then we might be able to make a saving }
  8616. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8617. Break;
  8618. { We have something like:
  8619. movzbw %dl,%dx
  8620. ...
  8621. movswl %dx,%edx
  8622. Change the latter to a zero-extension then enter the
  8623. A_MOVZX case branch.
  8624. }
  8625. {$ifdef x86_64}
  8626. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8627. begin
  8628. { this becomes a zero extension from 32-bit to 64-bit, but
  8629. the upper 32 bits are already zero, so just delete the
  8630. instruction }
  8631. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8632. RemoveInstruction(hp1);
  8633. Result := True;
  8634. Exit;
  8635. end
  8636. else
  8637. {$endif x86_64}
  8638. begin
  8639. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8640. taicpu(hp1).opcode := A_MOVZX;
  8641. {$ifdef x86_64}
  8642. case taicpu(hp1).opsize of
  8643. S_BQ:
  8644. begin
  8645. taicpu(hp1).opsize := S_BL;
  8646. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8647. end;
  8648. S_WQ:
  8649. begin
  8650. taicpu(hp1).opsize := S_WL;
  8651. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8652. end;
  8653. S_LQ:
  8654. begin
  8655. taicpu(hp1).opcode := A_MOV;
  8656. taicpu(hp1).opsize := S_L;
  8657. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8658. { In this instance, we need to break out because the
  8659. instruction is no longer MOVZX or MOVSXD }
  8660. Result := True;
  8661. Exit;
  8662. end;
  8663. else
  8664. ;
  8665. end;
  8666. {$endif x86_64}
  8667. Result := CompressInstructions;
  8668. Exit;
  8669. end;
  8670. end;
  8671. A_MOVZX:
  8672. begin
  8673. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8674. Break;
  8675. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8676. begin
  8677. if (InstrMax = -1) and
  8678. { Will return false if the second parameter isn't ThisReg
  8679. (can happen on -O2 and under) }
  8680. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8681. begin
  8682. { The two MOVZX instructions are adjacent, so remove the first one }
  8683. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8684. RemoveCurrentP(p);
  8685. Result := True;
  8686. Exit;
  8687. end;
  8688. Break;
  8689. end;
  8690. Result := CompressInstructions;
  8691. Exit;
  8692. end;
  8693. else
  8694. { This includes ADC, SBB and IDIV }
  8695. Break;
  8696. end;
  8697. if not CheckOverflowConditions then
  8698. Break;
  8699. { Contains highest index (so instruction count - 1) }
  8700. Inc(InstrMax);
  8701. if InstrMax > High(InstrList) then
  8702. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8703. InstrList[InstrMax] := taicpu(hp1);
  8704. end;
  8705. end;
  8706. {$pop}
  8707. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8708. var
  8709. hp1 : tai;
  8710. begin
  8711. Result:=false;
  8712. if (taicpu(p).ops >= 2) and
  8713. ((taicpu(p).oper[0]^.typ = top_const) or
  8714. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8715. (taicpu(p).oper[1]^.typ = top_reg) and
  8716. ((taicpu(p).ops = 2) or
  8717. ((taicpu(p).oper[2]^.typ = top_reg) and
  8718. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8719. GetLastInstruction(p,hp1) and
  8720. MatchInstruction(hp1,A_MOV,[]) and
  8721. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8722. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8723. begin
  8724. TransferUsedRegs(TmpUsedRegs);
  8725. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8726. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8727. { change
  8728. mov reg1,reg2
  8729. imul y,reg2 to imul y,reg1,reg2 }
  8730. begin
  8731. taicpu(p).ops := 3;
  8732. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8733. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8734. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8735. RemoveInstruction(hp1);
  8736. result:=true;
  8737. end;
  8738. end;
  8739. end;
  8740. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8741. var
  8742. ThisLabel: TAsmLabel;
  8743. begin
  8744. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8745. ThisLabel.decrefs;
  8746. taicpu(p).opcode := A_RET;
  8747. taicpu(p).is_jmp := false;
  8748. taicpu(p).ops := taicpu(ret_p).ops;
  8749. case taicpu(ret_p).ops of
  8750. 0:
  8751. taicpu(p).clearop(0);
  8752. 1:
  8753. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8754. else
  8755. internalerror(2016041301);
  8756. end;
  8757. { If the original label is now dead, it might turn out that the label
  8758. immediately follows p. As a result, everything beyond it, which will
  8759. be just some final register configuration and a RET instruction, is
  8760. now dead code. [Kit] }
  8761. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8762. running RemoveDeadCodeAfterJump for each RET instruction, because
  8763. this optimisation rarely happens and most RETs appear at the end of
  8764. routines where there is nothing that can be stripped. [Kit] }
  8765. if not ThisLabel.is_used then
  8766. RemoveDeadCodeAfterJump(p);
  8767. end;
  8768. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8769. var
  8770. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8771. Unconditional, PotentialModified: Boolean;
  8772. OperPtr: POper;
  8773. NewRef: TReference;
  8774. InstrList: array of taicpu;
  8775. InstrMax, Index: Integer;
  8776. const
  8777. {$ifdef DEBUG_AOPTCPU}
  8778. SNoFlags: shortstring = ' so the flags aren''t modified';
  8779. {$else DEBUG_AOPTCPU}
  8780. SNoFlags = '';
  8781. {$endif DEBUG_AOPTCPU}
  8782. begin
  8783. Result:=false;
  8784. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8785. begin
  8786. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8787. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8788. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8789. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8790. GetNextInstruction(hp1, hp2) and
  8791. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8792. { Change from: To:
  8793. set(C) %reg j(~C) label
  8794. test %reg,%reg/cmp $0,%reg
  8795. je label
  8796. set(C) %reg j(C) label
  8797. test %reg,%reg/cmp $0,%reg
  8798. jne label
  8799. (Also do something similar with sete/setne instead of je/jne)
  8800. }
  8801. begin
  8802. { Before we do anything else, we need to check the instructions
  8803. in between SETcc and TEST to make sure they don't modify the
  8804. FLAGS register - if -O2 or under, there won't be any
  8805. instructions between SET and TEST }
  8806. TransferUsedRegs(TmpUsedRegs);
  8807. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8808. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8809. begin
  8810. next := p;
  8811. SetLength(InstrList, 0);
  8812. InstrMax := -1;
  8813. PotentialModified := False;
  8814. { Make a note of every instruction that modifies the FLAGS
  8815. register }
  8816. while GetNextInstruction(next, next) and (next <> hp1) do
  8817. begin
  8818. if next.typ <> ait_instruction then
  8819. { GetNextInstructionUsingReg should have returned False }
  8820. InternalError(2021051701);
  8821. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8822. begin
  8823. case taicpu(next).opcode of
  8824. A_SETcc,
  8825. A_CMOVcc,
  8826. A_Jcc:
  8827. begin
  8828. if PotentialModified then
  8829. { Not safe because the flags were modified earlier }
  8830. Exit
  8831. else
  8832. { Condition is the same as the initial SETcc, so this is safe
  8833. (don't add to instruction list though) }
  8834. Continue;
  8835. end;
  8836. A_ADD:
  8837. begin
  8838. if (taicpu(next).opsize = S_B) or
  8839. { LEA doesn't support 8-bit operands }
  8840. (taicpu(next).oper[1]^.typ <> top_reg) or
  8841. { Must write to a register }
  8842. (taicpu(next).oper[0]^.typ = top_ref) then
  8843. { Require a constant or a register }
  8844. Exit;
  8845. PotentialModified := True;
  8846. end;
  8847. A_SUB:
  8848. begin
  8849. if (taicpu(next).opsize = S_B) or
  8850. { LEA doesn't support 8-bit operands }
  8851. (taicpu(next).oper[1]^.typ <> top_reg) or
  8852. { Must write to a register }
  8853. (taicpu(next).oper[0]^.typ <> top_const) or
  8854. (taicpu(next).oper[0]^.val = $80000000) then
  8855. { Can't subtract a register with LEA - also
  8856. check that the value isn't -2^31, as this
  8857. can't be negated }
  8858. Exit;
  8859. PotentialModified := True;
  8860. end;
  8861. A_SAL,
  8862. A_SHL:
  8863. begin
  8864. if (taicpu(next).opsize = S_B) or
  8865. { LEA doesn't support 8-bit operands }
  8866. (taicpu(next).oper[1]^.typ <> top_reg) or
  8867. { Must write to a register }
  8868. (taicpu(next).oper[0]^.typ <> top_const) or
  8869. (taicpu(next).oper[0]^.val < 0) or
  8870. (taicpu(next).oper[0]^.val > 3) then
  8871. Exit;
  8872. PotentialModified := True;
  8873. end;
  8874. A_IMUL:
  8875. begin
  8876. if (taicpu(next).ops <> 3) or
  8877. (taicpu(next).oper[1]^.typ <> top_reg) or
  8878. { Must write to a register }
  8879. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8880. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8881. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8882. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8883. Exit
  8884. else
  8885. PotentialModified := True;
  8886. end;
  8887. else
  8888. { Don't know how to change this, so abort }
  8889. Exit;
  8890. end;
  8891. { Contains highest index (so instruction count - 1) }
  8892. Inc(InstrMax);
  8893. if InstrMax > High(InstrList) then
  8894. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8895. InstrList[InstrMax] := taicpu(next);
  8896. end;
  8897. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8898. end;
  8899. if not Assigned(next) or (next <> hp1) then
  8900. { It should be equal to hp1 }
  8901. InternalError(2021051702);
  8902. { Cycle through each instruction and check to see if we can
  8903. change them to versions that don't modify the flags }
  8904. if (InstrMax >= 0) then
  8905. begin
  8906. for Index := 0 to InstrMax do
  8907. case InstrList[Index].opcode of
  8908. A_ADD:
  8909. begin
  8910. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8911. InstrList[Index].opcode := A_LEA;
  8912. reference_reset(NewRef, 1, []);
  8913. NewRef.base := InstrList[Index].oper[1]^.reg;
  8914. if InstrList[Index].oper[0]^.typ = top_reg then
  8915. begin
  8916. NewRef.index := InstrList[Index].oper[0]^.reg;
  8917. NewRef.scalefactor := 1;
  8918. end
  8919. else
  8920. NewRef.offset := InstrList[Index].oper[0]^.val;
  8921. InstrList[Index].loadref(0, NewRef);
  8922. end;
  8923. A_SUB:
  8924. begin
  8925. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8926. InstrList[Index].opcode := A_LEA;
  8927. reference_reset(NewRef, 1, []);
  8928. NewRef.base := InstrList[Index].oper[1]^.reg;
  8929. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8930. InstrList[Index].loadref(0, NewRef);
  8931. end;
  8932. A_SHL,
  8933. A_SAL:
  8934. begin
  8935. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8936. InstrList[Index].opcode := A_LEA;
  8937. reference_reset(NewRef, 1, []);
  8938. NewRef.index := InstrList[Index].oper[1]^.reg;
  8939. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8940. InstrList[Index].loadref(0, NewRef);
  8941. end;
  8942. A_IMUL:
  8943. begin
  8944. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8945. InstrList[Index].opcode := A_LEA;
  8946. reference_reset(NewRef, 1, []);
  8947. NewRef.index := InstrList[Index].oper[1]^.reg;
  8948. case InstrList[Index].oper[0]^.val of
  8949. 2, 4, 8:
  8950. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8951. else {3, 5 and 9}
  8952. begin
  8953. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8954. NewRef.base := InstrList[Index].oper[1]^.reg;
  8955. end;
  8956. end;
  8957. InstrList[Index].loadref(0, NewRef);
  8958. end;
  8959. else
  8960. InternalError(2021051710);
  8961. end;
  8962. end;
  8963. { Mark the FLAGS register as used across this whole block }
  8964. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8965. end;
  8966. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8967. JumpC := taicpu(hp2).condition;
  8968. Unconditional := False;
  8969. if conditions_equal(JumpC, C_E) then
  8970. SetC := inverse_cond(taicpu(p).condition)
  8971. else if conditions_equal(JumpC, C_NE) then
  8972. SetC := taicpu(p).condition
  8973. else
  8974. { We've got something weird here (and inefficent) }
  8975. begin
  8976. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8977. SetC := C_NONE;
  8978. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8979. if condition_in(C_AE, JumpC) then
  8980. Unconditional := True
  8981. else
  8982. { Not sure what to do with this jump - drop out }
  8983. Exit;
  8984. end;
  8985. RemoveInstruction(hp1);
  8986. if Unconditional then
  8987. MakeUnconditional(taicpu(hp2))
  8988. else
  8989. begin
  8990. if SetC = C_NONE then
  8991. InternalError(2018061402);
  8992. taicpu(hp2).SetCondition(SetC);
  8993. end;
  8994. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8995. TmpUsedRegs }
  8996. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8997. begin
  8998. RemoveCurrentp(p, hp2);
  8999. if taicpu(hp2).opcode = A_SETcc then
  9000. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9001. else
  9002. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9003. end
  9004. else
  9005. if taicpu(hp2).opcode = A_SETcc then
  9006. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9007. else
  9008. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9009. Result := True;
  9010. end
  9011. else if
  9012. { Make sure the instructions are adjacent }
  9013. (
  9014. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9015. GetNextInstruction(p, hp1)
  9016. ) and
  9017. MatchInstruction(hp1, A_MOV, [S_B]) and
  9018. { Writing to memory is allowed }
  9019. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9020. begin
  9021. {
  9022. Watch out for sequences such as:
  9023. set(c)b %regb
  9024. movb %regb,(ref)
  9025. movb $0,1(ref)
  9026. movb $0,2(ref)
  9027. movb $0,3(ref)
  9028. Much more efficient to turn it into:
  9029. movl $0,%regl
  9030. set(c)b %regb
  9031. movl %regl,(ref)
  9032. Or:
  9033. set(c)b %regb
  9034. movzbl %regb,%regl
  9035. movl %regl,(ref)
  9036. }
  9037. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9038. GetNextInstruction(hp1, hp2) and
  9039. MatchInstruction(hp2, A_MOV, [S_B]) and
  9040. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9041. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9042. begin
  9043. { Don't do anything else except set Result to True }
  9044. end
  9045. else
  9046. begin
  9047. if taicpu(p).oper[0]^.typ = top_reg then
  9048. begin
  9049. TransferUsedRegs(TmpUsedRegs);
  9050. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9051. end;
  9052. { If it's not a register, it's a memory address }
  9053. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9054. begin
  9055. { Even if the register is still in use, we can minimise the
  9056. pipeline stall by changing the MOV into another SETcc. }
  9057. taicpu(hp1).opcode := A_SETcc;
  9058. taicpu(hp1).condition := taicpu(p).condition;
  9059. if taicpu(hp1).oper[1]^.typ = top_ref then
  9060. begin
  9061. { Swapping the operand pointers like this is probably a
  9062. bit naughty, but it is far faster than using loadoper
  9063. to transfer the reference from oper[1] to oper[0] if
  9064. you take into account the extra procedure calls and
  9065. the memory allocation and deallocation required }
  9066. OperPtr := taicpu(hp1).oper[1];
  9067. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9068. taicpu(hp1).oper[0] := OperPtr;
  9069. end
  9070. else
  9071. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9072. taicpu(hp1).clearop(1);
  9073. taicpu(hp1).ops := 1;
  9074. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9075. end
  9076. else
  9077. begin
  9078. if taicpu(hp1).oper[1]^.typ = top_reg then
  9079. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9080. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9081. RemoveInstruction(hp1);
  9082. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9083. end
  9084. end;
  9085. Result := True;
  9086. end;
  9087. end;
  9088. end;
  9089. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9090. var
  9091. hp1: tai;
  9092. Count: Integer;
  9093. OrigLabel: TAsmLabel;
  9094. begin
  9095. result := False;
  9096. { Sometimes, the optimisations below can permit this }
  9097. RemoveDeadCodeAfterJump(p);
  9098. 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
  9099. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9100. begin
  9101. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9102. { Also a side-effect of optimisations }
  9103. if CollapseZeroDistJump(p, OrigLabel) then
  9104. begin
  9105. Result := True;
  9106. Exit;
  9107. end;
  9108. hp1 := GetLabelWithSym(OrigLabel);
  9109. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9110. begin
  9111. case taicpu(hp1).opcode of
  9112. A_RET:
  9113. {
  9114. change
  9115. jmp .L1
  9116. ...
  9117. .L1:
  9118. ret
  9119. into
  9120. ret
  9121. }
  9122. begin
  9123. ConvertJumpToRET(p, hp1);
  9124. result:=true;
  9125. end;
  9126. { Check any kind of direct assignment instruction }
  9127. A_MOV,
  9128. A_MOVD,
  9129. A_MOVQ,
  9130. A_MOVSX,
  9131. {$ifdef x86_64}
  9132. A_MOVSXD,
  9133. {$endif x86_64}
  9134. A_MOVZX,
  9135. A_MOVAPS,
  9136. A_MOVUPS,
  9137. A_MOVSD,
  9138. A_MOVAPD,
  9139. A_MOVUPD,
  9140. A_MOVDQA,
  9141. A_MOVDQU,
  9142. A_VMOVSS,
  9143. A_VMOVAPS,
  9144. A_VMOVUPS,
  9145. A_VMOVSD,
  9146. A_VMOVAPD,
  9147. A_VMOVUPD,
  9148. A_VMOVDQA,
  9149. A_VMOVDQU:
  9150. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9151. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9152. begin
  9153. Result := True;
  9154. Exit;
  9155. end;
  9156. else
  9157. ;
  9158. end;
  9159. end;
  9160. end;
  9161. end;
  9162. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9163. begin
  9164. CanBeCMOV:=assigned(p) and
  9165. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9166. { we can't use cmov ref,reg because
  9167. ref could be nil and cmov still throws an exception
  9168. if ref=nil but the mov isn't done (FK)
  9169. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9170. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9171. }
  9172. (taicpu(p).oper[1]^.typ = top_reg) and
  9173. (
  9174. (taicpu(p).oper[0]^.typ = top_reg) or
  9175. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9176. it is not expected that this can cause a seg. violation }
  9177. (
  9178. (taicpu(p).oper[0]^.typ = top_ref) and
  9179. IsRefSafe(taicpu(p).oper[0]^.ref)
  9180. )
  9181. );
  9182. end;
  9183. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9184. var
  9185. hp1,hp2: tai;
  9186. {$ifndef i8086}
  9187. hp3,hp4,hpmov2, hp5: tai;
  9188. l : Longint;
  9189. condition : TAsmCond;
  9190. {$endif i8086}
  9191. carryadd_opcode : TAsmOp;
  9192. symbol: TAsmSymbol;
  9193. increg, tmpreg: TRegister;
  9194. begin
  9195. result:=false;
  9196. if GetNextInstruction(p,hp1) then
  9197. begin
  9198. if (hp1.typ=ait_label) then
  9199. begin
  9200. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9201. Exit;
  9202. end
  9203. else if (hp1.typ<>ait_instruction) then
  9204. Exit;
  9205. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9206. if (
  9207. (
  9208. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9209. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9210. (Taicpu(hp1).oper[0]^.val=1)
  9211. ) or
  9212. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9213. ) and
  9214. GetNextInstruction(hp1,hp2) and
  9215. SkipAligns(hp2, hp2) and
  9216. (hp2.typ = ait_label) and
  9217. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9218. { jb @@1 cmc
  9219. inc/dec operand --> adc/sbb operand,0
  9220. @@1:
  9221. ... and ...
  9222. jnb @@1
  9223. inc/dec operand --> adc/sbb operand,0
  9224. @@1: }
  9225. begin
  9226. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9227. begin
  9228. case taicpu(hp1).opcode of
  9229. A_INC,
  9230. A_ADD:
  9231. carryadd_opcode:=A_ADC;
  9232. A_DEC,
  9233. A_SUB:
  9234. carryadd_opcode:=A_SBB;
  9235. else
  9236. InternalError(2021011001);
  9237. end;
  9238. Taicpu(p).clearop(0);
  9239. Taicpu(p).ops:=0;
  9240. Taicpu(p).is_jmp:=false;
  9241. Taicpu(p).opcode:=A_CMC;
  9242. Taicpu(p).condition:=C_NONE;
  9243. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9244. Taicpu(hp1).ops:=2;
  9245. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9246. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9247. else
  9248. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9249. Taicpu(hp1).loadconst(0,0);
  9250. Taicpu(hp1).opcode:=carryadd_opcode;
  9251. result:=true;
  9252. exit;
  9253. end
  9254. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9255. begin
  9256. case taicpu(hp1).opcode of
  9257. A_INC,
  9258. A_ADD:
  9259. carryadd_opcode:=A_ADC;
  9260. A_DEC,
  9261. A_SUB:
  9262. carryadd_opcode:=A_SBB;
  9263. else
  9264. InternalError(2021011002);
  9265. end;
  9266. Taicpu(hp1).ops:=2;
  9267. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9268. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9269. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9270. else
  9271. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9272. Taicpu(hp1).loadconst(0,0);
  9273. Taicpu(hp1).opcode:=carryadd_opcode;
  9274. RemoveCurrentP(p, hp1);
  9275. result:=true;
  9276. exit;
  9277. end
  9278. {
  9279. jcc @@1 setcc tmpreg
  9280. inc/dec/add/sub operand -> (movzx tmpreg)
  9281. @@1: add/sub tmpreg,operand
  9282. While this increases code size slightly, it makes the code much faster if the
  9283. jump is unpredictable
  9284. }
  9285. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9286. begin
  9287. { search for an available register which is volatile }
  9288. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9289. if increg <> NR_NO then
  9290. begin
  9291. { We don't need to check if tmpreg is in hp1 or not, because
  9292. it will be marked as in use at p (if not, this is
  9293. indictive of a compiler bug). }
  9294. TAsmLabel(symbol).decrefs;
  9295. Taicpu(p).clearop(0);
  9296. Taicpu(p).ops:=1;
  9297. Taicpu(p).is_jmp:=false;
  9298. Taicpu(p).opcode:=A_SETcc;
  9299. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9300. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9301. Taicpu(p).loadreg(0,increg);
  9302. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9303. begin
  9304. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9305. R_SUBW:
  9306. begin
  9307. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9308. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9309. end;
  9310. R_SUBD:
  9311. begin
  9312. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9313. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9314. end;
  9315. {$ifdef x86_64}
  9316. R_SUBQ:
  9317. begin
  9318. { MOVZX doesn't have a 64-bit variant, because
  9319. the 32-bit version implicitly zeroes the
  9320. upper 32-bits of the destination register }
  9321. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9322. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9323. setsubreg(tmpreg, R_SUBQ);
  9324. end;
  9325. {$endif x86_64}
  9326. else
  9327. Internalerror(2020030601);
  9328. end;
  9329. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9330. asml.InsertAfter(hp2,p);
  9331. end
  9332. else
  9333. tmpreg := increg;
  9334. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9335. begin
  9336. Taicpu(hp1).ops:=2;
  9337. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9338. end;
  9339. Taicpu(hp1).loadreg(0,tmpreg);
  9340. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9341. Result := True;
  9342. { p is no longer a Jcc instruction, so exit }
  9343. Exit;
  9344. end;
  9345. end;
  9346. end;
  9347. { Detect the following:
  9348. jmp<cond> @Lbl1
  9349. jmp @Lbl2
  9350. ...
  9351. @Lbl1:
  9352. ret
  9353. Change to:
  9354. jmp<inv_cond> @Lbl2
  9355. ret
  9356. }
  9357. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9358. begin
  9359. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9360. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9361. MatchInstruction(hp2,A_RET,[S_NO]) then
  9362. begin
  9363. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9364. { Change label address to that of the unconditional jump }
  9365. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9366. TAsmLabel(symbol).DecRefs;
  9367. taicpu(hp1).opcode := A_RET;
  9368. taicpu(hp1).is_jmp := false;
  9369. taicpu(hp1).ops := taicpu(hp2).ops;
  9370. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9371. case taicpu(hp2).ops of
  9372. 0:
  9373. taicpu(hp1).clearop(0);
  9374. 1:
  9375. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9376. else
  9377. internalerror(2016041302);
  9378. end;
  9379. end;
  9380. {$ifndef i8086}
  9381. end
  9382. {
  9383. convert
  9384. j<c> .L1
  9385. mov 1,reg
  9386. jmp .L2
  9387. .L1
  9388. mov 0,reg
  9389. .L2
  9390. into
  9391. mov 0,reg
  9392. set<not(c)> reg
  9393. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9394. would destroy the flag contents
  9395. }
  9396. else if MatchInstruction(hp1,A_MOV,[]) and
  9397. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9398. {$ifdef i386}
  9399. (
  9400. { Under i386, ESI, EDI, EBP and ESP
  9401. don't have an 8-bit representation }
  9402. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9403. ) and
  9404. {$endif i386}
  9405. (taicpu(hp1).oper[0]^.val=1) and
  9406. GetNextInstruction(hp1,hp2) and
  9407. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9408. GetNextInstruction(hp2,hp3) and
  9409. { skip align }
  9410. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9411. (hp3.typ=ait_label) and
  9412. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9413. (tai_label(hp3).labsym.getrefs=1) and
  9414. GetNextInstruction(hp3,hp4) and
  9415. MatchInstruction(hp4,A_MOV,[]) and
  9416. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9417. (taicpu(hp4).oper[0]^.val=0) and
  9418. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9419. GetNextInstruction(hp4,hp5) and
  9420. (hp5.typ=ait_label) and
  9421. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9422. (tai_label(hp5).labsym.getrefs=1) then
  9423. begin
  9424. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9425. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9426. { remove last label }
  9427. RemoveInstruction(hp5);
  9428. { remove second label }
  9429. RemoveInstruction(hp3);
  9430. { if align is present remove it }
  9431. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9432. RemoveInstruction(hp3);
  9433. { remove jmp }
  9434. RemoveInstruction(hp2);
  9435. if taicpu(hp1).opsize=S_B then
  9436. RemoveInstruction(hp1)
  9437. else
  9438. taicpu(hp1).loadconst(0,0);
  9439. taicpu(hp4).opcode:=A_SETcc;
  9440. taicpu(hp4).opsize:=S_B;
  9441. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9442. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9443. taicpu(hp4).opercnt:=1;
  9444. taicpu(hp4).ops:=1;
  9445. taicpu(hp4).freeop(1);
  9446. RemoveCurrentP(p);
  9447. Result:=true;
  9448. exit;
  9449. end
  9450. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9451. begin
  9452. { check for
  9453. jCC xxx
  9454. <several movs>
  9455. xxx:
  9456. Also spot:
  9457. Jcc xxx
  9458. <several movs>
  9459. jmp xxx
  9460. Change to:
  9461. <several cmovs with inverted condition>
  9462. jmp xxx
  9463. }
  9464. l:=0;
  9465. while assigned(hp1) and
  9466. CanBeCMOV(hp1) and
  9467. { stop on labels }
  9468. not(hp1.typ=ait_label) do
  9469. begin
  9470. inc(l);
  9471. hp5 := hp1;
  9472. GetNextInstruction(hp1,hp1);
  9473. end;
  9474. if assigned(hp1) then
  9475. begin
  9476. TransferUsedRegs(TmpUsedRegs);
  9477. if (
  9478. MatchInstruction(hp1, A_JMP, []) and
  9479. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9480. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9481. ) or
  9482. FindLabel(tasmlabel(symbol),hp1) then
  9483. begin
  9484. if (l<=4) and (l>0) then
  9485. begin
  9486. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9487. condition:=inverse_cond(taicpu(p).condition);
  9488. UpdateUsedRegs(tai(p.next));
  9489. GetNextInstruction(p,hp1);
  9490. repeat
  9491. if not Assigned(hp1) then
  9492. InternalError(2018062900);
  9493. taicpu(hp1).opcode:=A_CMOVcc;
  9494. taicpu(hp1).condition:=condition;
  9495. UpdateUsedRegs(tai(hp1.next));
  9496. GetNextInstruction(hp1,hp1);
  9497. until not(CanBeCMOV(hp1));
  9498. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9499. hp2 := hp1;
  9500. repeat
  9501. if not Assigned(hp2) then
  9502. InternalError(2018062910);
  9503. case hp2.typ of
  9504. ait_label:
  9505. { What we expected - break out of the loop (it won't be a dead label at the top of
  9506. a cluster because that was optimised at an earlier stage) }
  9507. Break;
  9508. ait_align:
  9509. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9510. begin
  9511. hp2 := tai(hp2.Next);
  9512. Continue;
  9513. end;
  9514. ait_instruction:
  9515. begin
  9516. if taicpu(hp2).opcode<>A_JMP then
  9517. InternalError(2018062912);
  9518. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9519. Break;
  9520. end
  9521. else
  9522. begin
  9523. { Might be a comment or temporary allocation entry }
  9524. if not (hp2.typ in SkipInstr) then
  9525. InternalError(2018062911);
  9526. hp2 := tai(hp2.Next);
  9527. Continue;
  9528. end;
  9529. end;
  9530. until False;
  9531. { Now we can safely decrement the reference count }
  9532. tasmlabel(symbol).decrefs;
  9533. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9534. { Remove the original jump }
  9535. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9536. if hp2.typ=ait_instruction then
  9537. begin
  9538. p:=hp2;
  9539. Result:=True;
  9540. end
  9541. else
  9542. begin
  9543. UpdateUsedRegs(tai(hp2.next));
  9544. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9545. { Remove the label if this is its final reference }
  9546. if (tasmlabel(symbol).getrefs=0) then
  9547. StripLabelFast(hp1);
  9548. end;
  9549. exit;
  9550. end;
  9551. end
  9552. else
  9553. begin
  9554. { check further for
  9555. jCC xxx
  9556. <several movs 1>
  9557. jmp yyy
  9558. xxx:
  9559. <several movs 2>
  9560. yyy:
  9561. }
  9562. { hp2 points to jmp yyy }
  9563. hp2:=hp1;
  9564. { skip hp1 to xxx (or an align right before it) }
  9565. GetNextInstruction(hp1, hp1);
  9566. if assigned(hp2) and
  9567. assigned(hp1) and
  9568. (l<=3) and
  9569. (hp2.typ=ait_instruction) and
  9570. (taicpu(hp2).is_jmp) and
  9571. (taicpu(hp2).condition=C_None) and
  9572. { real label and jump, no further references to the
  9573. label are allowed }
  9574. (tasmlabel(symbol).getrefs=1) and
  9575. FindLabel(tasmlabel(symbol),hp1) then
  9576. begin
  9577. l:=0;
  9578. { skip hp1 to <several moves 2> }
  9579. if (hp1.typ = ait_align) then
  9580. GetNextInstruction(hp1, hp1);
  9581. GetNextInstruction(hp1, hpmov2);
  9582. hp1 := hpmov2;
  9583. while assigned(hp1) and
  9584. CanBeCMOV(hp1) do
  9585. begin
  9586. inc(l);
  9587. hp5 := hp1;
  9588. GetNextInstruction(hp1, hp1);
  9589. end;
  9590. { hp1 points to yyy (or an align right before it) }
  9591. hp3 := hp1;
  9592. if assigned(hp1) and
  9593. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9594. begin
  9595. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9596. condition:=inverse_cond(taicpu(p).condition);
  9597. UpdateUsedRegs(tai(p.next));
  9598. GetNextInstruction(p,hp1);
  9599. repeat
  9600. taicpu(hp1).opcode:=A_CMOVcc;
  9601. taicpu(hp1).condition:=condition;
  9602. UpdateUsedRegs(tai(hp1.next));
  9603. GetNextInstruction(hp1,hp1);
  9604. until not(assigned(hp1)) or
  9605. not(CanBeCMOV(hp1));
  9606. condition:=inverse_cond(condition);
  9607. if GetLastInstruction(hpmov2,hp1) then
  9608. UpdateUsedRegs(tai(hp1.next));
  9609. hp1 := hpmov2;
  9610. { hp1 is now at <several movs 2> }
  9611. while Assigned(hp1) and CanBeCMOV(hp1) do
  9612. begin
  9613. taicpu(hp1).opcode:=A_CMOVcc;
  9614. taicpu(hp1).condition:=condition;
  9615. UpdateUsedRegs(tai(hp1.next));
  9616. GetNextInstruction(hp1,hp1);
  9617. end;
  9618. hp1 := p;
  9619. { Get first instruction after label }
  9620. UpdateUsedRegs(tai(hp3.next));
  9621. GetNextInstruction(hp3, p);
  9622. if assigned(p) and (hp3.typ = ait_align) then
  9623. GetNextInstruction(p, p);
  9624. { Don't dereference yet, as doing so will cause
  9625. GetNextInstruction to skip the label and
  9626. optional align marker. [Kit] }
  9627. GetNextInstruction(hp2, hp4);
  9628. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9629. { remove jCC }
  9630. RemoveInstruction(hp1);
  9631. { Now we can safely decrement it }
  9632. tasmlabel(symbol).decrefs;
  9633. { Remove label xxx (it will have a ref of zero due to the initial check }
  9634. StripLabelFast(hp4);
  9635. { remove jmp }
  9636. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9637. RemoveInstruction(hp2);
  9638. { As before, now we can safely decrement it }
  9639. tasmlabel(symbol).decrefs;
  9640. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9641. if tasmlabel(symbol).getrefs = 0 then
  9642. StripLabelFast(hp3);
  9643. if Assigned(p) then
  9644. result:=true;
  9645. exit;
  9646. end;
  9647. end;
  9648. end;
  9649. end;
  9650. {$endif i8086}
  9651. end;
  9652. end;
  9653. end;
  9654. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9655. var
  9656. hp1,hp2,hp3: tai;
  9657. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9658. NewSize: TOpSize;
  9659. NewRegSize: TSubRegister;
  9660. Limit: TCgInt;
  9661. SwapOper: POper;
  9662. begin
  9663. result:=false;
  9664. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9665. GetNextInstruction(p,hp1) and
  9666. (hp1.typ = ait_instruction);
  9667. if reg_and_hp1_is_instr and
  9668. (
  9669. (taicpu(hp1).opcode <> A_LEA) or
  9670. { If the LEA instruction can be converted into an arithmetic instruction,
  9671. it may be possible to then fold it. }
  9672. (
  9673. { If the flags register is in use, don't change the instruction
  9674. to an ADD otherwise this will scramble the flags. [Kit] }
  9675. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9676. ConvertLEA(taicpu(hp1))
  9677. )
  9678. ) and
  9679. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9680. GetNextInstruction(hp1,hp2) and
  9681. MatchInstruction(hp2,A_MOV,[]) and
  9682. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9683. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9684. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9685. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9686. {$ifdef i386}
  9687. { not all registers have byte size sub registers on i386 }
  9688. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9689. {$endif i386}
  9690. (((taicpu(hp1).ops=2) and
  9691. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9692. ((taicpu(hp1).ops=1) and
  9693. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9694. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9695. begin
  9696. { change movsX/movzX reg/ref, reg2
  9697. add/sub/or/... reg3/$const, reg2
  9698. mov reg2 reg/ref
  9699. to add/sub/or/... reg3/$const, reg/ref }
  9700. { by example:
  9701. movswl %si,%eax movswl %si,%eax p
  9702. decl %eax addl %edx,%eax hp1
  9703. movw %ax,%si movw %ax,%si hp2
  9704. ->
  9705. movswl %si,%eax movswl %si,%eax p
  9706. decw %eax addw %edx,%eax hp1
  9707. movw %ax,%si movw %ax,%si hp2
  9708. }
  9709. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9710. {
  9711. ->
  9712. movswl %si,%eax movswl %si,%eax p
  9713. decw %si addw %dx,%si hp1
  9714. movw %ax,%si movw %ax,%si hp2
  9715. }
  9716. case taicpu(hp1).ops of
  9717. 1:
  9718. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9719. 2:
  9720. begin
  9721. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9722. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9723. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9724. end;
  9725. else
  9726. internalerror(2008042702);
  9727. end;
  9728. {
  9729. ->
  9730. decw %si addw %dx,%si p
  9731. }
  9732. DebugMsg(SPeepholeOptimization + 'var3',p);
  9733. RemoveCurrentP(p, hp1);
  9734. RemoveInstruction(hp2);
  9735. Result := True;
  9736. Exit;
  9737. end;
  9738. if reg_and_hp1_is_instr and
  9739. (taicpu(hp1).opcode = A_MOV) and
  9740. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9741. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9742. {$ifdef x86_64}
  9743. { check for implicit extension to 64 bit }
  9744. or
  9745. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9746. (taicpu(hp1).opsize=S_Q) and
  9747. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9748. )
  9749. {$endif x86_64}
  9750. )
  9751. then
  9752. begin
  9753. { change
  9754. movx %reg1,%reg2
  9755. mov %reg2,%reg3
  9756. dealloc %reg2
  9757. into
  9758. movx %reg,%reg3
  9759. }
  9760. TransferUsedRegs(TmpUsedRegs);
  9761. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9762. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9763. begin
  9764. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9765. {$ifdef x86_64}
  9766. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9767. (taicpu(hp1).opsize=S_Q) then
  9768. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9769. else
  9770. {$endif x86_64}
  9771. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9772. RemoveInstruction(hp1);
  9773. Result := True;
  9774. Exit;
  9775. end;
  9776. end;
  9777. if reg_and_hp1_is_instr and
  9778. ((taicpu(hp1).opcode=A_MOV) or
  9779. (taicpu(hp1).opcode=A_ADD) or
  9780. (taicpu(hp1).opcode=A_SUB) or
  9781. (taicpu(hp1).opcode=A_CMP) or
  9782. (taicpu(hp1).opcode=A_OR) or
  9783. (taicpu(hp1).opcode=A_XOR) or
  9784. (taicpu(hp1).opcode=A_AND)
  9785. ) and
  9786. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9787. begin
  9788. AndTest := (taicpu(hp1).opcode=A_AND) and
  9789. GetNextInstruction(hp1, hp2) and
  9790. (hp2.typ = ait_instruction) and
  9791. (
  9792. (
  9793. (taicpu(hp2).opcode=A_TEST) and
  9794. (
  9795. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9796. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9797. (
  9798. { If the AND and TEST instructions share a constant, this is also valid }
  9799. (taicpu(hp1).oper[0]^.typ = top_const) and
  9800. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9801. )
  9802. ) and
  9803. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9804. ) or
  9805. (
  9806. (taicpu(hp2).opcode=A_CMP) and
  9807. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9808. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9809. )
  9810. );
  9811. { change
  9812. movx (oper),%reg2
  9813. and $x,%reg2
  9814. test %reg2,%reg2
  9815. dealloc %reg2
  9816. into
  9817. op %reg1,%reg3
  9818. if the second op accesses only the bits stored in reg1
  9819. }
  9820. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9821. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9822. (taicpu(hp1).oper[0]^.typ = top_const) and
  9823. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9824. AndTest then
  9825. begin
  9826. { Check if the AND constant is in range }
  9827. case taicpu(p).opsize of
  9828. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9829. begin
  9830. NewSize := S_B;
  9831. Limit := $FF;
  9832. end;
  9833. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9834. begin
  9835. NewSize := S_W;
  9836. Limit := $FFFF;
  9837. end;
  9838. {$ifdef x86_64}
  9839. S_LQ:
  9840. begin
  9841. NewSize := S_L;
  9842. Limit := $FFFFFFFF;
  9843. end;
  9844. {$endif x86_64}
  9845. else
  9846. InternalError(2021120303);
  9847. end;
  9848. if (
  9849. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9850. { Check for negative operands }
  9851. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9852. ) and
  9853. GetNextInstruction(hp2,hp3) and
  9854. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9855. (taicpu(hp3).condition in [C_E,C_NE]) then
  9856. begin
  9857. TransferUsedRegs(TmpUsedRegs);
  9858. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9859. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9860. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9861. begin
  9862. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9863. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9864. taicpu(hp1).opcode := A_TEST;
  9865. taicpu(hp1).opsize := NewSize;
  9866. RemoveInstruction(hp2);
  9867. RemoveCurrentP(p, hp1);
  9868. Result:=true;
  9869. exit;
  9870. end;
  9871. end;
  9872. end;
  9873. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9874. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9875. (taicpu(hp1).opsize=S_B)) or
  9876. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9877. (taicpu(hp1).opsize=S_W))
  9878. {$ifdef x86_64}
  9879. or ((taicpu(p).opsize=S_LQ) and
  9880. (taicpu(hp1).opsize=S_L))
  9881. {$endif x86_64}
  9882. ) and
  9883. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9884. begin
  9885. { change
  9886. movx %reg1,%reg2
  9887. op %reg2,%reg3
  9888. dealloc %reg2
  9889. into
  9890. op %reg1,%reg3
  9891. if the second op accesses only the bits stored in reg1
  9892. }
  9893. TransferUsedRegs(TmpUsedRegs);
  9894. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9895. if AndTest then
  9896. begin
  9897. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9898. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9899. end
  9900. else
  9901. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9902. if not RegUsed then
  9903. begin
  9904. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9905. if taicpu(p).oper[0]^.typ=top_reg then
  9906. begin
  9907. case taicpu(hp1).opsize of
  9908. S_B:
  9909. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9910. S_W:
  9911. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9912. S_L:
  9913. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9914. else
  9915. Internalerror(2020102301);
  9916. end;
  9917. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9918. end
  9919. else
  9920. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9921. RemoveCurrentP(p);
  9922. if AndTest then
  9923. RemoveInstruction(hp2);
  9924. result:=true;
  9925. exit;
  9926. end;
  9927. end
  9928. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9929. (
  9930. { Bitwise operations only }
  9931. (taicpu(hp1).opcode=A_AND) or
  9932. (taicpu(hp1).opcode=A_TEST) or
  9933. (
  9934. (taicpu(hp1).oper[0]^.typ = top_const) and
  9935. (
  9936. (taicpu(hp1).opcode=A_OR) or
  9937. (taicpu(hp1).opcode=A_XOR)
  9938. )
  9939. )
  9940. ) and
  9941. (
  9942. (taicpu(hp1).oper[0]^.typ = top_const) or
  9943. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9944. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9945. ) then
  9946. begin
  9947. { change
  9948. movx %reg2,%reg2
  9949. op const,%reg2
  9950. into
  9951. op const,%reg2 (smaller version)
  9952. movx %reg2,%reg2
  9953. also change
  9954. movx %reg1,%reg2
  9955. and/test (oper),%reg2
  9956. dealloc %reg2
  9957. into
  9958. and/test (oper),%reg1
  9959. }
  9960. case taicpu(p).opsize of
  9961. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9962. begin
  9963. NewSize := S_B;
  9964. NewRegSize := R_SUBL;
  9965. Limit := $FF;
  9966. end;
  9967. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9968. begin
  9969. NewSize := S_W;
  9970. NewRegSize := R_SUBW;
  9971. Limit := $FFFF;
  9972. end;
  9973. {$ifdef x86_64}
  9974. S_LQ:
  9975. begin
  9976. NewSize := S_L;
  9977. NewRegSize := R_SUBD;
  9978. Limit := $FFFFFFFF;
  9979. end;
  9980. {$endif x86_64}
  9981. else
  9982. Internalerror(2021120302);
  9983. end;
  9984. TransferUsedRegs(TmpUsedRegs);
  9985. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9986. if AndTest then
  9987. begin
  9988. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9989. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9990. end
  9991. else
  9992. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9993. if
  9994. (
  9995. (taicpu(p).opcode = A_MOVZX) and
  9996. (
  9997. (taicpu(hp1).opcode=A_AND) or
  9998. (taicpu(hp1).opcode=A_TEST)
  9999. ) and
  10000. not (
  10001. { If both are references, then the final instruction will have
  10002. both operands as references, which is not allowed }
  10003. (taicpu(p).oper[0]^.typ = top_ref) and
  10004. (taicpu(hp1).oper[0]^.typ = top_ref)
  10005. ) and
  10006. not RegUsed
  10007. ) or
  10008. (
  10009. (
  10010. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10011. not RegUsed
  10012. ) and
  10013. (taicpu(p).oper[0]^.typ = top_reg) and
  10014. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10015. (taicpu(hp1).oper[0]^.typ = top_const) and
  10016. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10017. ) then
  10018. begin
  10019. {$if defined(i386) or defined(i8086)}
  10020. { If the target size is 8-bit, make sure we can actually encode it }
  10021. 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
  10022. Exit;
  10023. {$endif i386 or i8086}
  10024. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10025. taicpu(hp1).opsize := NewSize;
  10026. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10027. if AndTest then
  10028. begin
  10029. RemoveInstruction(hp2);
  10030. if not RegUsed then
  10031. begin
  10032. taicpu(hp1).opcode := A_TEST;
  10033. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10034. begin
  10035. { Make sure the reference is the second operand }
  10036. SwapOper := taicpu(hp1).oper[0];
  10037. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10038. taicpu(hp1).oper[1] := SwapOper;
  10039. end;
  10040. end;
  10041. end;
  10042. case taicpu(hp1).oper[0]^.typ of
  10043. top_reg:
  10044. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10045. top_const:
  10046. { For the AND/TEST case }
  10047. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10048. else
  10049. ;
  10050. end;
  10051. if RegUsed then
  10052. begin
  10053. AsmL.Remove(p);
  10054. AsmL.InsertAfter(p, hp1);
  10055. p := hp1;
  10056. end
  10057. else
  10058. RemoveCurrentP(p, hp1);
  10059. result:=true;
  10060. exit;
  10061. end;
  10062. end;
  10063. end;
  10064. if reg_and_hp1_is_instr and
  10065. (taicpu(p).oper[0]^.typ = top_reg) and
  10066. (
  10067. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10068. ) and
  10069. (taicpu(hp1).oper[0]^.typ = top_const) and
  10070. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10071. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10072. { Minimum shift value allowed is the bit difference between the sizes }
  10073. (taicpu(hp1).oper[0]^.val >=
  10074. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10075. 8 * (
  10076. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10077. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10078. )
  10079. ) then
  10080. begin
  10081. { For:
  10082. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10083. shl/sal ##, %reg1
  10084. Remove the movsx/movzx instruction if the shift overwrites the
  10085. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10086. }
  10087. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10088. RemoveCurrentP(p, hp1);
  10089. Result := True;
  10090. Exit;
  10091. end
  10092. else if reg_and_hp1_is_instr and
  10093. (taicpu(p).oper[0]^.typ = top_reg) and
  10094. (
  10095. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10096. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10097. ) and
  10098. (taicpu(hp1).oper[0]^.typ = top_const) and
  10099. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10100. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10101. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10102. (taicpu(hp1).oper[0]^.val <
  10103. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10104. 8 * (
  10105. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10106. )
  10107. ) then
  10108. begin
  10109. { For:
  10110. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10111. sar ##, %reg1 shr ##, %reg1
  10112. Move the shift to before the movx instruction if the shift value
  10113. is not too large.
  10114. }
  10115. asml.Remove(hp1);
  10116. asml.InsertBefore(hp1, p);
  10117. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10118. case taicpu(p).opsize of
  10119. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10120. taicpu(hp1).opsize := S_B;
  10121. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10122. taicpu(hp1).opsize := S_W;
  10123. {$ifdef x86_64}
  10124. S_LQ:
  10125. taicpu(hp1).opsize := S_L;
  10126. {$endif}
  10127. else
  10128. InternalError(2020112401);
  10129. end;
  10130. if (taicpu(hp1).opcode = A_SHR) then
  10131. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10132. else
  10133. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10134. Result := True;
  10135. end;
  10136. if reg_and_hp1_is_instr and
  10137. (taicpu(p).oper[0]^.typ = top_reg) and
  10138. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10139. (
  10140. (taicpu(hp1).opcode = taicpu(p).opcode)
  10141. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10142. {$ifdef x86_64}
  10143. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10144. {$endif x86_64}
  10145. ) then
  10146. begin
  10147. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10148. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10149. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10150. begin
  10151. {
  10152. For example:
  10153. movzbw %al,%ax
  10154. movzwl %ax,%eax
  10155. Compress into:
  10156. movzbl %al,%eax
  10157. }
  10158. RegUsed := False;
  10159. case taicpu(p).opsize of
  10160. S_BW:
  10161. case taicpu(hp1).opsize of
  10162. S_WL:
  10163. begin
  10164. taicpu(p).opsize := S_BL;
  10165. RegUsed := True;
  10166. end;
  10167. {$ifdef x86_64}
  10168. S_WQ:
  10169. begin
  10170. if taicpu(p).opcode = A_MOVZX then
  10171. begin
  10172. taicpu(p).opsize := S_BL;
  10173. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10174. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10175. end
  10176. else
  10177. taicpu(p).opsize := S_BQ;
  10178. RegUsed := True;
  10179. end;
  10180. {$endif x86_64}
  10181. else
  10182. ;
  10183. end;
  10184. {$ifdef x86_64}
  10185. S_BL:
  10186. case taicpu(hp1).opsize of
  10187. S_LQ:
  10188. begin
  10189. if taicpu(p).opcode = A_MOVZX then
  10190. begin
  10191. taicpu(p).opsize := S_BL;
  10192. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10193. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10194. end
  10195. else
  10196. taicpu(p).opsize := S_BQ;
  10197. RegUsed := True;
  10198. end;
  10199. else
  10200. ;
  10201. end;
  10202. S_WL:
  10203. case taicpu(hp1).opsize of
  10204. S_LQ:
  10205. begin
  10206. if taicpu(p).opcode = A_MOVZX then
  10207. begin
  10208. taicpu(p).opsize := S_WL;
  10209. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10210. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10211. end
  10212. else
  10213. taicpu(p).opsize := S_WQ;
  10214. RegUsed := True;
  10215. end;
  10216. else
  10217. ;
  10218. end;
  10219. {$endif x86_64}
  10220. else
  10221. ;
  10222. end;
  10223. if RegUsed then
  10224. begin
  10225. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10226. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10227. RemoveInstruction(hp1);
  10228. Result := True;
  10229. Exit;
  10230. end;
  10231. end;
  10232. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10233. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10234. GetNextInstruction(hp1, hp2) and
  10235. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10236. (
  10237. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10238. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10239. {$ifdef x86_64}
  10240. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10241. {$endif x86_64}
  10242. ) and
  10243. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10244. (
  10245. (
  10246. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10247. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10248. ) or
  10249. (
  10250. { Only allow the operands in reverse order for TEST instructions }
  10251. (taicpu(hp2).opcode = A_TEST) and
  10252. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10253. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10254. )
  10255. ) then
  10256. begin
  10257. {
  10258. For example:
  10259. movzbl %al,%eax
  10260. movzbl (ref),%edx
  10261. andl %edx,%eax
  10262. (%edx deallocated)
  10263. Change to:
  10264. andb (ref),%al
  10265. movzbl %al,%eax
  10266. Rules are:
  10267. - First two instructions have the same opcode and opsize
  10268. - First instruction's operands are the same super-register
  10269. - Second instruction operates on a different register
  10270. - Third instruction is AND, OR, XOR or TEST
  10271. - Third instruction's operands are the destination registers of the first two instructions
  10272. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10273. - Second instruction's destination register is deallocated afterwards
  10274. }
  10275. TransferUsedRegs(TmpUsedRegs);
  10276. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10277. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10278. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10279. begin
  10280. case taicpu(p).opsize of
  10281. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10282. NewSize := S_B;
  10283. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10284. NewSize := S_W;
  10285. {$ifdef x86_64}
  10286. S_LQ:
  10287. NewSize := S_L;
  10288. {$endif x86_64}
  10289. else
  10290. InternalError(2021120301);
  10291. end;
  10292. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10293. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10294. taicpu(hp2).opsize := NewSize;
  10295. RemoveInstruction(hp1);
  10296. { With TEST, it's best to keep the MOVX instruction at the top }
  10297. if (taicpu(hp2).opcode <> A_TEST) then
  10298. begin
  10299. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10300. asml.Remove(p);
  10301. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10302. asml.InsertAfter(p, hp2);
  10303. p := hp2;
  10304. end
  10305. else
  10306. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10307. Result := True;
  10308. Exit;
  10309. end;
  10310. end;
  10311. end;
  10312. if taicpu(p).opcode=A_MOVZX then
  10313. begin
  10314. { removes superfluous And's after movzx's }
  10315. if reg_and_hp1_is_instr and
  10316. (taicpu(hp1).opcode = A_AND) and
  10317. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10318. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10319. {$ifdef x86_64}
  10320. { check for implicit extension to 64 bit }
  10321. or
  10322. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10323. (taicpu(hp1).opsize=S_Q) and
  10324. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10325. )
  10326. {$endif x86_64}
  10327. )
  10328. then
  10329. begin
  10330. case taicpu(p).opsize Of
  10331. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10332. if (taicpu(hp1).oper[0]^.val = $ff) then
  10333. begin
  10334. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10335. RemoveInstruction(hp1);
  10336. Result:=true;
  10337. exit;
  10338. end;
  10339. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10340. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10341. begin
  10342. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10343. RemoveInstruction(hp1);
  10344. Result:=true;
  10345. exit;
  10346. end;
  10347. {$ifdef x86_64}
  10348. S_LQ:
  10349. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10350. begin
  10351. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10352. RemoveInstruction(hp1);
  10353. Result:=true;
  10354. exit;
  10355. end;
  10356. {$endif x86_64}
  10357. else
  10358. ;
  10359. end;
  10360. { we cannot get rid of the and, but can we get rid of the movz ?}
  10361. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10362. begin
  10363. case taicpu(p).opsize Of
  10364. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10365. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10366. begin
  10367. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10368. RemoveCurrentP(p,hp1);
  10369. Result:=true;
  10370. exit;
  10371. end;
  10372. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10373. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10374. begin
  10375. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10376. RemoveCurrentP(p,hp1);
  10377. Result:=true;
  10378. exit;
  10379. end;
  10380. {$ifdef x86_64}
  10381. S_LQ:
  10382. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10383. begin
  10384. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10385. RemoveCurrentP(p,hp1);
  10386. Result:=true;
  10387. exit;
  10388. end;
  10389. {$endif x86_64}
  10390. else
  10391. ;
  10392. end;
  10393. end;
  10394. end;
  10395. { changes some movzx constructs to faster synonyms (all examples
  10396. are given with eax/ax, but are also valid for other registers)}
  10397. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10398. begin
  10399. case taicpu(p).opsize of
  10400. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10401. (the machine code is equivalent to movzbl %al,%eax), but the
  10402. code generator still generates that assembler instruction and
  10403. it is silently converted. This should probably be checked.
  10404. [Kit] }
  10405. S_BW:
  10406. begin
  10407. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10408. (
  10409. not IsMOVZXAcceptable
  10410. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10411. or (
  10412. (cs_opt_size in current_settings.optimizerswitches) and
  10413. (taicpu(p).oper[1]^.reg = NR_AX)
  10414. )
  10415. ) then
  10416. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10417. begin
  10418. DebugMsg(SPeepholeOptimization + 'var7',p);
  10419. taicpu(p).opcode := A_AND;
  10420. taicpu(p).changeopsize(S_W);
  10421. taicpu(p).loadConst(0,$ff);
  10422. Result := True;
  10423. end
  10424. else if not IsMOVZXAcceptable and
  10425. GetNextInstruction(p, hp1) and
  10426. (tai(hp1).typ = ait_instruction) and
  10427. (taicpu(hp1).opcode = A_AND) and
  10428. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10429. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10430. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10431. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10432. begin
  10433. DebugMsg(SPeepholeOptimization + 'var8',p);
  10434. taicpu(p).opcode := A_MOV;
  10435. taicpu(p).changeopsize(S_W);
  10436. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10437. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10438. Result := True;
  10439. end;
  10440. end;
  10441. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10442. S_BL:
  10443. begin
  10444. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10445. (
  10446. not IsMOVZXAcceptable
  10447. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10448. or (
  10449. (cs_opt_size in current_settings.optimizerswitches) and
  10450. (taicpu(p).oper[1]^.reg = NR_EAX)
  10451. )
  10452. ) then
  10453. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10454. begin
  10455. DebugMsg(SPeepholeOptimization + 'var9',p);
  10456. taicpu(p).opcode := A_AND;
  10457. taicpu(p).changeopsize(S_L);
  10458. taicpu(p).loadConst(0,$ff);
  10459. Result := True;
  10460. end
  10461. else if not IsMOVZXAcceptable and
  10462. GetNextInstruction(p, hp1) and
  10463. (tai(hp1).typ = ait_instruction) and
  10464. (taicpu(hp1).opcode = A_AND) and
  10465. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10466. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10467. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10468. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10469. begin
  10470. DebugMsg(SPeepholeOptimization + 'var10',p);
  10471. taicpu(p).opcode := A_MOV;
  10472. taicpu(p).changeopsize(S_L);
  10473. { do not use R_SUBWHOLE
  10474. as movl %rdx,%eax
  10475. is invalid in assembler PM }
  10476. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10477. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10478. Result := True;
  10479. end;
  10480. end;
  10481. {$endif i8086}
  10482. S_WL:
  10483. if not IsMOVZXAcceptable then
  10484. begin
  10485. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10486. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10487. begin
  10488. DebugMsg(SPeepholeOptimization + 'var11',p);
  10489. taicpu(p).opcode := A_AND;
  10490. taicpu(p).changeopsize(S_L);
  10491. taicpu(p).loadConst(0,$ffff);
  10492. Result := True;
  10493. end
  10494. else if GetNextInstruction(p, hp1) and
  10495. (tai(hp1).typ = ait_instruction) and
  10496. (taicpu(hp1).opcode = A_AND) and
  10497. (taicpu(hp1).oper[0]^.typ = top_const) and
  10498. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10499. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10500. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10501. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10502. begin
  10503. DebugMsg(SPeepholeOptimization + 'var12',p);
  10504. taicpu(p).opcode := A_MOV;
  10505. taicpu(p).changeopsize(S_L);
  10506. { do not use R_SUBWHOLE
  10507. as movl %rdx,%eax
  10508. is invalid in assembler PM }
  10509. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10510. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10511. Result := True;
  10512. end;
  10513. end;
  10514. else
  10515. InternalError(2017050705);
  10516. end;
  10517. end
  10518. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10519. begin
  10520. if GetNextInstruction(p, hp1) and
  10521. (tai(hp1).typ = ait_instruction) and
  10522. (taicpu(hp1).opcode = A_AND) and
  10523. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10524. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10525. begin
  10526. //taicpu(p).opcode := A_MOV;
  10527. case taicpu(p).opsize Of
  10528. S_BL:
  10529. begin
  10530. DebugMsg(SPeepholeOptimization + 'var13',p);
  10531. taicpu(hp1).changeopsize(S_L);
  10532. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10533. end;
  10534. S_WL:
  10535. begin
  10536. DebugMsg(SPeepholeOptimization + 'var14',p);
  10537. taicpu(hp1).changeopsize(S_L);
  10538. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10539. end;
  10540. S_BW:
  10541. begin
  10542. DebugMsg(SPeepholeOptimization + 'var15',p);
  10543. taicpu(hp1).changeopsize(S_W);
  10544. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10545. end;
  10546. else
  10547. Internalerror(2017050704)
  10548. end;
  10549. Result := True;
  10550. end;
  10551. end;
  10552. end;
  10553. end;
  10554. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10555. var
  10556. hp1, hp2 : tai;
  10557. MaskLength : Cardinal;
  10558. MaskedBits : TCgInt;
  10559. ActiveReg : TRegister;
  10560. begin
  10561. Result:=false;
  10562. { There are no optimisations for reference targets }
  10563. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10564. Exit;
  10565. while GetNextInstruction(p, hp1) and
  10566. (hp1.typ = ait_instruction) do
  10567. begin
  10568. if (taicpu(p).oper[0]^.typ = top_const) then
  10569. begin
  10570. case taicpu(hp1).opcode of
  10571. A_AND:
  10572. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10573. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10574. { the second register must contain the first one, so compare their subreg types }
  10575. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10576. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10577. { change
  10578. and const1, reg
  10579. and const2, reg
  10580. to
  10581. and (const1 and const2), reg
  10582. }
  10583. begin
  10584. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10585. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10586. RemoveCurrentP(p, hp1);
  10587. Result:=true;
  10588. exit;
  10589. end;
  10590. A_CMP:
  10591. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10592. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10593. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10594. { Just check that the condition on the next instruction is compatible }
  10595. GetNextInstruction(hp1, hp2) and
  10596. (hp2.typ = ait_instruction) and
  10597. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10598. then
  10599. { change
  10600. and 2^n, reg
  10601. cmp 2^n, reg
  10602. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10603. to
  10604. and 2^n, reg
  10605. test reg, reg
  10606. j(~c) / set(~c) / cmov(~c)
  10607. }
  10608. begin
  10609. { Keep TEST instruction in, rather than remove it, because
  10610. it may trigger other optimisations such as MovAndTest2Test }
  10611. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10612. taicpu(hp1).opcode := A_TEST;
  10613. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10614. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10615. Result := True;
  10616. Exit;
  10617. end;
  10618. A_MOVZX:
  10619. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10620. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10621. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10622. (
  10623. (
  10624. (taicpu(p).opsize=S_W) and
  10625. (taicpu(hp1).opsize=S_BW)
  10626. ) or
  10627. (
  10628. (taicpu(p).opsize=S_L) and
  10629. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10630. )
  10631. {$ifdef x86_64}
  10632. or
  10633. (
  10634. (taicpu(p).opsize=S_Q) and
  10635. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10636. )
  10637. {$endif x86_64}
  10638. ) then
  10639. begin
  10640. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10641. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10642. ) or
  10643. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10644. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10645. then
  10646. begin
  10647. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10648. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10649. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10650. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10651. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10652. }
  10653. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10654. RemoveInstruction(hp1);
  10655. { See if there are other optimisations possible }
  10656. Continue;
  10657. end;
  10658. end;
  10659. A_SHL:
  10660. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10661. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10662. begin
  10663. {$ifopt R+}
  10664. {$define RANGE_WAS_ON}
  10665. {$R-}
  10666. {$endif}
  10667. { get length of potential and mask }
  10668. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10669. { really a mask? }
  10670. {$ifdef RANGE_WAS_ON}
  10671. {$R+}
  10672. {$endif}
  10673. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10674. { unmasked part shifted out? }
  10675. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10676. begin
  10677. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10678. RemoveCurrentP(p, hp1);
  10679. Result:=true;
  10680. exit;
  10681. end;
  10682. end;
  10683. A_SHR:
  10684. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10685. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10686. (taicpu(hp1).oper[0]^.val <= 63) then
  10687. begin
  10688. { Does SHR combined with the AND cover all the bits?
  10689. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10690. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10691. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10692. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10693. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10694. begin
  10695. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10696. RemoveCurrentP(p, hp1);
  10697. Result := True;
  10698. Exit;
  10699. end;
  10700. end;
  10701. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10702. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10703. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10704. begin
  10705. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10706. (
  10707. (
  10708. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10709. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10710. ) or (
  10711. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10712. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10713. {$ifdef x86_64}
  10714. ) or (
  10715. (taicpu(hp1).opsize = S_LQ) and
  10716. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10717. {$endif x86_64}
  10718. )
  10719. ) then
  10720. begin
  10721. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10722. begin
  10723. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10724. RemoveInstruction(hp1);
  10725. { See if there are other optimisations possible }
  10726. Continue;
  10727. end;
  10728. { The super-registers are the same though.
  10729. Note that this change by itself doesn't improve
  10730. code speed, but it opens up other optimisations. }
  10731. {$ifdef x86_64}
  10732. { Convert 64-bit register to 32-bit }
  10733. case taicpu(hp1).opsize of
  10734. S_BQ:
  10735. begin
  10736. taicpu(hp1).opsize := S_BL;
  10737. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10738. end;
  10739. S_WQ:
  10740. begin
  10741. taicpu(hp1).opsize := S_WL;
  10742. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10743. end
  10744. else
  10745. ;
  10746. end;
  10747. {$endif x86_64}
  10748. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10749. taicpu(hp1).opcode := A_MOVZX;
  10750. { See if there are other optimisations possible }
  10751. Continue;
  10752. end;
  10753. end;
  10754. else
  10755. ;
  10756. end;
  10757. end
  10758. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10759. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10760. begin
  10761. {$ifdef x86_64}
  10762. if (taicpu(p).opsize = S_Q) then
  10763. begin
  10764. { Never necessary }
  10765. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10766. RemoveCurrentP(p, hp1);
  10767. Result := True;
  10768. Exit;
  10769. end;
  10770. {$endif x86_64}
  10771. { Forward check to determine necessity of and %reg,%reg }
  10772. TransferUsedRegs(TmpUsedRegs);
  10773. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10774. { Saves on a bunch of dereferences }
  10775. ActiveReg := taicpu(p).oper[1]^.reg;
  10776. case taicpu(hp1).opcode of
  10777. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10778. if (
  10779. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10780. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10781. ) and
  10782. (
  10783. (taicpu(hp1).opcode <> A_MOV) or
  10784. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10785. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10786. ) and
  10787. not (
  10788. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10789. (taicpu(hp1).opcode = A_MOV) and
  10790. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10791. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10792. ) and
  10793. (
  10794. (
  10795. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10796. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10797. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10798. ) or
  10799. (
  10800. {$ifdef x86_64}
  10801. (
  10802. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10803. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10804. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10805. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10806. ) and
  10807. {$endif x86_64}
  10808. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10809. )
  10810. ) then
  10811. begin
  10812. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10813. RemoveCurrentP(p, hp1);
  10814. Result := True;
  10815. Exit;
  10816. end;
  10817. A_ADD,
  10818. A_AND,
  10819. A_BSF,
  10820. A_BSR,
  10821. A_BTC,
  10822. A_BTR,
  10823. A_BTS,
  10824. A_OR,
  10825. A_SUB,
  10826. A_XOR:
  10827. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10828. if (
  10829. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10830. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10831. ) and
  10832. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10833. begin
  10834. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10835. RemoveCurrentP(p, hp1);
  10836. Result := True;
  10837. Exit;
  10838. end;
  10839. A_CMP,
  10840. A_TEST:
  10841. if (
  10842. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10843. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10844. ) and
  10845. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10846. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10847. begin
  10848. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10849. RemoveCurrentP(p, hp1);
  10850. Result := True;
  10851. Exit;
  10852. end;
  10853. A_BSWAP,
  10854. A_NEG,
  10855. A_NOT:
  10856. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10857. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10858. begin
  10859. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10860. RemoveCurrentP(p, hp1);
  10861. Result := True;
  10862. Exit;
  10863. end;
  10864. else
  10865. ;
  10866. end;
  10867. end;
  10868. if (taicpu(hp1).is_jmp) and
  10869. (taicpu(hp1).opcode<>A_JMP) and
  10870. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10871. begin
  10872. { change
  10873. and x, reg
  10874. jxx
  10875. to
  10876. test x, reg
  10877. jxx
  10878. if reg is deallocated before the
  10879. jump, but only if it's a conditional jump (PFV)
  10880. }
  10881. taicpu(p).opcode := A_TEST;
  10882. Exit;
  10883. end;
  10884. Break;
  10885. end;
  10886. { Lone AND tests }
  10887. if (taicpu(p).oper[0]^.typ = top_const) then
  10888. begin
  10889. {
  10890. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10891. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10892. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10893. }
  10894. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10895. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10896. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10897. begin
  10898. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10899. if taicpu(p).opsize = S_L then
  10900. begin
  10901. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10902. Result := True;
  10903. end;
  10904. end;
  10905. end;
  10906. { Backward check to determine necessity of and %reg,%reg }
  10907. if (taicpu(p).oper[0]^.typ = top_reg) and
  10908. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10909. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10910. GetLastInstruction(p, hp2) and
  10911. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10912. { Check size of adjacent instruction to determine if the AND is
  10913. effectively a null operation }
  10914. (
  10915. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10916. { Note: Don't include S_Q }
  10917. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10918. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10919. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10920. ) then
  10921. begin
  10922. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10923. { If GetNextInstruction returned False, hp1 will be nil }
  10924. RemoveCurrentP(p, hp1);
  10925. Result := True;
  10926. Exit;
  10927. end;
  10928. end;
  10929. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10930. var
  10931. hp1: tai; NewRef: TReference;
  10932. { This entire nested function is used in an if-statement below, but we
  10933. want to avoid all the used reg transfers and GetNextInstruction calls
  10934. until we really have to check }
  10935. function MemRegisterNotUsedLater: Boolean; inline;
  10936. var
  10937. hp2: tai;
  10938. begin
  10939. TransferUsedRegs(TmpUsedRegs);
  10940. hp2 := p;
  10941. repeat
  10942. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10943. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10944. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10945. end;
  10946. begin
  10947. Result := False;
  10948. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10949. Exit;
  10950. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10951. begin
  10952. { Change:
  10953. add %reg2,%reg1
  10954. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10955. To:
  10956. mov/s/z #(%reg1,%reg2),%reg1
  10957. }
  10958. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10959. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10960. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10961. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10962. (
  10963. (
  10964. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10965. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10966. { r/esp cannot be an index }
  10967. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10968. ) or (
  10969. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10970. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10971. )
  10972. ) and (
  10973. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10974. (
  10975. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10976. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10977. MemRegisterNotUsedLater
  10978. )
  10979. ) then
  10980. begin
  10981. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10982. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10983. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10984. RemoveCurrentp(p, hp1);
  10985. Result := True;
  10986. Exit;
  10987. end;
  10988. { Change:
  10989. addl/q $x,%reg1
  10990. movl/q %reg1,%reg2
  10991. To:
  10992. leal/q $x(%reg1),%reg2
  10993. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10994. Breaks the dependency chain.
  10995. }
  10996. if MatchOpType(taicpu(p),top_const,top_reg) and
  10997. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10998. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10999. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11000. (
  11001. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11002. not (cs_opt_size in current_settings.optimizerswitches) or
  11003. (
  11004. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11005. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11006. )
  11007. ) then
  11008. begin
  11009. { Change the MOV instruction to a LEA instruction, and update the
  11010. first operand }
  11011. reference_reset(NewRef, 1, []);
  11012. NewRef.base := taicpu(p).oper[1]^.reg;
  11013. NewRef.scalefactor := 1;
  11014. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11015. taicpu(hp1).opcode := A_LEA;
  11016. taicpu(hp1).loadref(0, NewRef);
  11017. TransferUsedRegs(TmpUsedRegs);
  11018. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11019. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11020. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11021. begin
  11022. { Move what is now the LEA instruction to before the SUB instruction }
  11023. Asml.Remove(hp1);
  11024. Asml.InsertBefore(hp1, p);
  11025. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11026. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11027. p := hp1;
  11028. end
  11029. else
  11030. begin
  11031. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11032. RemoveCurrentP(p, hp1);
  11033. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11034. end;
  11035. Result := True;
  11036. end;
  11037. end;
  11038. end;
  11039. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11040. var
  11041. SubReg: TSubRegister;
  11042. begin
  11043. Result:=false;
  11044. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11045. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11046. with taicpu(p).oper[0]^.ref^ do
  11047. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11048. begin
  11049. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11050. begin
  11051. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11052. taicpu(p).opcode := A_ADD;
  11053. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11054. Result := True;
  11055. end
  11056. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11057. begin
  11058. if (base <> NR_NO) then
  11059. begin
  11060. if (scalefactor <= 1) then
  11061. begin
  11062. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11063. taicpu(p).opcode := A_ADD;
  11064. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11065. Result := True;
  11066. end;
  11067. end
  11068. else
  11069. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11070. if (scalefactor in [2, 4, 8]) then
  11071. begin
  11072. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11073. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11074. taicpu(p).opcode := A_SHL;
  11075. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11076. Result := True;
  11077. end;
  11078. end;
  11079. end;
  11080. end;
  11081. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11082. var
  11083. hp1: tai; NewRef: TReference;
  11084. begin
  11085. { Change:
  11086. subl/q $x,%reg1
  11087. movl/q %reg1,%reg2
  11088. To:
  11089. leal/q $-x(%reg1),%reg2
  11090. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11091. Breaks the dependency chain and potentially permits the removal of
  11092. a CMP instruction if one follows.
  11093. }
  11094. Result := False;
  11095. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11096. MatchOpType(taicpu(p),top_const,top_reg) and
  11097. GetNextInstruction(p, hp1) and
  11098. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11099. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11100. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11101. (
  11102. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11103. not (cs_opt_size in current_settings.optimizerswitches) or
  11104. (
  11105. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11106. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11107. )
  11108. ) then
  11109. begin
  11110. { Change the MOV instruction to a LEA instruction, and update the
  11111. first operand }
  11112. reference_reset(NewRef, 1, []);
  11113. NewRef.base := taicpu(p).oper[1]^.reg;
  11114. NewRef.scalefactor := 1;
  11115. NewRef.offset := -taicpu(p).oper[0]^.val;
  11116. taicpu(hp1).opcode := A_LEA;
  11117. taicpu(hp1).loadref(0, NewRef);
  11118. TransferUsedRegs(TmpUsedRegs);
  11119. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11120. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11121. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11122. begin
  11123. { Move what is now the LEA instruction to before the SUB instruction }
  11124. Asml.Remove(hp1);
  11125. Asml.InsertBefore(hp1, p);
  11126. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11127. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11128. p := hp1;
  11129. end
  11130. else
  11131. begin
  11132. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11133. RemoveCurrentP(p, hp1);
  11134. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11135. end;
  11136. Result := True;
  11137. end;
  11138. end;
  11139. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11140. begin
  11141. { we can skip all instructions not messing with the stack pointer }
  11142. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11143. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11144. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11145. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11146. ({(taicpu(hp1).ops=0) or }
  11147. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11148. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11149. ) and }
  11150. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11151. )
  11152. ) do
  11153. GetNextInstruction(hp1,hp1);
  11154. Result:=assigned(hp1);
  11155. end;
  11156. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11157. var
  11158. hp1, hp2, hp3, hp4, hp5: tai;
  11159. begin
  11160. Result:=false;
  11161. hp5:=nil;
  11162. { replace
  11163. leal(q) x(<stackpointer>),<stackpointer>
  11164. call procname
  11165. leal(q) -x(<stackpointer>),<stackpointer>
  11166. ret
  11167. by
  11168. jmp procname
  11169. but do it only on level 4 because it destroys stack back traces
  11170. }
  11171. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11172. MatchOpType(taicpu(p),top_ref,top_reg) and
  11173. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11174. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11175. { the -8 or -24 are not required, but bail out early if possible,
  11176. higher values are unlikely }
  11177. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11178. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11179. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11180. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11181. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11182. GetNextInstruction(p, hp1) and
  11183. { Take a copy of hp1 }
  11184. SetAndTest(hp1, hp4) and
  11185. { trick to skip label }
  11186. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11187. SkipSimpleInstructions(hp1) and
  11188. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11189. GetNextInstruction(hp1, hp2) and
  11190. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11191. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11192. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11193. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11194. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11195. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11196. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11197. { Segment register will be NR_NO }
  11198. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11199. GetNextInstruction(hp2, hp3) and
  11200. { trick to skip label }
  11201. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11202. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11203. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11204. SetAndTest(hp3,hp5) and
  11205. GetNextInstruction(hp3,hp3) and
  11206. MatchInstruction(hp3,A_RET,[S_NO])
  11207. )
  11208. ) and
  11209. (taicpu(hp3).ops=0) then
  11210. begin
  11211. taicpu(hp1).opcode := A_JMP;
  11212. taicpu(hp1).is_jmp := true;
  11213. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11214. RemoveCurrentP(p, hp4);
  11215. RemoveInstruction(hp2);
  11216. RemoveInstruction(hp3);
  11217. if Assigned(hp5) then
  11218. begin
  11219. AsmL.Remove(hp5);
  11220. ASmL.InsertBefore(hp5,hp1)
  11221. end;
  11222. Result:=true;
  11223. end;
  11224. end;
  11225. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11226. {$ifdef x86_64}
  11227. var
  11228. hp1, hp2, hp3, hp4, hp5: tai;
  11229. {$endif x86_64}
  11230. begin
  11231. Result:=false;
  11232. {$ifdef x86_64}
  11233. hp5:=nil;
  11234. { replace
  11235. push %rax
  11236. call procname
  11237. pop %rcx
  11238. ret
  11239. by
  11240. jmp procname
  11241. but do it only on level 4 because it destroys stack back traces
  11242. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11243. for all supported calling conventions
  11244. }
  11245. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11246. MatchOpType(taicpu(p),top_reg) and
  11247. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11248. GetNextInstruction(p, hp1) and
  11249. { Take a copy of hp1 }
  11250. SetAndTest(hp1, hp4) and
  11251. { trick to skip label }
  11252. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11253. SkipSimpleInstructions(hp1) and
  11254. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11255. GetNextInstruction(hp1, hp2) and
  11256. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11257. MatchOpType(taicpu(hp2),top_reg) and
  11258. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11259. GetNextInstruction(hp2, hp3) and
  11260. { trick to skip label }
  11261. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11262. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11263. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11264. SetAndTest(hp3,hp5) and
  11265. GetNextInstruction(hp3,hp3) and
  11266. MatchInstruction(hp3,A_RET,[S_NO])
  11267. )
  11268. ) and
  11269. (taicpu(hp3).ops=0) then
  11270. begin
  11271. taicpu(hp1).opcode := A_JMP;
  11272. taicpu(hp1).is_jmp := true;
  11273. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11274. RemoveCurrentP(p, hp4);
  11275. RemoveInstruction(hp2);
  11276. RemoveInstruction(hp3);
  11277. if Assigned(hp5) then
  11278. begin
  11279. AsmL.Remove(hp5);
  11280. ASmL.InsertBefore(hp5,hp1)
  11281. end;
  11282. Result:=true;
  11283. end;
  11284. {$endif x86_64}
  11285. end;
  11286. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11287. var
  11288. Value, RegName: string;
  11289. begin
  11290. Result:=false;
  11291. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11292. begin
  11293. case taicpu(p).oper[0]^.val of
  11294. 0:
  11295. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11296. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11297. begin
  11298. { change "mov $0,%reg" into "xor %reg,%reg" }
  11299. taicpu(p).opcode := A_XOR;
  11300. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11301. Result := True;
  11302. {$ifdef x86_64}
  11303. end
  11304. else if (taicpu(p).opsize = S_Q) then
  11305. begin
  11306. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11307. { The actual optimization }
  11308. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11309. taicpu(p).changeopsize(S_L);
  11310. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11311. Result := True;
  11312. end;
  11313. $1..$FFFFFFFF:
  11314. begin
  11315. { Code size reduction by J. Gareth "Kit" Moreton }
  11316. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11317. case taicpu(p).opsize of
  11318. S_Q:
  11319. begin
  11320. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11321. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11322. { The actual optimization }
  11323. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11324. taicpu(p).changeopsize(S_L);
  11325. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11326. Result := True;
  11327. end;
  11328. else
  11329. { Do nothing };
  11330. end;
  11331. {$endif x86_64}
  11332. end;
  11333. -1:
  11334. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11335. if (cs_opt_size in current_settings.optimizerswitches) and
  11336. (taicpu(p).opsize <> S_B) and
  11337. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11338. begin
  11339. { change "mov $-1,%reg" into "or $-1,%reg" }
  11340. { NOTES:
  11341. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11342. - This operation creates a false dependency on the register, so only do it when optimising for size
  11343. - 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
  11344. }
  11345. taicpu(p).opcode := A_OR;
  11346. Result := True;
  11347. end;
  11348. else
  11349. { Do nothing };
  11350. end;
  11351. end;
  11352. end;
  11353. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11354. var
  11355. hp1: tai;
  11356. begin
  11357. { Detect:
  11358. andw x, %ax (0 <= x < $8000)
  11359. ...
  11360. movzwl %ax,%eax
  11361. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11362. }
  11363. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11364. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11365. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11366. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11367. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11368. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11369. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11370. begin
  11371. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11372. taicpu(hp1).opcode := A_CWDE;
  11373. taicpu(hp1).clearop(0);
  11374. taicpu(hp1).clearop(1);
  11375. taicpu(hp1).ops := 0;
  11376. { A change was made, but not with p, so move forward 1 }
  11377. p := tai(p.Next);
  11378. Result := True;
  11379. end;
  11380. end;
  11381. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11382. begin
  11383. Result := False;
  11384. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11385. Exit;
  11386. { Convert:
  11387. movswl %ax,%eax -> cwtl
  11388. movslq %eax,%rax -> cdqe
  11389. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11390. refer to the same opcode and depends only on the assembler's
  11391. current operand-size attribute. [Kit]
  11392. }
  11393. with taicpu(p) do
  11394. case opsize of
  11395. S_WL:
  11396. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11397. begin
  11398. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11399. opcode := A_CWDE;
  11400. clearop(0);
  11401. clearop(1);
  11402. ops := 0;
  11403. Result := True;
  11404. end;
  11405. {$ifdef x86_64}
  11406. S_LQ:
  11407. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11408. begin
  11409. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11410. opcode := A_CDQE;
  11411. clearop(0);
  11412. clearop(1);
  11413. ops := 0;
  11414. Result := True;
  11415. end;
  11416. {$endif x86_64}
  11417. else
  11418. ;
  11419. end;
  11420. end;
  11421. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11422. var
  11423. hp1: tai;
  11424. begin
  11425. { Detect:
  11426. shr x, %ax (x > 0)
  11427. ...
  11428. movzwl %ax,%eax
  11429. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11430. }
  11431. Result := False;
  11432. if MatchOpType(taicpu(p), top_const, top_reg) and
  11433. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11434. (taicpu(p).oper[0]^.val > 0) and
  11435. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11436. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11437. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11438. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11439. begin
  11440. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11441. taicpu(hp1).opcode := A_CWDE;
  11442. taicpu(hp1).clearop(0);
  11443. taicpu(hp1).clearop(1);
  11444. taicpu(hp1).ops := 0;
  11445. { A change was made, but not with p, so move forward 1 }
  11446. p := tai(p.Next);
  11447. Result := True;
  11448. end;
  11449. end;
  11450. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11451. var
  11452. hp1, hp2: tai;
  11453. Opposite, SecondOpposite: TAsmOp;
  11454. NewCond: TAsmCond;
  11455. begin
  11456. Result := False;
  11457. { Change:
  11458. add/sub 128,(dest)
  11459. To:
  11460. sub/add -128,(dest)
  11461. This generaally takes fewer bytes to encode because -128 can be stored
  11462. in a signed byte, whereas +128 cannot.
  11463. }
  11464. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11465. begin
  11466. if taicpu(p).opcode = A_ADD then
  11467. Opposite := A_SUB
  11468. else
  11469. Opposite := A_ADD;
  11470. { Be careful if the flags are in use, because the CF flag inverts
  11471. when changing from ADD to SUB and vice versa }
  11472. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11473. GetNextInstruction(p, hp1) then
  11474. begin
  11475. TransferUsedRegs(TmpUsedRegs);
  11476. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11477. hp2 := hp1;
  11478. { Scan ahead to check if everything's safe }
  11479. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11480. begin
  11481. if (hp1.typ <> ait_instruction) then
  11482. { Probably unsafe since the flags are still in use }
  11483. Exit;
  11484. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11485. { Stop searching at an unconditional jump }
  11486. Break;
  11487. if not
  11488. (
  11489. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11490. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11491. ) and
  11492. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11493. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11494. Exit;
  11495. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11496. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11497. { Move to the next instruction }
  11498. GetNextInstruction(hp1, hp1);
  11499. end;
  11500. while Assigned(hp2) and (hp2 <> hp1) do
  11501. begin
  11502. NewCond := C_None;
  11503. case taicpu(hp2).condition of
  11504. C_A, C_NBE:
  11505. NewCond := C_BE;
  11506. C_B, C_C, C_NAE:
  11507. NewCond := C_AE;
  11508. C_AE, C_NB, C_NC:
  11509. NewCond := C_B;
  11510. C_BE, C_NA:
  11511. NewCond := C_A;
  11512. else
  11513. { No change needed };
  11514. end;
  11515. if NewCond <> C_None then
  11516. begin
  11517. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11518. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11519. taicpu(hp2).condition := NewCond;
  11520. end
  11521. else
  11522. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11523. begin
  11524. { Because of the flipping of the carry bit, to ensure
  11525. the operation remains equivalent, ADC becomes SBB
  11526. and vice versa, and the constant is not-inverted.
  11527. If multiple ADCs or SBBs appear in a row, each one
  11528. changed causes the carry bit to invert, so they all
  11529. need to be flipped }
  11530. if taicpu(hp2).opcode = A_ADC then
  11531. SecondOpposite := A_SBB
  11532. else
  11533. SecondOpposite := A_ADC;
  11534. if taicpu(hp2).oper[0]^.typ <> top_const then
  11535. { Should have broken out of this optimisation already }
  11536. InternalError(2021112901);
  11537. 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]^) + ' -> ' +
  11538. 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);
  11539. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11540. taicpu(hp2).opcode := SecondOpposite;
  11541. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11542. end;
  11543. { Move to the next instruction }
  11544. GetNextInstruction(hp2, hp2);
  11545. end;
  11546. if (hp2 <> hp1) then
  11547. InternalError(2021111501);
  11548. end;
  11549. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11550. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11551. taicpu(p).opcode := Opposite;
  11552. taicpu(p).oper[0]^.val := -128;
  11553. { No further optimisations can be made on this instruction, so move
  11554. onto the next one to save time }
  11555. p := tai(p.Next);
  11556. UpdateUsedRegs(p);
  11557. Result := True;
  11558. Exit;
  11559. end;
  11560. { Detect:
  11561. add/sub %reg2,(dest)
  11562. add/sub x, (dest)
  11563. (dest can be a register or a reference)
  11564. Swap the instructions to minimise a pipeline stall. This reverses the
  11565. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11566. optimisations could be made.
  11567. }
  11568. if (taicpu(p).oper[0]^.typ = top_reg) and
  11569. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11570. (
  11571. (
  11572. (taicpu(p).oper[1]^.typ = top_reg) and
  11573. { We can try searching further ahead if we're writing to a register }
  11574. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11575. ) or
  11576. (
  11577. (taicpu(p).oper[1]^.typ = top_ref) and
  11578. GetNextInstruction(p, hp1)
  11579. )
  11580. ) and
  11581. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11582. (taicpu(hp1).oper[0]^.typ = top_const) and
  11583. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11584. begin
  11585. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11586. TransferUsedRegs(TmpUsedRegs);
  11587. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11588. hp2 := p;
  11589. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11590. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11591. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11592. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11593. begin
  11594. asml.remove(hp1);
  11595. asml.InsertBefore(hp1, p);
  11596. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11597. Result := True;
  11598. end;
  11599. end;
  11600. end;
  11601. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11602. begin
  11603. Result:=false;
  11604. { change "cmp $0, %reg" to "test %reg, %reg" }
  11605. if MatchOpType(taicpu(p),top_const,top_reg) and
  11606. (taicpu(p).oper[0]^.val = 0) then
  11607. begin
  11608. taicpu(p).opcode := A_TEST;
  11609. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11610. Result:=true;
  11611. end;
  11612. end;
  11613. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11614. var
  11615. IsTestConstX : Boolean;
  11616. hp1,hp2 : tai;
  11617. begin
  11618. Result:=false;
  11619. { removes the line marked with (x) from the sequence
  11620. and/or/xor/add/sub/... $x, %y
  11621. test/or %y, %y | test $-1, %y (x)
  11622. j(n)z _Label
  11623. as the first instruction already adjusts the ZF
  11624. %y operand may also be a reference }
  11625. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11626. MatchOperand(taicpu(p).oper[0]^,-1);
  11627. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11628. GetLastInstruction(p, hp1) and
  11629. (tai(hp1).typ = ait_instruction) and
  11630. GetNextInstruction(p,hp2) and
  11631. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11632. case taicpu(hp1).opcode Of
  11633. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11634. { These two instructions set the zero flag if the result is zero }
  11635. A_POPCNT, A_LZCNT:
  11636. begin
  11637. if (
  11638. { With POPCNT, an input of zero will set the zero flag
  11639. because the population count of zero is zero }
  11640. (taicpu(hp1).opcode = A_POPCNT) and
  11641. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11642. (
  11643. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11644. { Faster than going through the second half of the 'or'
  11645. condition below }
  11646. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11647. )
  11648. ) or (
  11649. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11650. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11651. { and in case of carry for A(E)/B(E)/C/NC }
  11652. (
  11653. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11654. (
  11655. (taicpu(hp1).opcode <> A_ADD) and
  11656. (taicpu(hp1).opcode <> A_SUB) and
  11657. (taicpu(hp1).opcode <> A_LZCNT)
  11658. )
  11659. )
  11660. ) then
  11661. begin
  11662. RemoveCurrentP(p, hp2);
  11663. Result:=true;
  11664. Exit;
  11665. end;
  11666. end;
  11667. A_SHL, A_SAL, A_SHR, A_SAR:
  11668. begin
  11669. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11670. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11671. { therefore, it's only safe to do this optimization for }
  11672. { shifts by a (nonzero) constant }
  11673. (taicpu(hp1).oper[0]^.typ = top_const) and
  11674. (taicpu(hp1).oper[0]^.val <> 0) and
  11675. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11676. { and in case of carry for A(E)/B(E)/C/NC }
  11677. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11678. begin
  11679. RemoveCurrentP(p, hp2);
  11680. Result:=true;
  11681. Exit;
  11682. end;
  11683. end;
  11684. A_DEC, A_INC, A_NEG:
  11685. begin
  11686. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11687. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11688. { and in case of carry for A(E)/B(E)/C/NC }
  11689. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11690. begin
  11691. RemoveCurrentP(p, hp2);
  11692. Result:=true;
  11693. Exit;
  11694. end;
  11695. end
  11696. else
  11697. ;
  11698. end; { case }
  11699. { change "test $-1,%reg" into "test %reg,%reg" }
  11700. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11701. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11702. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11703. if MatchInstruction(p, A_OR, []) and
  11704. { Can only match if they're both registers }
  11705. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11706. begin
  11707. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11708. taicpu(p).opcode := A_TEST;
  11709. { No need to set Result to True, as we've done all the optimisations we can }
  11710. end;
  11711. end;
  11712. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11713. var
  11714. hp1,hp3 : tai;
  11715. {$ifndef x86_64}
  11716. hp2 : taicpu;
  11717. {$endif x86_64}
  11718. begin
  11719. Result:=false;
  11720. hp3:=nil;
  11721. {$ifndef x86_64}
  11722. { don't do this on modern CPUs, this really hurts them due to
  11723. broken call/ret pairing }
  11724. if (current_settings.optimizecputype < cpu_Pentium2) and
  11725. not(cs_create_pic in current_settings.moduleswitches) and
  11726. GetNextInstruction(p, hp1) and
  11727. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11728. MatchOpType(taicpu(hp1),top_ref) and
  11729. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11730. begin
  11731. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11732. InsertLLItem(p.previous, p, hp2);
  11733. taicpu(p).opcode := A_JMP;
  11734. taicpu(p).is_jmp := true;
  11735. RemoveInstruction(hp1);
  11736. Result:=true;
  11737. end
  11738. else
  11739. {$endif x86_64}
  11740. { replace
  11741. call procname
  11742. ret
  11743. by
  11744. jmp procname
  11745. but do it only on level 4 because it destroys stack back traces
  11746. else if the subroutine is marked as no return, remove the ret
  11747. }
  11748. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11749. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11750. GetNextInstruction(p, hp1) and
  11751. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11752. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11753. SetAndTest(hp1,hp3) and
  11754. GetNextInstruction(hp1,hp1) and
  11755. MatchInstruction(hp1,A_RET,[S_NO])
  11756. )
  11757. ) and
  11758. (taicpu(hp1).ops=0) then
  11759. begin
  11760. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11761. { we might destroy stack alignment here if we do not do a call }
  11762. (target_info.stackalign<=sizeof(SizeUInt)) then
  11763. begin
  11764. taicpu(p).opcode := A_JMP;
  11765. taicpu(p).is_jmp := true;
  11766. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11767. end
  11768. else
  11769. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11770. RemoveInstruction(hp1);
  11771. if Assigned(hp3) then
  11772. begin
  11773. AsmL.Remove(hp3);
  11774. AsmL.InsertBefore(hp3,p)
  11775. end;
  11776. Result:=true;
  11777. end;
  11778. end;
  11779. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11780. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11781. begin
  11782. case OpSize of
  11783. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11784. Result := (Val <= $FF) and (Val >= -128);
  11785. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11786. Result := (Val <= $FFFF) and (Val >= -32768);
  11787. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11788. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11789. else
  11790. Result := True;
  11791. end;
  11792. end;
  11793. var
  11794. hp1, hp2 : tai;
  11795. SizeChange: Boolean;
  11796. PreMessage: string;
  11797. begin
  11798. Result := False;
  11799. if (taicpu(p).oper[0]^.typ = top_reg) and
  11800. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11801. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11802. begin
  11803. { Change (using movzbl %al,%eax as an example):
  11804. movzbl %al, %eax movzbl %al, %eax
  11805. cmpl x, %eax testl %eax,%eax
  11806. To:
  11807. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11808. movzbl %al, %eax movzbl %al, %eax
  11809. Smaller instruction and minimises pipeline stall as the CPU
  11810. doesn't have to wait for the register to get zero-extended. [Kit]
  11811. Also allow if the smaller of the two registers is being checked,
  11812. as this still removes the false dependency.
  11813. }
  11814. if
  11815. (
  11816. (
  11817. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11818. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11819. ) or (
  11820. { If MatchOperand returns True, they must both be registers }
  11821. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11822. )
  11823. ) and
  11824. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11825. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11826. begin
  11827. 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);
  11828. asml.Remove(hp1);
  11829. asml.InsertBefore(hp1, p);
  11830. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11831. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11832. begin
  11833. taicpu(hp1).opcode := A_TEST;
  11834. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11835. end;
  11836. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11837. case taicpu(p).opsize of
  11838. S_BW, S_BL:
  11839. begin
  11840. SizeChange := taicpu(hp1).opsize <> S_B;
  11841. taicpu(hp1).changeopsize(S_B);
  11842. end;
  11843. S_WL:
  11844. begin
  11845. SizeChange := taicpu(hp1).opsize <> S_W;
  11846. taicpu(hp1).changeopsize(S_W);
  11847. end
  11848. else
  11849. InternalError(2020112701);
  11850. end;
  11851. UpdateUsedRegs(tai(p.Next));
  11852. { Check if the register is used aferwards - if not, we can
  11853. remove the movzx instruction completely }
  11854. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11855. begin
  11856. { Hp1 is a better position than p for debugging purposes }
  11857. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11858. RemoveCurrentp(p, hp1);
  11859. Result := True;
  11860. end;
  11861. if SizeChange then
  11862. DebugMsg(SPeepholeOptimization + PreMessage +
  11863. 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)
  11864. else
  11865. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11866. Exit;
  11867. end;
  11868. { Change (using movzwl %ax,%eax as an example):
  11869. movzwl %ax, %eax
  11870. movb %al, (dest) (Register is smaller than read register in movz)
  11871. To:
  11872. movb %al, (dest) (Move one back to avoid a false dependency)
  11873. movzwl %ax, %eax
  11874. }
  11875. if (taicpu(hp1).opcode = A_MOV) and
  11876. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11877. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11878. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11879. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11880. begin
  11881. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11882. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11883. asml.Remove(hp1);
  11884. asml.InsertBefore(hp1, p);
  11885. if taicpu(hp1).oper[1]^.typ = top_reg then
  11886. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11887. { Check if the register is used aferwards - if not, we can
  11888. remove the movzx instruction completely }
  11889. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11890. begin
  11891. { Hp1 is a better position than p for debugging purposes }
  11892. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11893. RemoveCurrentp(p, hp1);
  11894. Result := True;
  11895. end;
  11896. Exit;
  11897. end;
  11898. end;
  11899. end;
  11900. {$ifdef x86_64}
  11901. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11902. var
  11903. PreMessage, RegName: string;
  11904. begin
  11905. { Code size reduction by J. Gareth "Kit" Moreton }
  11906. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11907. as this removes the REX prefix }
  11908. Result := False;
  11909. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11910. Exit;
  11911. if taicpu(p).oper[0]^.typ <> top_reg then
  11912. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11913. InternalError(2018011500);
  11914. case taicpu(p).opsize of
  11915. S_Q:
  11916. begin
  11917. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11918. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11919. { The actual optimization }
  11920. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11921. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11922. taicpu(p).changeopsize(S_L);
  11923. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11924. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11925. end;
  11926. else
  11927. ;
  11928. end;
  11929. end;
  11930. {$endif}
  11931. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11932. var
  11933. XReg: TRegister;
  11934. begin
  11935. Result := False;
  11936. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11937. Smaller encoding and slightly faster on some platforms (also works for
  11938. ZMM-sized registers) }
  11939. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11940. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11941. begin
  11942. XReg := taicpu(p).oper[0]^.reg;
  11943. if (taicpu(p).oper[1]^.reg = XReg) then
  11944. begin
  11945. taicpu(p).changeopsize(S_XMM);
  11946. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11947. if (cs_opt_size in current_settings.optimizerswitches) then
  11948. begin
  11949. { Change input registers to %xmm0 to reduce size. Note that
  11950. there's a risk of a false dependency doing this, so only
  11951. optimise for size here }
  11952. XReg := NR_XMM0;
  11953. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11954. end
  11955. else
  11956. begin
  11957. setsubreg(XReg, R_SUBMMX);
  11958. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11959. end;
  11960. taicpu(p).oper[0]^.reg := XReg;
  11961. taicpu(p).oper[1]^.reg := XReg;
  11962. Result := True;
  11963. end;
  11964. end;
  11965. end;
  11966. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11967. var
  11968. OperIdx: Integer;
  11969. begin
  11970. for OperIdx := 0 to p.ops - 1 do
  11971. if p.oper[OperIdx]^.typ = top_ref then
  11972. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11973. end;
  11974. end.