aoptx86.pas 574 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. InsertLLItem(p.previous, p.next, hp1);
  1418. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1419. p.free;
  1420. p := hp1;
  1421. end
  1422. else if ((taicpu(p).ops <= 2) or
  1423. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1424. not(cs_opt_size in current_settings.optimizerswitches) and
  1425. (not(GetNextInstruction(p, hp1)) or
  1426. not((tai(hp1).typ = ait_instruction) and
  1427. ((taicpu(hp1).opcode=A_Jcc) and
  1428. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1429. begin
  1430. {
  1431. imul X, reg1, reg2 to
  1432. lea (reg1,reg1,Y), reg2
  1433. shl ZZ,reg2
  1434. imul XX, reg1 to
  1435. lea (reg1,reg1,YY), reg1
  1436. shl ZZ,reg2
  1437. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1438. it does not exist as a separate optimization target in FPC though.
  1439. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1440. at most two zeros
  1441. }
  1442. reference_reset(tmpref,1,[]);
  1443. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1444. begin
  1445. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1446. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1447. TmpRef.base := taicpu(p).oper[1]^.reg;
  1448. TmpRef.index := taicpu(p).oper[1]^.reg;
  1449. if not(BaseValue in [3,5,9]) then
  1450. Internalerror(2018110101);
  1451. TmpRef.ScaleFactor := BaseValue-1;
  1452. if (taicpu(p).ops = 2) then
  1453. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1454. else
  1455. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1456. AsmL.InsertAfter(hp1,p);
  1457. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1458. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1459. RemoveCurrentP(p, hp1);
  1460. if ShiftValue>0 then
  1461. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1462. end;
  1463. end;
  1464. end;
  1465. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1466. begin
  1467. Result := False;
  1468. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1469. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1470. begin
  1471. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1472. taicpu(p).opcode := A_MOV;
  1473. Result := True;
  1474. end;
  1475. end;
  1476. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1477. var
  1478. p: taicpu absolute hp; { Implicit typecast }
  1479. i: Integer;
  1480. begin
  1481. Result := False;
  1482. if not assigned(hp) or
  1483. (hp.typ <> ait_instruction) then
  1484. Exit;
  1485. Prefetch(insprop[p.opcode]);
  1486. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1487. with insprop[p.opcode] do
  1488. begin
  1489. case getsubreg(reg) of
  1490. R_SUBW,R_SUBD,R_SUBQ:
  1491. Result:=
  1492. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1493. uncommon flags are checked first }
  1494. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1495. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1496. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1497. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1498. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1499. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1500. R_SUBFLAGCARRY:
  1501. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1502. R_SUBFLAGPARITY:
  1503. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1504. R_SUBFLAGAUXILIARY:
  1505. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1506. R_SUBFLAGZERO:
  1507. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGSIGN:
  1509. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGOVERFLOW:
  1511. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGINTERRUPT:
  1513. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGDIRECTION:
  1515. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1516. else
  1517. internalerror(2017050501);
  1518. end;
  1519. exit;
  1520. end;
  1521. { Handle special cases first }
  1522. case p.opcode of
  1523. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1524. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1525. begin
  1526. Result :=
  1527. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1528. (p.oper[1]^.typ = top_reg) and
  1529. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1530. (
  1531. (p.oper[0]^.typ = top_const) or
  1532. (
  1533. (p.oper[0]^.typ = top_reg) and
  1534. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1535. ) or (
  1536. (p.oper[0]^.typ = top_ref) and
  1537. not RegInRef(reg,p.oper[0]^.ref^)
  1538. )
  1539. );
  1540. end;
  1541. A_MUL, A_IMUL:
  1542. Result :=
  1543. (
  1544. (p.ops=3) and { IMUL only }
  1545. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1546. (
  1547. (
  1548. (p.oper[1]^.typ=top_reg) and
  1549. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1550. ) or (
  1551. (p.oper[1]^.typ=top_ref) and
  1552. not RegInRef(reg,p.oper[1]^.ref^)
  1553. )
  1554. )
  1555. ) or (
  1556. (
  1557. (p.ops=1) and
  1558. (
  1559. (
  1560. (
  1561. (p.oper[0]^.typ=top_reg) and
  1562. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1563. )
  1564. ) or (
  1565. (p.oper[0]^.typ=top_ref) and
  1566. not RegInRef(reg,p.oper[0]^.ref^)
  1567. )
  1568. ) and (
  1569. (
  1570. (p.opsize=S_B) and
  1571. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1572. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1573. ) or (
  1574. (p.opsize=S_W) and
  1575. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1576. ) or (
  1577. (p.opsize=S_L) and
  1578. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1579. {$ifdef x86_64}
  1580. ) or (
  1581. (p.opsize=S_Q) and
  1582. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1583. {$endif x86_64}
  1584. )
  1585. )
  1586. )
  1587. );
  1588. A_CBW:
  1589. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1590. {$ifndef x86_64}
  1591. A_LDS:
  1592. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1593. A_LES:
  1594. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1595. {$endif not x86_64}
  1596. A_LFS:
  1597. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1598. A_LGS:
  1599. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1600. A_LSS:
  1601. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1602. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1603. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1604. A_LODSB:
  1605. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1606. A_LODSW:
  1607. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1608. {$ifdef x86_64}
  1609. A_LODSQ:
  1610. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1611. {$endif x86_64}
  1612. A_LODSD:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1614. A_FSTSW, A_FNSTSW:
  1615. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1616. else
  1617. begin
  1618. with insprop[p.opcode] do
  1619. begin
  1620. if (
  1621. { xor %reg,%reg etc. is classed as a new value }
  1622. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1623. MatchOpType(p, top_reg, top_reg) and
  1624. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1625. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1626. ) then
  1627. begin
  1628. Result := True;
  1629. Exit;
  1630. end;
  1631. { Make sure the entire register is overwritten }
  1632. if (getregtype(reg) = R_INTREGISTER) then
  1633. begin
  1634. if (p.ops > 0) then
  1635. begin
  1636. if RegInOp(reg, p.oper[0]^) then
  1637. begin
  1638. if (p.oper[0]^.typ = top_ref) then
  1639. begin
  1640. if RegInRef(reg, p.oper[0]^.ref^) then
  1641. begin
  1642. Result := False;
  1643. Exit;
  1644. end;
  1645. end
  1646. else if (p.oper[0]^.typ = top_reg) then
  1647. begin
  1648. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1649. begin
  1650. Result := False;
  1651. Exit;
  1652. end
  1653. else if ([Ch_WOp1]*Ch<>[]) then
  1654. begin
  1655. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1656. Result := True
  1657. else
  1658. begin
  1659. Result := False;
  1660. Exit;
  1661. end;
  1662. end;
  1663. end;
  1664. end;
  1665. if (p.ops > 1) then
  1666. begin
  1667. if RegInOp(reg, p.oper[1]^) then
  1668. begin
  1669. if (p.oper[1]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[1]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[1]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp2]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 2) then
  1697. begin
  1698. if RegInOp(reg, p.oper[2]^) then
  1699. begin
  1700. if (p.oper[2]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[2]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[2]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp3]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1728. begin
  1729. if (p.oper[3]^.typ = top_ref) then
  1730. begin
  1731. if RegInRef(reg, p.oper[3]^.ref^) then
  1732. begin
  1733. Result := False;
  1734. Exit;
  1735. end;
  1736. end
  1737. else if (p.oper[3]^.typ = top_reg) then
  1738. begin
  1739. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1740. begin
  1741. Result := False;
  1742. Exit;
  1743. end
  1744. else if ([Ch_WOp4]*Ch<>[]) then
  1745. begin
  1746. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1747. Result := True
  1748. else
  1749. begin
  1750. Result := False;
  1751. Exit;
  1752. end;
  1753. end;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1760. case getsupreg(reg) of
  1761. RS_EAX:
  1762. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1763. begin
  1764. Result := True;
  1765. Exit;
  1766. end;
  1767. RS_ECX:
  1768. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_EDX:
  1774. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EBX:
  1780. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_ESP:
  1786. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_EBP:
  1792. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_ESI:
  1798. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_EDI:
  1804. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. else
  1810. ;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1818. var
  1819. hp2,hp3 : tai;
  1820. begin
  1821. { some x86-64 issue a NOP before the real exit code }
  1822. if MatchInstruction(p,A_NOP,[]) then
  1823. GetNextInstruction(p,p);
  1824. result:=assigned(p) and (p.typ=ait_instruction) and
  1825. ((taicpu(p).opcode = A_RET) or
  1826. ((taicpu(p).opcode=A_LEAVE) and
  1827. GetNextInstruction(p,hp2) and
  1828. MatchInstruction(hp2,A_RET,[S_NO])
  1829. ) or
  1830. (((taicpu(p).opcode=A_LEA) and
  1831. MatchOpType(taicpu(p),top_ref,top_reg) and
  1832. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1833. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1834. ) and
  1835. GetNextInstruction(p,hp2) and
  1836. MatchInstruction(hp2,A_RET,[S_NO])
  1837. ) or
  1838. ((((taicpu(p).opcode=A_MOV) and
  1839. MatchOpType(taicpu(p),top_reg,top_reg) and
  1840. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1841. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1842. ((taicpu(p).opcode=A_LEA) and
  1843. MatchOpType(taicpu(p),top_ref,top_reg) and
  1844. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1845. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1846. )
  1847. ) and
  1848. GetNextInstruction(p,hp2) and
  1849. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1850. MatchOpType(taicpu(hp2),top_reg) and
  1851. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1852. GetNextInstruction(hp2,hp3) and
  1853. MatchInstruction(hp3,A_RET,[S_NO])
  1854. )
  1855. );
  1856. end;
  1857. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1858. begin
  1859. isFoldableArithOp := False;
  1860. case hp1.opcode of
  1861. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1862. isFoldableArithOp :=
  1863. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1864. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1865. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1867. (taicpu(hp1).oper[1]^.reg = reg);
  1868. A_INC,A_DEC,A_NEG,A_NOT:
  1869. isFoldableArithOp :=
  1870. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg = reg);
  1872. else
  1873. ;
  1874. end;
  1875. end;
  1876. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1877. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1878. var
  1879. hp2: tai;
  1880. begin
  1881. hp2 := p;
  1882. repeat
  1883. hp2 := tai(hp2.previous);
  1884. if assigned(hp2) and
  1885. (hp2.typ = ait_regalloc) and
  1886. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1887. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1888. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1889. begin
  1890. RemoveInstruction(hp2);
  1891. break;
  1892. end;
  1893. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1894. end;
  1895. begin
  1896. case current_procinfo.procdef.returndef.typ of
  1897. arraydef,recorddef,pointerdef,
  1898. stringdef,enumdef,procdef,objectdef,errordef,
  1899. filedef,setdef,procvardef,
  1900. classrefdef,forwarddef:
  1901. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1902. orddef:
  1903. if current_procinfo.procdef.returndef.size <> 0 then
  1904. begin
  1905. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1906. { for int64/qword }
  1907. if current_procinfo.procdef.returndef.size = 8 then
  1908. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1909. end;
  1910. else
  1911. ;
  1912. end;
  1913. end;
  1914. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1915. var
  1916. hp1,hp2 : tai;
  1917. begin
  1918. result:=false;
  1919. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1920. begin
  1921. { vmova* reg1,reg1
  1922. =>
  1923. <nop> }
  1924. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1925. begin
  1926. RemoveCurrentP(p);
  1927. result:=true;
  1928. exit;
  1929. end
  1930. else if GetNextInstruction(p,hp1) then
  1931. begin
  1932. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1933. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1934. begin
  1935. { vmova* reg1,reg2
  1936. vmova* reg2,reg3
  1937. dealloc reg2
  1938. =>
  1939. vmova* reg1,reg3 }
  1940. TransferUsedRegs(TmpUsedRegs);
  1941. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1942. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1943. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1944. begin
  1945. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1946. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1947. RemoveInstruction(hp1);
  1948. result:=true;
  1949. exit;
  1950. end
  1951. { special case:
  1952. vmova* reg1,<op>
  1953. vmova* <op>,reg1
  1954. =>
  1955. vmova* reg1,<op> }
  1956. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1957. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1958. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1959. ) then
  1960. begin
  1961. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1962. RemoveInstruction(hp1);
  1963. result:=true;
  1964. exit;
  1965. end
  1966. end
  1967. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1968. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1969. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1970. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1971. ) and
  1972. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1973. begin
  1974. { vmova* reg1,reg2
  1975. vmovs* reg2,<op>
  1976. dealloc reg2
  1977. =>
  1978. vmovs* reg1,reg3 }
  1979. TransferUsedRegs(TmpUsedRegs);
  1980. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1981. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1982. begin
  1983. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1984. taicpu(p).opcode:=taicpu(hp1).opcode;
  1985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1986. RemoveInstruction(hp1);
  1987. result:=true;
  1988. exit;
  1989. end
  1990. end;
  1991. end;
  1992. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1993. begin
  1994. if MatchInstruction(hp1,[A_VFMADDPD,
  1995. A_VFMADD132PD,
  1996. A_VFMADD132PS,
  1997. A_VFMADD132SD,
  1998. A_VFMADD132SS,
  1999. A_VFMADD213PD,
  2000. A_VFMADD213PS,
  2001. A_VFMADD213SD,
  2002. A_VFMADD213SS,
  2003. A_VFMADD231PD,
  2004. A_VFMADD231PS,
  2005. A_VFMADD231SD,
  2006. A_VFMADD231SS,
  2007. A_VFMADDSUB132PD,
  2008. A_VFMADDSUB132PS,
  2009. A_VFMADDSUB213PD,
  2010. A_VFMADDSUB213PS,
  2011. A_VFMADDSUB231PD,
  2012. A_VFMADDSUB231PS,
  2013. A_VFMSUB132PD,
  2014. A_VFMSUB132PS,
  2015. A_VFMSUB132SD,
  2016. A_VFMSUB132SS,
  2017. A_VFMSUB213PD,
  2018. A_VFMSUB213PS,
  2019. A_VFMSUB213SD,
  2020. A_VFMSUB213SS,
  2021. A_VFMSUB231PD,
  2022. A_VFMSUB231PS,
  2023. A_VFMSUB231SD,
  2024. A_VFMSUB231SS,
  2025. A_VFMSUBADD132PD,
  2026. A_VFMSUBADD132PS,
  2027. A_VFMSUBADD213PD,
  2028. A_VFMSUBADD213PS,
  2029. A_VFMSUBADD231PD,
  2030. A_VFMSUBADD231PS,
  2031. A_VFNMADD132PD,
  2032. A_VFNMADD132PS,
  2033. A_VFNMADD132SD,
  2034. A_VFNMADD132SS,
  2035. A_VFNMADD213PD,
  2036. A_VFNMADD213PS,
  2037. A_VFNMADD213SD,
  2038. A_VFNMADD213SS,
  2039. A_VFNMADD231PD,
  2040. A_VFNMADD231PS,
  2041. A_VFNMADD231SD,
  2042. A_VFNMADD231SS,
  2043. A_VFNMSUB132PD,
  2044. A_VFNMSUB132PS,
  2045. A_VFNMSUB132SD,
  2046. A_VFNMSUB132SS,
  2047. A_VFNMSUB213PD,
  2048. A_VFNMSUB213PS,
  2049. A_VFNMSUB213SD,
  2050. A_VFNMSUB213SS,
  2051. A_VFNMSUB231PD,
  2052. A_VFNMSUB231PS,
  2053. A_VFNMSUB231SD,
  2054. A_VFNMSUB231SS],[S_NO]) and
  2055. { we mix single and double opperations here because we assume that the compiler
  2056. generates vmovapd only after double operations and vmovaps only after single operations }
  2057. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2058. GetNextInstruction(hp1,hp2) and
  2059. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2060. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2061. begin
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2065. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2066. begin
  2067. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2068. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  2069. RemoveInstruction(hp2);
  2070. end;
  2071. end
  2072. else if (hp1.typ = ait_instruction) and
  2073. GetNextInstruction(hp1, hp2) and
  2074. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2075. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2076. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2077. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2078. (((taicpu(p).opcode=A_MOVAPS) and
  2079. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2080. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2081. ((taicpu(p).opcode=A_MOVAPD) and
  2082. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2083. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2084. ) then
  2085. { change
  2086. movapX reg,reg2
  2087. addsX/subsX/... reg3, reg2
  2088. movapX reg2,reg
  2089. to
  2090. addsX/subsX/... reg3,reg
  2091. }
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2099. debug_op2str(taicpu(p).opcode)+' '+
  2100. debug_op2str(taicpu(hp1).opcode)+' '+
  2101. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2102. { we cannot eliminate the first move if
  2103. the operations uses the same register for source and dest }
  2104. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2105. RemoveCurrentP(p, nil);
  2106. p:=hp1;
  2107. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2108. RemoveInstruction(hp2);
  2109. result:=true;
  2110. end;
  2111. end
  2112. else if (hp1.typ = ait_instruction) and
  2113. (((taicpu(p).opcode=A_VMOVAPD) and
  2114. (taicpu(hp1).opcode=A_VCOMISD)) or
  2115. ((taicpu(p).opcode=A_VMOVAPS) and
  2116. ((taicpu(hp1).opcode=A_VCOMISS))
  2117. )
  2118. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2119. { change
  2120. movapX reg,reg1
  2121. vcomisX reg1,reg1
  2122. to
  2123. vcomisX reg,reg
  2124. }
  2125. begin
  2126. TransferUsedRegs(TmpUsedRegs);
  2127. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2128. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2129. begin
  2130. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2131. debug_op2str(taicpu(p).opcode)+' '+
  2132. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2133. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2134. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2135. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2136. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2137. RemoveCurrentP(p, nil);
  2138. result:=true;
  2139. exit;
  2140. end;
  2141. end
  2142. end;
  2143. end;
  2144. end;
  2145. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2146. var
  2147. hp1 : tai;
  2148. begin
  2149. result:=false;
  2150. { replace
  2151. V<Op>X %mreg1,%mreg2,%mreg3
  2152. VMovX %mreg3,%mreg4
  2153. dealloc %mreg3
  2154. by
  2155. V<Op>X %mreg1,%mreg2,%mreg4
  2156. ?
  2157. }
  2158. if GetNextInstruction(p,hp1) and
  2159. { we mix single and double operations here because we assume that the compiler
  2160. generates vmovapd only after double operations and vmovaps only after single operations }
  2161. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2162. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2163. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2164. begin
  2165. TransferUsedRegs(TmpUsedRegs);
  2166. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2167. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2168. begin
  2169. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2170. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2171. RemoveInstruction(hp1);
  2172. result:=true;
  2173. end;
  2174. end;
  2175. end;
  2176. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2177. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2178. begin
  2179. Result := False;
  2180. { For safety reasons, only check for exact register matches }
  2181. { Check base register }
  2182. if (ref.base = AOldReg) then
  2183. begin
  2184. ref.base := ANewReg;
  2185. Result := True;
  2186. end;
  2187. { Check index register }
  2188. if (ref.index = AOldReg) then
  2189. begin
  2190. ref.index := ANewReg;
  2191. Result := True;
  2192. end;
  2193. end;
  2194. { Replaces all references to AOldReg in an operand to ANewReg }
  2195. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2196. var
  2197. OldSupReg, NewSupReg: TSuperRegister;
  2198. OldSubReg, NewSubReg: TSubRegister;
  2199. OldRegType: TRegisterType;
  2200. ThisOper: POper;
  2201. begin
  2202. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2203. Result := False;
  2204. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2205. InternalError(2020011801);
  2206. OldSupReg := getsupreg(AOldReg);
  2207. OldSubReg := getsubreg(AOldReg);
  2208. OldRegType := getregtype(AOldReg);
  2209. NewSupReg := getsupreg(ANewReg);
  2210. NewSubReg := getsubreg(ANewReg);
  2211. if OldRegType <> getregtype(ANewReg) then
  2212. InternalError(2020011802);
  2213. if OldSubReg <> NewSubReg then
  2214. InternalError(2020011803);
  2215. case ThisOper^.typ of
  2216. top_reg:
  2217. if (
  2218. (ThisOper^.reg = AOldReg) or
  2219. (
  2220. (OldRegType = R_INTREGISTER) and
  2221. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2222. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2223. (
  2224. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2225. {$ifndef x86_64}
  2226. and (
  2227. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2228. don't have an 8-bit representation }
  2229. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2230. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2231. )
  2232. {$endif x86_64}
  2233. )
  2234. )
  2235. ) then
  2236. begin
  2237. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2238. Result := True;
  2239. end;
  2240. top_ref:
  2241. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2242. Result := True;
  2243. else
  2244. ;
  2245. end;
  2246. end;
  2247. { Replaces all references to AOldReg in an instruction to ANewReg }
  2248. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2249. const
  2250. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2251. var
  2252. OperIdx: Integer;
  2253. begin
  2254. Result := False;
  2255. for OperIdx := 0 to p.ops - 1 do
  2256. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2257. begin
  2258. { The shift and rotate instructions can only use CL }
  2259. if not (
  2260. (OperIdx = 0) and
  2261. { This second condition just helps to avoid unnecessarily
  2262. calling MatchInstruction for 10 different opcodes }
  2263. (p.oper[0]^.reg = NR_CL) and
  2264. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2265. ) then
  2266. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2267. end
  2268. else if p.oper[OperIdx]^.typ = top_ref then
  2269. { It's okay to replace registers in references that get written to }
  2270. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2271. end;
  2272. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2273. begin
  2274. with ref^ do
  2275. Result :=
  2276. (index = NR_NO) and
  2277. (
  2278. {$ifdef x86_64}
  2279. (
  2280. (base = NR_RIP) and
  2281. (refaddr in [addr_pic, addr_pic_no_got])
  2282. ) or
  2283. {$endif x86_64}
  2284. (base = NR_STACK_POINTER_REG) or
  2285. (base = current_procinfo.framepointer)
  2286. );
  2287. end;
  2288. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2289. var
  2290. l: asizeint;
  2291. begin
  2292. Result := False;
  2293. { Should have been checked previously }
  2294. if p.opcode <> A_LEA then
  2295. InternalError(2020072501);
  2296. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2297. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2298. not(cs_opt_size in current_settings.optimizerswitches) then
  2299. exit;
  2300. with p.oper[0]^.ref^ do
  2301. begin
  2302. if (base <> p.oper[1]^.reg) or
  2303. (index <> NR_NO) or
  2304. assigned(symbol) then
  2305. exit;
  2306. l:=offset;
  2307. if (l=1) and UseIncDec then
  2308. begin
  2309. p.opcode:=A_INC;
  2310. p.loadreg(0,p.oper[1]^.reg);
  2311. p.ops:=1;
  2312. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2313. end
  2314. else if (l=-1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_DEC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2320. end
  2321. else
  2322. begin
  2323. if (l<0) and (l<>-2147483648) then
  2324. begin
  2325. p.opcode:=A_SUB;
  2326. p.loadConst(0,-l);
  2327. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2328. end
  2329. else
  2330. begin
  2331. p.opcode:=A_ADD;
  2332. p.loadConst(0,l);
  2333. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2334. end;
  2335. end;
  2336. end;
  2337. Result := True;
  2338. end;
  2339. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2340. var
  2341. CurrentReg, ReplaceReg: TRegister;
  2342. begin
  2343. Result := False;
  2344. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2345. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2346. case hp.opcode of
  2347. A_FSTSW, A_FNSTSW,
  2348. A_IN, A_INS, A_OUT, A_OUTS,
  2349. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2350. { These routines have explicit operands, but they are restricted in
  2351. what they can be (e.g. IN and OUT can only read from AL, AX or
  2352. EAX. }
  2353. Exit;
  2354. A_IMUL:
  2355. begin
  2356. { The 1-operand version writes to implicit registers
  2357. The 2-operand version reads from the first operator, and reads
  2358. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2359. the 3-operand version reads from a register that it doesn't write to
  2360. }
  2361. case hp.ops of
  2362. 1:
  2363. if (
  2364. (
  2365. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2366. ) or
  2367. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2368. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2369. begin
  2370. Result := True;
  2371. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2372. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2373. end;
  2374. 2:
  2375. { Only modify the first parameter }
  2376. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2377. begin
  2378. Result := True;
  2379. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2380. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2381. end;
  2382. 3:
  2383. { Only modify the second parameter }
  2384. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2385. begin
  2386. Result := True;
  2387. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2388. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2389. end;
  2390. else
  2391. InternalError(2020012901);
  2392. end;
  2393. end;
  2394. else
  2395. if (hp.ops > 0) and
  2396. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2397. begin
  2398. Result := True;
  2399. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2400. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2401. end;
  2402. end;
  2403. end;
  2404. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2405. var
  2406. hp1, hp2, hp3: tai;
  2407. DoOptimisation, TempBool: Boolean;
  2408. {$ifdef x86_64}
  2409. NewConst: TCGInt;
  2410. {$endif x86_64}
  2411. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2412. begin
  2413. if taicpu(hp1).opcode = signed_movop then
  2414. begin
  2415. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2416. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2417. end
  2418. else
  2419. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2420. end;
  2421. function TryConstMerge(var p1, p2: tai): Boolean;
  2422. var
  2423. ThisRef: TReference;
  2424. begin
  2425. Result := False;
  2426. ThisRef := taicpu(p2).oper[1]^.ref^;
  2427. { Only permit writes to the stack, since we can guarantee alignment with that }
  2428. if (ThisRef.index = NR_NO) and
  2429. (
  2430. (ThisRef.base = NR_STACK_POINTER_REG) or
  2431. (ThisRef.base = current_procinfo.framepointer)
  2432. ) then
  2433. begin
  2434. case taicpu(p).opsize of
  2435. S_B:
  2436. begin
  2437. { Word writes must be on a 2-byte boundary }
  2438. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2439. begin
  2440. { Reduce offset of second reference to see if it is sequential with the first }
  2441. Dec(ThisRef.offset, 1);
  2442. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2443. begin
  2444. { Make sure the constants aren't represented as a
  2445. negative number, as these won't merge properly }
  2446. taicpu(p1).opsize := S_W;
  2447. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2448. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2449. RemoveInstruction(p2);
  2450. Result := True;
  2451. end;
  2452. end;
  2453. end;
  2454. S_W:
  2455. begin
  2456. { Longword writes must be on a 4-byte boundary }
  2457. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2458. begin
  2459. { Reduce offset of second reference to see if it is sequential with the first }
  2460. Dec(ThisRef.offset, 2);
  2461. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2462. begin
  2463. { Make sure the constants aren't represented as a
  2464. negative number, as these won't merge properly }
  2465. taicpu(p1).opsize := S_L;
  2466. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2467. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2468. RemoveInstruction(p2);
  2469. Result := True;
  2470. end;
  2471. end;
  2472. end;
  2473. {$ifdef x86_64}
  2474. S_L:
  2475. begin
  2476. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2477. see if the constants can be encoded this way. }
  2478. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2479. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2480. { Quadword writes must be on an 8-byte boundary }
  2481. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2482. begin
  2483. { Reduce offset of second reference to see if it is sequential with the first }
  2484. Dec(ThisRef.offset, 4);
  2485. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2486. begin
  2487. { Make sure the constants aren't represented as a
  2488. negative number, as these won't merge properly }
  2489. taicpu(p1).opsize := S_Q;
  2490. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2491. taicpu(p1).oper[0]^.val := NewConst;
  2492. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2493. RemoveInstruction(p2);
  2494. Result := True;
  2495. end;
  2496. end;
  2497. end;
  2498. {$endif x86_64}
  2499. else
  2500. ;
  2501. end;
  2502. end;
  2503. end;
  2504. var
  2505. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2506. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2507. NewSize: topsize;
  2508. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2509. SourceRef, TargetRef: TReference;
  2510. MovAligned, MovUnaligned: TAsmOp;
  2511. ThisRef: TReference;
  2512. JumpTracking: TLinkedList;
  2513. begin
  2514. Result:=false;
  2515. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2516. { remove mov reg1,reg1? }
  2517. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2518. then
  2519. begin
  2520. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2521. { take care of the register (de)allocs following p }
  2522. RemoveCurrentP(p, hp1);
  2523. Result:=true;
  2524. exit;
  2525. end;
  2526. { All the next optimisations require a next instruction }
  2527. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2528. Exit;
  2529. { Prevent compiler warnings }
  2530. p_TargetReg := NR_NO;
  2531. if taicpu(p).oper[1]^.typ = top_reg then
  2532. begin
  2533. { Saves on a large number of dereferences }
  2534. p_TargetReg := taicpu(p).oper[1]^.reg;
  2535. { Look for:
  2536. mov %reg1,%reg2
  2537. ??? %reg2,r/m
  2538. Change to:
  2539. mov %reg1,%reg2
  2540. ??? %reg1,r/m
  2541. }
  2542. if taicpu(p).oper[0]^.typ = top_reg then
  2543. begin
  2544. if RegReadByInstruction(p_TargetReg, hp1) and
  2545. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2546. begin
  2547. { A change has occurred, just not in p }
  2548. Result := True;
  2549. TransferUsedRegs(TmpUsedRegs);
  2550. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2551. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2552. { Just in case something didn't get modified (e.g. an
  2553. implicit register) }
  2554. not RegReadByInstruction(p_TargetReg, hp1) then
  2555. begin
  2556. { We can remove the original MOV }
  2557. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2558. RemoveCurrentp(p, hp1);
  2559. { UsedRegs got updated by RemoveCurrentp }
  2560. Result := True;
  2561. Exit;
  2562. end;
  2563. { If we know a MOV instruction has become a null operation, we might as well
  2564. get rid of it now to save time. }
  2565. if (taicpu(hp1).opcode = A_MOV) and
  2566. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2567. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2568. { Just being a register is enough to confirm it's a null operation }
  2569. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2570. begin
  2571. Result := True;
  2572. { Speed-up to reduce a pipeline stall... if we had something like...
  2573. movl %eax,%edx
  2574. movw %dx,%ax
  2575. ... the second instruction would change to movw %ax,%ax, but
  2576. given that it is now %ax that's active rather than %eax,
  2577. penalties might occur due to a partial register write, so instead,
  2578. change it to a MOVZX instruction when optimising for speed.
  2579. }
  2580. if not (cs_opt_size in current_settings.optimizerswitches) and
  2581. IsMOVZXAcceptable and
  2582. (taicpu(hp1).opsize < taicpu(p).opsize)
  2583. {$ifdef x86_64}
  2584. { operations already implicitly set the upper 64 bits to zero }
  2585. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2586. {$endif x86_64}
  2587. then
  2588. begin
  2589. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2590. case taicpu(p).opsize of
  2591. S_W:
  2592. if taicpu(hp1).opsize = S_B then
  2593. taicpu(hp1).opsize := S_BL
  2594. else
  2595. InternalError(2020012911);
  2596. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2597. case taicpu(hp1).opsize of
  2598. S_B:
  2599. taicpu(hp1).opsize := S_BL;
  2600. S_W:
  2601. taicpu(hp1).opsize := S_WL;
  2602. else
  2603. InternalError(2020012912);
  2604. end;
  2605. else
  2606. InternalError(2020012910);
  2607. end;
  2608. taicpu(hp1).opcode := A_MOVZX;
  2609. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2610. end
  2611. else
  2612. begin
  2613. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2614. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2615. RemoveInstruction(hp1);
  2616. { The instruction after what was hp1 is now the immediate next instruction,
  2617. so we can continue to make optimisations if it's present }
  2618. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2619. Exit;
  2620. hp1 := hp2;
  2621. end;
  2622. end;
  2623. end;
  2624. end;
  2625. end;
  2626. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2627. overwrites the original destination register. e.g.
  2628. movl ###,%reg2d
  2629. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2630. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2631. }
  2632. if (taicpu(p).oper[1]^.typ = top_reg) and
  2633. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2634. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2635. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2636. begin
  2637. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2638. begin
  2639. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2640. case taicpu(p).oper[0]^.typ of
  2641. top_const:
  2642. { We have something like:
  2643. movb $x, %regb
  2644. movzbl %regb,%regd
  2645. Change to:
  2646. movl $x, %regd
  2647. }
  2648. begin
  2649. case taicpu(hp1).opsize of
  2650. S_BW:
  2651. begin
  2652. convert_mov_value(A_MOVSX, $FF);
  2653. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2654. taicpu(p).opsize := S_W;
  2655. end;
  2656. S_BL:
  2657. begin
  2658. convert_mov_value(A_MOVSX, $FF);
  2659. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2660. taicpu(p).opsize := S_L;
  2661. end;
  2662. S_WL:
  2663. begin
  2664. convert_mov_value(A_MOVSX, $FFFF);
  2665. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2666. taicpu(p).opsize := S_L;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_BQ:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2673. taicpu(p).opsize := S_Q;
  2674. end;
  2675. S_WQ:
  2676. begin
  2677. convert_mov_value(A_MOVSX, $FFFF);
  2678. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2679. taicpu(p).opsize := S_Q;
  2680. end;
  2681. S_LQ:
  2682. begin
  2683. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2684. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2685. taicpu(p).opsize := S_Q;
  2686. end;
  2687. {$endif x86_64}
  2688. else
  2689. { If hp1 was a MOV instruction, it should have been
  2690. optimised already }
  2691. InternalError(2020021001);
  2692. end;
  2693. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2694. RemoveInstruction(hp1);
  2695. Result := True;
  2696. Exit;
  2697. end;
  2698. top_ref:
  2699. begin
  2700. { We have something like:
  2701. movb mem, %regb
  2702. movzbl %regb,%regd
  2703. Change to:
  2704. movzbl mem, %regd
  2705. }
  2706. ThisRef := taicpu(p).oper[0]^.ref^;
  2707. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2708. begin
  2709. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2710. taicpu(hp1).loadref(0, ThisRef);
  2711. { Make sure any registers in the references are properly tracked }
  2712. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2713. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2714. if (ThisRef.index <> NR_NO) then
  2715. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2716. RemoveCurrentP(p, hp1);
  2717. Result := True;
  2718. Exit;
  2719. end;
  2720. end;
  2721. else
  2722. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2723. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2724. Exit;
  2725. end;
  2726. end
  2727. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2728. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2729. optimised }
  2730. else
  2731. begin
  2732. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2733. RemoveCurrentP(p, hp1);
  2734. Result := True;
  2735. Exit;
  2736. end;
  2737. end;
  2738. if (taicpu(hp1).opcode = A_AND) and
  2739. (taicpu(p).oper[1]^.typ = top_reg) and
  2740. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2741. begin
  2742. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2743. begin
  2744. case taicpu(p).opsize of
  2745. S_L:
  2746. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2747. begin
  2748. { Optimize out:
  2749. mov x, %reg
  2750. and ffffffffh, %reg
  2751. }
  2752. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2753. RemoveInstruction(hp1);
  2754. Result:=true;
  2755. exit;
  2756. end;
  2757. S_Q: { TODO: Confirm if this is even possible }
  2758. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2759. begin
  2760. { Optimize out:
  2761. mov x, %reg
  2762. and ffffffffffffffffh, %reg
  2763. }
  2764. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2765. RemoveInstruction(hp1);
  2766. Result:=true;
  2767. exit;
  2768. end;
  2769. else
  2770. ;
  2771. end;
  2772. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2773. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2774. GetNextInstruction(hp1,hp2) and
  2775. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2776. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2777. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2778. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2779. GetNextInstruction(hp2,hp3) and
  2780. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2781. (taicpu(hp3).condition in [C_E,C_NE]) then
  2782. begin
  2783. TransferUsedRegs(TmpUsedRegs);
  2784. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2785. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2786. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2787. begin
  2788. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2789. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2790. taicpu(hp1).opcode:=A_TEST;
  2791. RemoveInstruction(hp2);
  2792. RemoveCurrentP(p, hp1);
  2793. Result:=true;
  2794. exit;
  2795. end;
  2796. end;
  2797. end
  2798. else if IsMOVZXAcceptable and
  2799. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2800. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2801. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2802. then
  2803. begin
  2804. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2805. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2806. case taicpu(p).opsize of
  2807. S_B:
  2808. if (taicpu(hp1).oper[0]^.val = $ff) then
  2809. begin
  2810. { Convert:
  2811. movb x, %regl movb x, %regl
  2812. andw ffh, %regw andl ffh, %regd
  2813. To:
  2814. movzbw x, %regd movzbl x, %regd
  2815. (Identical registers, just different sizes)
  2816. }
  2817. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2818. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2819. case taicpu(hp1).opsize of
  2820. S_W: NewSize := S_BW;
  2821. S_L: NewSize := S_BL;
  2822. {$ifdef x86_64}
  2823. S_Q: NewSize := S_BQ;
  2824. {$endif x86_64}
  2825. else
  2826. InternalError(2018011510);
  2827. end;
  2828. end
  2829. else
  2830. NewSize := S_NO;
  2831. S_W:
  2832. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2833. begin
  2834. { Convert:
  2835. movw x, %regw
  2836. andl ffffh, %regd
  2837. To:
  2838. movzwl x, %regd
  2839. (Identical registers, just different sizes)
  2840. }
  2841. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2842. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2843. case taicpu(hp1).opsize of
  2844. S_L: NewSize := S_WL;
  2845. {$ifdef x86_64}
  2846. S_Q: NewSize := S_WQ;
  2847. {$endif x86_64}
  2848. else
  2849. InternalError(2018011511);
  2850. end;
  2851. end
  2852. else
  2853. NewSize := S_NO;
  2854. else
  2855. NewSize := S_NO;
  2856. end;
  2857. if NewSize <> S_NO then
  2858. begin
  2859. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2860. { The actual optimization }
  2861. taicpu(p).opcode := A_MOVZX;
  2862. taicpu(p).changeopsize(NewSize);
  2863. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2864. { Safeguard if "and" is followed by a conditional command }
  2865. TransferUsedRegs(TmpUsedRegs);
  2866. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2867. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2868. begin
  2869. { At this point, the "and" command is effectively equivalent to
  2870. "test %reg,%reg". This will be handled separately by the
  2871. Peephole Optimizer. [Kit] }
  2872. DebugMsg(SPeepholeOptimization + PreMessage +
  2873. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2874. end
  2875. else
  2876. begin
  2877. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2878. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2879. RemoveInstruction(hp1);
  2880. end;
  2881. Result := True;
  2882. Exit;
  2883. end;
  2884. end;
  2885. end;
  2886. if (taicpu(hp1).opcode = A_OR) and
  2887. (taicpu(p).oper[1]^.typ = top_reg) and
  2888. MatchOperand(taicpu(p).oper[0]^, 0) and
  2889. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2890. begin
  2891. { mov 0, %reg
  2892. or ###,%reg
  2893. Change to (only if the flags are not used):
  2894. mov ###,%reg
  2895. }
  2896. TransferUsedRegs(TmpUsedRegs);
  2897. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2898. DoOptimisation := True;
  2899. { Even if the flags are used, we might be able to do the optimisation
  2900. if the conditions are predictable }
  2901. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2902. begin
  2903. { Only perform if ### = %reg (the same register) or equal to 0,
  2904. so %reg is guaranteed to still have a value of zero }
  2905. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2906. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2907. begin
  2908. hp2 := hp1;
  2909. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2910. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2911. GetNextInstruction(hp2, hp3) do
  2912. begin
  2913. { Don't continue modifying if the flags state is getting changed }
  2914. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2915. Break;
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2917. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2918. begin
  2919. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2920. begin
  2921. { Condition is always true }
  2922. case taicpu(hp3).opcode of
  2923. A_Jcc:
  2924. begin
  2925. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2926. { Check for jump shortcuts before we destroy the condition }
  2927. DoJumpOptimizations(hp3, TempBool);
  2928. MakeUnconditional(taicpu(hp3));
  2929. Result := True;
  2930. end;
  2931. A_CMOVcc:
  2932. begin
  2933. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2934. taicpu(hp3).opcode := A_MOV;
  2935. taicpu(hp3).condition := C_None;
  2936. Result := True;
  2937. end;
  2938. A_SETcc:
  2939. begin
  2940. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2941. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2942. taicpu(hp3).opcode := A_MOV;
  2943. taicpu(hp3).ops := 2;
  2944. taicpu(hp3).condition := C_None;
  2945. taicpu(hp3).opsize := S_B;
  2946. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2947. taicpu(hp3).loadconst(0, 1);
  2948. Result := True;
  2949. end;
  2950. else
  2951. InternalError(2021090701);
  2952. end;
  2953. end
  2954. 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
  2955. begin
  2956. { Condition is always false }
  2957. case taicpu(hp3).opcode of
  2958. A_Jcc:
  2959. begin
  2960. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2961. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2962. RemoveInstruction(hp3);
  2963. Result := True;
  2964. { Since hp3 was deleted, hp2 must not be updated }
  2965. Continue;
  2966. end;
  2967. A_CMOVcc:
  2968. begin
  2969. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2970. RemoveInstruction(hp3);
  2971. Result := True;
  2972. { Since hp3 was deleted, hp2 must not be updated }
  2973. Continue;
  2974. end;
  2975. A_SETcc:
  2976. begin
  2977. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2978. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2979. taicpu(hp3).opcode := A_MOV;
  2980. taicpu(hp3).ops := 2;
  2981. taicpu(hp3).condition := C_None;
  2982. taicpu(hp3).opsize := S_B;
  2983. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2984. taicpu(hp3).loadconst(0, 0);
  2985. Result := True;
  2986. end;
  2987. else
  2988. InternalError(2021090702);
  2989. end;
  2990. end
  2991. else
  2992. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2993. DoOptimisation := False;
  2994. end;
  2995. hp2 := hp3;
  2996. end;
  2997. { Flags are still in use - don't optimise }
  2998. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2999. DoOptimisation := False;
  3000. end
  3001. else
  3002. DoOptimisation := False;
  3003. end;
  3004. if DoOptimisation then
  3005. begin
  3006. {$ifdef x86_64}
  3007. { OR only supports 32-bit sign-extended constants for 64-bit
  3008. instructions, so compensate for this if the constant is
  3009. encoded as a value greater than or equal to 2^31 }
  3010. if (taicpu(hp1).opsize = S_Q) and
  3011. (taicpu(hp1).oper[0]^.typ = top_const) and
  3012. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3013. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3014. {$endif x86_64}
  3015. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3016. taicpu(hp1).opcode := A_MOV;
  3017. RemoveCurrentP(p, hp1);
  3018. Result := True;
  3019. Exit;
  3020. end;
  3021. end;
  3022. { Next instruction is also a MOV ? }
  3023. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3024. begin
  3025. if MatchOpType(taicpu(p), top_const, top_ref) and
  3026. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3027. TryConstMerge(p, hp1) then
  3028. begin
  3029. Result := True;
  3030. { In case we have four byte writes in a row, check for 2 more
  3031. right now so we don't have to wait for another iteration of
  3032. pass 1
  3033. }
  3034. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3035. case taicpu(p).opsize of
  3036. S_W:
  3037. begin
  3038. if GetNextInstruction(p, hp1) and
  3039. MatchInstruction(hp1, A_MOV, [S_B]) and
  3040. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3041. GetNextInstruction(hp1, hp2) and
  3042. MatchInstruction(hp2, A_MOV, [S_B]) and
  3043. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3044. { Try to merge the two bytes }
  3045. TryConstMerge(hp1, hp2) then
  3046. { Now try to merge the two words (hp2 will get deleted) }
  3047. TryConstMerge(p, hp1);
  3048. end;
  3049. S_L:
  3050. begin
  3051. { Though this only really benefits x86_64 and not i386, it
  3052. gets a potential optimisation done faster and hence
  3053. reduces the number of times OptPass1MOV is entered }
  3054. if GetNextInstruction(p, hp1) and
  3055. MatchInstruction(hp1, A_MOV, [S_W]) and
  3056. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3057. GetNextInstruction(hp1, hp2) and
  3058. MatchInstruction(hp2, A_MOV, [S_W]) and
  3059. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3060. { Try to merge the two words }
  3061. TryConstMerge(hp1, hp2) then
  3062. { This will always fail on i386, so don't bother
  3063. calling it unless we're doing x86_64 }
  3064. {$ifdef x86_64}
  3065. { Now try to merge the two longwords (hp2 will get deleted) }
  3066. TryConstMerge(p, hp1)
  3067. {$endif x86_64}
  3068. ;
  3069. end;
  3070. else
  3071. ;
  3072. end;
  3073. Exit;
  3074. end;
  3075. if (taicpu(p).oper[1]^.typ = top_reg) and
  3076. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3077. begin
  3078. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3079. TransferUsedRegs(TmpUsedRegs);
  3080. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3081. { we have
  3082. mov x, %treg
  3083. mov %treg, y
  3084. }
  3085. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3086. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3087. { we've got
  3088. mov x, %treg
  3089. mov %treg, y
  3090. with %treg is not used after }
  3091. case taicpu(p).oper[0]^.typ Of
  3092. { top_reg is covered by DeepMOVOpt }
  3093. top_const:
  3094. begin
  3095. { change
  3096. mov const, %treg
  3097. mov %treg, y
  3098. to
  3099. mov const, y
  3100. }
  3101. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3102. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3103. begin
  3104. if taicpu(hp1).oper[1]^.typ=top_reg then
  3105. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3106. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3107. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3108. RemoveInstruction(hp1);
  3109. Result:=true;
  3110. Exit;
  3111. end;
  3112. end;
  3113. top_ref:
  3114. case taicpu(hp1).oper[1]^.typ of
  3115. top_reg:
  3116. begin
  3117. { change
  3118. mov mem, %treg
  3119. mov %treg, %reg
  3120. to
  3121. mov mem, %reg"
  3122. }
  3123. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3124. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3125. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3126. RemoveInstruction(hp1);
  3127. Result:=true;
  3128. Exit;
  3129. end;
  3130. top_ref:
  3131. begin
  3132. {$ifdef x86_64}
  3133. { Look for the following to simplify:
  3134. mov x(mem1), %reg
  3135. mov %reg, y(mem2)
  3136. mov x+8(mem1), %reg
  3137. mov %reg, y+8(mem2)
  3138. Change to:
  3139. movdqu x(mem1), %xmmreg
  3140. movdqu %xmmreg, y(mem2)
  3141. ...but only as long as the memory blocks don't overlap
  3142. }
  3143. SourceRef := taicpu(p).oper[0]^.ref^;
  3144. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3145. if (taicpu(p).opsize = S_Q) and
  3146. GetNextInstruction(hp1, hp2) and
  3147. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3148. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3149. begin
  3150. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3151. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3152. Inc(SourceRef.offset, 8);
  3153. if UseAVX then
  3154. begin
  3155. MovAligned := A_VMOVDQA;
  3156. MovUnaligned := A_VMOVDQU;
  3157. end
  3158. else
  3159. begin
  3160. MovAligned := A_MOVDQA;
  3161. MovUnaligned := A_MOVDQU;
  3162. end;
  3163. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3164. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3165. begin
  3166. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3167. Inc(TargetRef.offset, 8);
  3168. if GetNextInstruction(hp2, hp3) and
  3169. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3170. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3171. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3172. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3173. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3174. begin
  3175. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3176. if NewMMReg <> NR_NO then
  3177. begin
  3178. { Remember that the offsets are 8 ahead }
  3179. if ((SourceRef.offset mod 16) = 8) and
  3180. (
  3181. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3182. (SourceRef.base = current_procinfo.framepointer) or
  3183. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3184. ) then
  3185. taicpu(p).opcode := MovAligned
  3186. else
  3187. taicpu(p).opcode := MovUnaligned;
  3188. taicpu(p).opsize := S_XMM;
  3189. taicpu(p).oper[1]^.reg := NewMMReg;
  3190. if ((TargetRef.offset mod 16) = 8) and
  3191. (
  3192. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3193. (TargetRef.base = current_procinfo.framepointer) or
  3194. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3195. ) then
  3196. taicpu(hp1).opcode := MovAligned
  3197. else
  3198. taicpu(hp1).opcode := MovUnaligned;
  3199. taicpu(hp1).opsize := S_XMM;
  3200. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3201. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3202. RemoveInstruction(hp2);
  3203. RemoveInstruction(hp3);
  3204. Result := True;
  3205. Exit;
  3206. end;
  3207. end;
  3208. end
  3209. else
  3210. begin
  3211. { See if the next references are 8 less rather than 8 greater }
  3212. Dec(SourceRef.offset, 16); { -8 the other way }
  3213. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3214. begin
  3215. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3216. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3217. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3218. GetNextInstruction(hp2, hp3) and
  3219. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3220. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3221. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3222. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3223. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3224. begin
  3225. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3226. if NewMMReg <> NR_NO then
  3227. begin
  3228. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3229. if ((SourceRef.offset mod 16) = 0) and
  3230. (
  3231. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3232. (SourceRef.base = current_procinfo.framepointer) or
  3233. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3234. ) then
  3235. taicpu(hp2).opcode := MovAligned
  3236. else
  3237. taicpu(hp2).opcode := MovUnaligned;
  3238. taicpu(hp2).opsize := S_XMM;
  3239. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3240. if ((TargetRef.offset mod 16) = 0) and
  3241. (
  3242. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3243. (TargetRef.base = current_procinfo.framepointer) or
  3244. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3245. ) then
  3246. taicpu(hp3).opcode := MovAligned
  3247. else
  3248. taicpu(hp3).opcode := MovUnaligned;
  3249. taicpu(hp3).opsize := S_XMM;
  3250. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3251. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3252. RemoveInstruction(hp1);
  3253. RemoveCurrentP(p, hp2);
  3254. Result := True;
  3255. Exit;
  3256. end;
  3257. end;
  3258. end;
  3259. end;
  3260. end;
  3261. {$endif x86_64}
  3262. end;
  3263. else
  3264. { The write target should be a reg or a ref }
  3265. InternalError(2021091601);
  3266. end;
  3267. else
  3268. ;
  3269. end
  3270. else
  3271. { %treg is used afterwards, but all eventualities
  3272. other than the first MOV instruction being a constant
  3273. are covered by DeepMOVOpt, so only check for that }
  3274. if (taicpu(p).oper[0]^.typ = top_const) and
  3275. (
  3276. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3277. not (cs_opt_size in current_settings.optimizerswitches) or
  3278. (taicpu(hp1).opsize = S_B)
  3279. ) and
  3280. (
  3281. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3282. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3283. ) then
  3284. begin
  3285. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3286. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3287. end;
  3288. end;
  3289. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3290. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3291. { mov reg1, mem1 or mov mem1, reg1
  3292. mov mem2, reg2 mov reg2, mem2}
  3293. begin
  3294. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3295. { mov reg1, mem1 or mov mem1, reg1
  3296. mov mem2, reg1 mov reg2, mem1}
  3297. begin
  3298. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3299. { Removes the second statement from
  3300. mov reg1, mem1/reg2
  3301. mov mem1/reg2, reg1 }
  3302. begin
  3303. if taicpu(p).oper[0]^.typ=top_reg then
  3304. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3305. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3306. RemoveInstruction(hp1);
  3307. Result:=true;
  3308. exit;
  3309. end
  3310. else
  3311. begin
  3312. TransferUsedRegs(TmpUsedRegs);
  3313. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3314. if (taicpu(p).oper[1]^.typ = top_ref) and
  3315. { mov reg1, mem1
  3316. mov mem2, reg1 }
  3317. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3320. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3321. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3322. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3323. { change to
  3324. mov reg1, mem1 mov reg1, mem1
  3325. mov mem2, reg1 cmp reg1, mem2
  3326. cmp mem1, reg1
  3327. }
  3328. begin
  3329. RemoveInstruction(hp2);
  3330. taicpu(hp1).opcode := A_CMP;
  3331. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3332. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3333. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3334. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3335. end;
  3336. end;
  3337. end
  3338. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3339. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3340. begin
  3341. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3342. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3343. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3344. end
  3345. else
  3346. begin
  3347. TransferUsedRegs(TmpUsedRegs);
  3348. if GetNextInstruction(hp1, hp2) and
  3349. MatchOpType(taicpu(p),top_ref,top_reg) and
  3350. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3351. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3352. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3353. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3354. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3355. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3356. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3357. { mov mem1, %reg1
  3358. mov %reg1, mem2
  3359. mov mem2, reg2
  3360. to:
  3361. mov mem1, reg2
  3362. mov reg2, mem2}
  3363. begin
  3364. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3365. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3366. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3367. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3368. RemoveInstruction(hp2);
  3369. Result := True;
  3370. end
  3371. {$ifdef i386}
  3372. { this is enabled for i386 only, as the rules to create the reg sets below
  3373. are too complicated for x86-64, so this makes this code too error prone
  3374. on x86-64
  3375. }
  3376. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3377. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3378. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3379. { mov mem1, reg1 mov mem1, reg1
  3380. mov reg1, mem2 mov reg1, mem2
  3381. mov mem2, reg2 mov mem2, reg1
  3382. to: to:
  3383. mov mem1, reg1 mov mem1, reg1
  3384. mov mem1, reg2 mov reg1, mem2
  3385. mov reg1, mem2
  3386. or (if mem1 depends on reg1
  3387. and/or if mem2 depends on reg2)
  3388. to:
  3389. mov mem1, reg1
  3390. mov reg1, mem2
  3391. mov reg1, reg2
  3392. }
  3393. begin
  3394. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3395. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3396. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3397. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3398. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3399. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3400. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3401. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3402. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3403. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3404. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3405. end
  3406. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3407. begin
  3408. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3409. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3410. end
  3411. else
  3412. begin
  3413. RemoveInstruction(hp2);
  3414. end
  3415. {$endif i386}
  3416. ;
  3417. end;
  3418. end
  3419. { movl [mem1],reg1
  3420. movl [mem1],reg2
  3421. to
  3422. movl [mem1],reg1
  3423. movl reg1,reg2
  3424. }
  3425. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3426. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3427. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3428. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3429. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3430. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3431. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3432. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3433. begin
  3434. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3435. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3436. end;
  3437. { movl const1,[mem1]
  3438. movl [mem1],reg1
  3439. to
  3440. movl const1,reg1
  3441. movl reg1,[mem1]
  3442. }
  3443. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3444. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3445. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3446. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3447. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3448. begin
  3449. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3450. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3451. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3452. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3453. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3454. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3455. Result:=true;
  3456. exit;
  3457. end;
  3458. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3459. { Change:
  3460. movl %reg1,%reg2
  3461. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3462. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3463. To:
  3464. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3465. movl x(%reg1),%reg1
  3466. movl %reg1,%regX
  3467. }
  3468. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3469. begin
  3470. p_SourceReg := taicpu(p).oper[0]^.reg;
  3471. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3472. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3473. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3474. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3475. GetNextInstruction(hp1, hp2) and
  3476. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3477. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3478. begin
  3479. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3480. if RegInRef(p_TargetReg, SourceRef) and
  3481. { If %reg1 also appears in the second reference, then it will
  3482. not refer to the same memory block as the first reference }
  3483. not RegInRef(p_SourceReg, SourceRef) then
  3484. begin
  3485. { Check to see if the references match if %reg2 is changed to %reg1 }
  3486. if SourceRef.base = p_TargetReg then
  3487. SourceRef.base := p_SourceReg;
  3488. if SourceRef.index = p_TargetReg then
  3489. SourceRef.index := p_SourceReg;
  3490. { RefsEqual also checks to ensure both references are non-volatile }
  3491. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3492. begin
  3493. taicpu(hp2).loadreg(0, p_SourceReg);
  3494. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3495. Result := True;
  3496. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3497. begin
  3498. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3499. RemoveCurrentP(p, hp1);
  3500. Exit;
  3501. end
  3502. else
  3503. begin
  3504. { Check to see if %reg2 is no longer in use }
  3505. TransferUsedRegs(TmpUsedRegs);
  3506. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3507. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3508. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3509. begin
  3510. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3511. RemoveCurrentP(p, hp1);
  3512. Exit;
  3513. end;
  3514. end;
  3515. { If we reach this point, p and hp1 weren't actually modified,
  3516. so we can do a bit more work on this pass }
  3517. end;
  3518. end;
  3519. end;
  3520. end;
  3521. end;
  3522. { search further than the next instruction for a mov (as long as it's not a jump) }
  3523. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3524. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3525. (taicpu(p).oper[1]^.typ = top_reg) and
  3526. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3527. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3528. begin
  3529. { we work with hp2 here, so hp1 can be still used later on when
  3530. checking for GetNextInstruction_p }
  3531. hp3 := hp1;
  3532. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3533. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3534. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3535. TransferUsedRegs(TmpUsedRegs);
  3536. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3537. if NotFirstIteration then
  3538. JumpTracking := TLinkedList.Create
  3539. else
  3540. JumpTracking := nil;
  3541. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3542. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3543. (hp2.typ=ait_instruction) do
  3544. begin
  3545. case taicpu(hp2).opcode of
  3546. A_POP:
  3547. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3548. begin
  3549. if not CrossJump and
  3550. not RegUsedBetween(p_TargetReg, p, hp2) then
  3551. begin
  3552. { We can remove the original MOV since the register
  3553. wasn't used between it and its popping from the stack }
  3554. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3555. RemoveCurrentp(p, hp1);
  3556. Result := True;
  3557. JumpTracking.Free;
  3558. Exit;
  3559. end;
  3560. { Can't go any further }
  3561. Break;
  3562. end;
  3563. A_MOV:
  3564. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3565. ((taicpu(p).oper[0]^.typ=top_const) or
  3566. ((taicpu(p).oper[0]^.typ=top_reg) and
  3567. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3568. )
  3569. ) then
  3570. begin
  3571. { we have
  3572. mov x, %treg
  3573. mov %treg, y
  3574. }
  3575. { We don't need to call UpdateUsedRegs for every instruction between
  3576. p and hp2 because the register we're concerned about will not
  3577. become deallocated (otherwise GetNextInstructionUsingReg would
  3578. have stopped at an earlier instruction). [Kit] }
  3579. TempRegUsed :=
  3580. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3581. RegReadByInstruction(p_TargetReg, hp3) or
  3582. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3583. case taicpu(p).oper[0]^.typ Of
  3584. top_reg:
  3585. begin
  3586. { change
  3587. mov %reg, %treg
  3588. mov %treg, y
  3589. to
  3590. mov %reg, y
  3591. }
  3592. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3593. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3594. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3595. begin
  3596. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3597. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3598. if TempRegUsed then
  3599. begin
  3600. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3601. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3602. { Set the start of the next GetNextInstructionUsingRegCond search
  3603. to start at the entry right before hp2 (which is about to be removed) }
  3604. hp3 := tai(hp2.Previous);
  3605. RemoveInstruction(hp2);
  3606. { See if there's more we can optimise }
  3607. Continue;
  3608. end
  3609. else
  3610. begin
  3611. RemoveInstruction(hp2);
  3612. { We can remove the original MOV too }
  3613. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3614. RemoveCurrentP(p, hp1);
  3615. Result:=true;
  3616. JumpTracking.Free;
  3617. Exit;
  3618. end;
  3619. end
  3620. else
  3621. begin
  3622. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3623. taicpu(hp2).loadReg(0, p_SourceReg);
  3624. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3625. { Check to see if the register also appears in the reference }
  3626. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3627. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3628. { Don't remove the first instruction if the temporary register is in use }
  3629. if not TempRegUsed and
  3630. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3631. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3632. begin
  3633. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3634. RemoveCurrentP(p, hp1);
  3635. Result:=true;
  3636. JumpTracking.Free;
  3637. Exit;
  3638. end;
  3639. { No need to set Result to True here. If there's another instruction later
  3640. on that can be optimised, it will be detected when the main Pass 1 loop
  3641. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3642. end;
  3643. end;
  3644. top_const:
  3645. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3646. begin
  3647. { change
  3648. mov const, %treg
  3649. mov %treg, y
  3650. to
  3651. mov const, y
  3652. }
  3653. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3654. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3655. begin
  3656. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3657. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3658. if TempRegUsed then
  3659. begin
  3660. { Don't remove the first instruction if the temporary register is in use }
  3661. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3662. { No need to set Result to True. If there's another instruction later on
  3663. that can be optimised, it will be detected when the main Pass 1 loop
  3664. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3665. end
  3666. else
  3667. begin
  3668. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3669. RemoveCurrentP(p, hp1);
  3670. Result:=true;
  3671. Exit;
  3672. end;
  3673. end;
  3674. end;
  3675. else
  3676. Internalerror(2019103001);
  3677. end;
  3678. end
  3679. else
  3680. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3681. begin
  3682. if not CrossJump and
  3683. not RegUsedBetween(p_TargetReg, p, hp2) and
  3684. not RegReadByInstruction(p_TargetReg, hp2) then
  3685. begin
  3686. { Register is not used before it is overwritten }
  3687. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3688. RemoveCurrentp(p, hp1);
  3689. Result := True;
  3690. Exit;
  3691. end;
  3692. if (taicpu(p).oper[0]^.typ = top_const) and
  3693. (taicpu(hp2).oper[0]^.typ = top_const) then
  3694. begin
  3695. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3696. begin
  3697. { Same value - register hasn't changed }
  3698. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3699. RemoveInstruction(hp2);
  3700. Result := True;
  3701. { See if there's more we can optimise }
  3702. Continue;
  3703. end;
  3704. end;
  3705. end;
  3706. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3707. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3708. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3709. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3710. begin
  3711. {
  3712. Change from:
  3713. mov ###, %reg
  3714. ...
  3715. movs/z %reg,%reg (Same register, just different sizes)
  3716. To:
  3717. movs/z ###, %reg (Longer version)
  3718. ...
  3719. (remove)
  3720. }
  3721. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3722. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3723. { Keep the first instruction as mov if ### is a constant }
  3724. if taicpu(p).oper[0]^.typ = top_const then
  3725. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3726. else
  3727. begin
  3728. taicpu(p).opcode := taicpu(hp2).opcode;
  3729. taicpu(p).opsize := taicpu(hp2).opsize;
  3730. end;
  3731. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3732. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3733. RemoveInstruction(hp2);
  3734. Result := True;
  3735. JumpTracking.Free;
  3736. Exit;
  3737. end;
  3738. else
  3739. { Move down to the MatchOpType if-block below };
  3740. end;
  3741. { Also catches MOV/S/Z instructions that aren't modified }
  3742. if taicpu(p).oper[0]^.typ = top_reg then
  3743. begin
  3744. p_SourceReg := taicpu(p).oper[0]^.reg;
  3745. if
  3746. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3747. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3748. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3749. begin
  3750. Result := True;
  3751. { Just in case something didn't get modified (e.g. an
  3752. implicit register). Also, if it does read from this
  3753. register, then there's no longer an advantage to
  3754. changing the register on subsequent instructions.}
  3755. if not RegReadByInstruction(p_TargetReg, hp2) then
  3756. begin
  3757. { If a conditional jump was crossed, do not delete
  3758. the original MOV no matter what }
  3759. if not CrossJump and
  3760. { RegEndOfLife returns True if the register is
  3761. deallocated before the next instruction or has
  3762. been loaded with a new value }
  3763. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3764. begin
  3765. { We can remove the original MOV }
  3766. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3767. RemoveCurrentp(p, hp1);
  3768. JumpTracking.Free;
  3769. Result := True;
  3770. Exit;
  3771. end;
  3772. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3773. begin
  3774. { See if there's more we can optimise }
  3775. hp3 := hp2;
  3776. Continue;
  3777. end;
  3778. end;
  3779. end;
  3780. end;
  3781. { Break out of the while loop under normal circumstances }
  3782. Break;
  3783. end;
  3784. JumpTracking.Free;
  3785. end;
  3786. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3787. (taicpu(p).oper[1]^.typ = top_reg) and
  3788. (taicpu(p).opsize = S_L) and
  3789. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3790. (taicpu(hp2).opcode = A_AND) and
  3791. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3792. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3793. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3794. ) then
  3795. begin
  3796. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3797. begin
  3798. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3799. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3800. begin
  3801. { Optimize out:
  3802. mov x, %reg
  3803. and ffffffffh, %reg
  3804. }
  3805. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3806. RemoveInstruction(hp2);
  3807. Result:=true;
  3808. exit;
  3809. end;
  3810. end;
  3811. end;
  3812. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3813. x >= RetOffset) as it doesn't do anything (it writes either to a
  3814. parameter or to the temporary storage room for the function
  3815. result)
  3816. }
  3817. if IsExitCode(hp1) and
  3818. (taicpu(p).oper[1]^.typ = top_ref) and
  3819. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3820. (
  3821. (
  3822. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3823. not (
  3824. assigned(current_procinfo.procdef.funcretsym) and
  3825. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3826. )
  3827. ) or
  3828. { Also discard writes to the stack that are below the base pointer,
  3829. as this is temporary storage rather than a function result on the
  3830. stack, say. }
  3831. (
  3832. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3833. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3834. )
  3835. ) then
  3836. begin
  3837. RemoveCurrentp(p, hp1);
  3838. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3839. RemoveLastDeallocForFuncRes(p);
  3840. Result:=true;
  3841. exit;
  3842. end;
  3843. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3844. begin
  3845. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3846. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3847. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3848. begin
  3849. { change
  3850. mov reg1, mem1
  3851. test/cmp x, mem1
  3852. to
  3853. mov reg1, mem1
  3854. test/cmp x, reg1
  3855. }
  3856. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3857. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3858. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3859. Result := True;
  3860. Exit;
  3861. end;
  3862. if DoMovCmpMemOpt(p, hp1, True) then
  3863. begin
  3864. Result := True;
  3865. Exit;
  3866. end;
  3867. end;
  3868. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3869. { If the flags register is in use, don't change the instruction to an
  3870. ADD otherwise this will scramble the flags. [Kit] }
  3871. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3872. begin
  3873. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3874. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3875. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3876. ) or
  3877. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3878. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3879. )
  3880. ) then
  3881. { mov reg1,ref
  3882. lea reg2,[reg1,reg2]
  3883. to
  3884. add reg2,ref}
  3885. begin
  3886. TransferUsedRegs(TmpUsedRegs);
  3887. { reg1 may not be used afterwards }
  3888. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3889. begin
  3890. Taicpu(hp1).opcode:=A_ADD;
  3891. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3892. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3893. RemoveCurrentp(p, hp1);
  3894. result:=true;
  3895. exit;
  3896. end;
  3897. end;
  3898. { If the LEA instruction can be converted into an arithmetic instruction,
  3899. it may be possible to then fold it in the next optimisation, otherwise
  3900. there's nothing more that can be optimised here. }
  3901. if not ConvertLEA(taicpu(hp1)) then
  3902. Exit;
  3903. end;
  3904. if (taicpu(p).oper[1]^.typ = top_reg) and
  3905. (hp1.typ = ait_instruction) and
  3906. GetNextInstruction(hp1, hp2) and
  3907. MatchInstruction(hp2,A_MOV,[]) and
  3908. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3909. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3910. (
  3911. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3912. {$ifdef x86_64}
  3913. or
  3914. (
  3915. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3916. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3917. )
  3918. {$endif x86_64}
  3919. ) then
  3920. begin
  3921. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3922. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3923. { change movsX/movzX reg/ref, reg2
  3924. add/sub/or/... reg3/$const, reg2
  3925. mov reg2 reg/ref
  3926. dealloc reg2
  3927. to
  3928. add/sub/or/... reg3/$const, reg/ref }
  3929. begin
  3930. TransferUsedRegs(TmpUsedRegs);
  3931. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3932. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3933. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3934. begin
  3935. { by example:
  3936. movswl %si,%eax movswl %si,%eax p
  3937. decl %eax addl %edx,%eax hp1
  3938. movw %ax,%si movw %ax,%si hp2
  3939. ->
  3940. movswl %si,%eax movswl %si,%eax p
  3941. decw %eax addw %edx,%eax hp1
  3942. movw %ax,%si movw %ax,%si hp2
  3943. }
  3944. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3945. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3946. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3947. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3948. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3949. {
  3950. ->
  3951. movswl %si,%eax movswl %si,%eax p
  3952. decw %si addw %dx,%si hp1
  3953. movw %ax,%si movw %ax,%si hp2
  3954. }
  3955. case taicpu(hp1).ops of
  3956. 1:
  3957. begin
  3958. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3959. if taicpu(hp1).oper[0]^.typ=top_reg then
  3960. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3961. end;
  3962. 2:
  3963. begin
  3964. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3965. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3966. (taicpu(hp1).opcode<>A_SHL) and
  3967. (taicpu(hp1).opcode<>A_SHR) and
  3968. (taicpu(hp1).opcode<>A_SAR) then
  3969. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3970. end;
  3971. else
  3972. internalerror(2008042701);
  3973. end;
  3974. {
  3975. ->
  3976. decw %si addw %dx,%si p
  3977. }
  3978. RemoveInstruction(hp2);
  3979. RemoveCurrentP(p, hp1);
  3980. Result:=True;
  3981. Exit;
  3982. end;
  3983. end;
  3984. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3985. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3986. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3987. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3988. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3989. )
  3990. {$ifdef i386}
  3991. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3992. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3993. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3994. {$endif i386}
  3995. then
  3996. { change movsX/movzX reg/ref, reg2
  3997. add/sub/or/... regX/$const, reg2
  3998. mov reg2, reg3
  3999. dealloc reg2
  4000. to
  4001. movsX/movzX reg/ref, reg3
  4002. add/sub/or/... reg3/$const, reg3
  4003. }
  4004. begin
  4005. TransferUsedRegs(TmpUsedRegs);
  4006. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4007. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4008. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4009. begin
  4010. { by example:
  4011. movswl %si,%eax movswl %si,%eax p
  4012. decl %eax addl %edx,%eax hp1
  4013. movw %ax,%si movw %ax,%si hp2
  4014. ->
  4015. movswl %si,%eax movswl %si,%eax p
  4016. decw %eax addw %edx,%eax hp1
  4017. movw %ax,%si movw %ax,%si hp2
  4018. }
  4019. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4020. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4021. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4022. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4023. { limit size of constants as well to avoid assembler errors, but
  4024. check opsize to avoid overflow when left shifting the 1 }
  4025. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4026. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4027. {$ifdef x86_64}
  4028. { Be careful of, for example:
  4029. movl %reg1,%reg2
  4030. addl %reg3,%reg2
  4031. movq %reg2,%reg4
  4032. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4033. }
  4034. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4035. begin
  4036. taicpu(hp2).changeopsize(S_L);
  4037. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4038. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4039. end;
  4040. {$endif x86_64}
  4041. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4042. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4043. if taicpu(p).oper[0]^.typ=top_reg then
  4044. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4045. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4046. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4047. {
  4048. ->
  4049. movswl %si,%eax movswl %si,%eax p
  4050. decw %si addw %dx,%si hp1
  4051. movw %ax,%si movw %ax,%si hp2
  4052. }
  4053. case taicpu(hp1).ops of
  4054. 1:
  4055. begin
  4056. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4057. if taicpu(hp1).oper[0]^.typ=top_reg then
  4058. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4059. end;
  4060. 2:
  4061. begin
  4062. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4063. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4064. (taicpu(hp1).opcode<>A_SHL) and
  4065. (taicpu(hp1).opcode<>A_SHR) and
  4066. (taicpu(hp1).opcode<>A_SAR) then
  4067. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4068. end;
  4069. else
  4070. internalerror(2018111801);
  4071. end;
  4072. {
  4073. ->
  4074. decw %si addw %dx,%si p
  4075. }
  4076. RemoveInstruction(hp2);
  4077. end;
  4078. end;
  4079. end;
  4080. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4081. GetNextInstruction(hp1, hp2) and
  4082. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4083. MatchOperand(Taicpu(p).oper[0]^,0) and
  4084. (Taicpu(p).oper[1]^.typ = top_reg) and
  4085. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4086. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4087. { mov reg1,0
  4088. bts reg1,operand1 --> mov reg1,operand2
  4089. or reg1,operand2 bts reg1,operand1}
  4090. begin
  4091. Taicpu(hp2).opcode:=A_MOV;
  4092. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4093. asml.remove(hp1);
  4094. insertllitem(hp2,hp2.next,hp1);
  4095. RemoveCurrentp(p, hp1);
  4096. Result:=true;
  4097. exit;
  4098. end;
  4099. {
  4100. mov ref,reg0
  4101. <op> reg0,reg1
  4102. dealloc reg0
  4103. to
  4104. <op> ref,reg1
  4105. }
  4106. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4107. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4108. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4109. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4110. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4111. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4112. begin
  4113. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4114. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4115. RemoveCurrentp(p, hp1);
  4116. Result:=true;
  4117. exit;
  4118. end;
  4119. {$ifdef x86_64}
  4120. { Convert:
  4121. movq x(ref),%reg64
  4122. shrq y,%reg64
  4123. To:
  4124. movl x+4(ref),%reg32
  4125. shrl y-32,%reg32 (Remove if y = 32)
  4126. }
  4127. if (taicpu(p).opsize = S_Q) and
  4128. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4129. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4130. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4131. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4132. (taicpu(hp1).oper[0]^.val >= 32) and
  4133. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4134. begin
  4135. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4136. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4137. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4138. { Convert to 32-bit }
  4139. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4140. taicpu(p).opsize := S_L;
  4141. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4142. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4143. if (taicpu(hp1).oper[0]^.val = 32) then
  4144. begin
  4145. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4146. RemoveInstruction(hp1);
  4147. end
  4148. else
  4149. begin
  4150. { This will potentially open up more arithmetic operations since
  4151. the peephole optimizer now has a big hint that only the lower
  4152. 32 bits are currently in use (and opcodes are smaller in size) }
  4153. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4154. taicpu(hp1).opsize := S_L;
  4155. Dec(taicpu(hp1).oper[0]^.val, 32);
  4156. DebugMsg(SPeepholeOptimization + PreMessage +
  4157. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4158. end;
  4159. Result := True;
  4160. Exit;
  4161. end;
  4162. {$endif x86_64}
  4163. { Backward optimisation. If we have:
  4164. func. %reg1,%reg2
  4165. mov %reg2,%reg3
  4166. (dealloc %reg2)
  4167. Change to:
  4168. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4169. }
  4170. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4171. begin
  4172. p_SourceReg := taicpu(p).oper[0]^.reg;
  4173. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4174. TransferUsedRegs(TmpUsedRegs);
  4175. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4176. GetLastInstruction(p, hp2) and
  4177. (hp2.typ = ait_instruction) and
  4178. { Have to make sure it's an instruction that only reads from
  4179. operand 1 and only writes (not reads or modifies) from operand 2;
  4180. in essence, a one-operand pure function such as BSR or POPCNT }
  4181. (taicpu(hp2).ops = 2) and
  4182. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4183. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4184. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4185. begin
  4186. case taicpu(hp2).opcode of
  4187. A_FSTSW, A_FNSTSW,
  4188. A_IN, A_INS, A_OUT, A_OUTS,
  4189. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4190. { These routines have explicit operands, but they are restricted in
  4191. what they can be (e.g. IN and OUT can only read from AL, AX or
  4192. EAX. }
  4193. ;
  4194. else
  4195. begin
  4196. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4197. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4198. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4199. RemoveCurrentp(p, hp1);
  4200. Result := True;
  4201. Exit;
  4202. end;
  4203. end;
  4204. end;
  4205. end;
  4206. end;
  4207. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4208. var
  4209. hp1 : tai;
  4210. begin
  4211. Result:=false;
  4212. if taicpu(p).ops <> 2 then
  4213. exit;
  4214. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4215. GetNextInstruction(p,hp1) then
  4216. begin
  4217. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4218. (taicpu(hp1).ops = 2) then
  4219. begin
  4220. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4221. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4222. { movXX reg1, mem1 or movXX mem1, reg1
  4223. movXX mem2, reg2 movXX reg2, mem2}
  4224. begin
  4225. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4226. { movXX reg1, mem1 or movXX mem1, reg1
  4227. movXX mem2, reg1 movXX reg2, mem1}
  4228. begin
  4229. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4230. begin
  4231. { Removes the second statement from
  4232. movXX reg1, mem1/reg2
  4233. movXX mem1/reg2, reg1
  4234. }
  4235. if taicpu(p).oper[0]^.typ=top_reg then
  4236. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4237. { Removes the second statement from
  4238. movXX mem1/reg1, reg2
  4239. movXX reg2, mem1/reg1
  4240. }
  4241. if (taicpu(p).oper[1]^.typ=top_reg) and
  4242. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4243. begin
  4244. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4245. RemoveInstruction(hp1);
  4246. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4247. Result:=true;
  4248. exit;
  4249. end
  4250. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4251. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4252. begin
  4253. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4254. RemoveInstruction(hp1);
  4255. Result:=true;
  4256. exit;
  4257. end;
  4258. end
  4259. end;
  4260. end;
  4261. end;
  4262. end;
  4263. end;
  4264. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4265. var
  4266. hp1 : tai;
  4267. begin
  4268. result:=false;
  4269. { replace
  4270. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4271. MovX %mreg2,%mreg1
  4272. dealloc %mreg2
  4273. by
  4274. <Op>X %mreg2,%mreg1
  4275. ?
  4276. }
  4277. if GetNextInstruction(p,hp1) and
  4278. { we mix single and double opperations here because we assume that the compiler
  4279. generates vmovapd only after double operations and vmovaps only after single operations }
  4280. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4281. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4282. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4283. (taicpu(p).oper[0]^.typ=top_reg) then
  4284. begin
  4285. TransferUsedRegs(TmpUsedRegs);
  4286. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4287. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4288. begin
  4289. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4290. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4291. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4292. RemoveInstruction(hp1);
  4293. result:=true;
  4294. end;
  4295. end;
  4296. end;
  4297. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4298. var
  4299. hp1, p_label, p_dist, hp1_dist: tai;
  4300. JumpLabel, JumpLabel_dist: TAsmLabel;
  4301. FirstValue, SecondValue: TCGInt;
  4302. begin
  4303. Result := False;
  4304. if (taicpu(p).oper[0]^.typ = top_const) and
  4305. (taicpu(p).oper[0]^.val <> -1) then
  4306. begin
  4307. { Convert unsigned maximum constants to -1 to aid optimisation }
  4308. case taicpu(p).opsize of
  4309. S_B:
  4310. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4311. begin
  4312. taicpu(p).oper[0]^.val := -1;
  4313. Result := True;
  4314. Exit;
  4315. end;
  4316. S_W:
  4317. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4318. begin
  4319. taicpu(p).oper[0]^.val := -1;
  4320. Result := True;
  4321. Exit;
  4322. end;
  4323. S_L:
  4324. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4325. begin
  4326. taicpu(p).oper[0]^.val := -1;
  4327. Result := True;
  4328. Exit;
  4329. end;
  4330. {$ifdef x86_64}
  4331. S_Q:
  4332. { Storing anything greater than $7FFFFFFF is not possible so do
  4333. nothing };
  4334. {$endif x86_64}
  4335. else
  4336. InternalError(2021121001);
  4337. end;
  4338. end;
  4339. if GetNextInstruction(p, hp1) and
  4340. TrySwapMovCmp(p, hp1) then
  4341. begin
  4342. Result := True;
  4343. Exit;
  4344. end;
  4345. { Search for:
  4346. test $x,(reg/ref)
  4347. jne @lbl1
  4348. test $y,(reg/ref) (same register or reference)
  4349. jne @lbl1
  4350. Change to:
  4351. test $(x or y),(reg/ref)
  4352. jne @lbl1
  4353. (Note, this doesn't work with je instead of jne)
  4354. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4355. Also search for:
  4356. test $x,(reg/ref)
  4357. je @lbl1
  4358. test $y,(reg/ref)
  4359. je/jne @lbl2
  4360. If (x or y) = x, then the second jump is deterministic
  4361. }
  4362. if (
  4363. (
  4364. (taicpu(p).oper[0]^.typ = top_const) or
  4365. (
  4366. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4367. (taicpu(p).oper[0]^.typ = top_reg) and
  4368. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4369. )
  4370. ) and
  4371. MatchInstruction(hp1, A_JCC, [])
  4372. ) then
  4373. begin
  4374. if (taicpu(p).oper[0]^.typ = top_reg) and
  4375. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4376. FirstValue := -1
  4377. else
  4378. FirstValue := taicpu(p).oper[0]^.val;
  4379. { If we have several test/jne's in a row, it might be the case that
  4380. the second label doesn't go to the same location, but the one
  4381. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4382. so accommodate for this with a while loop.
  4383. }
  4384. hp1_dist := hp1;
  4385. if GetNextInstruction(hp1, p_dist) and
  4386. (p_dist.typ = ait_instruction) and
  4387. (
  4388. (
  4389. (taicpu(p_dist).opcode = A_TEST) and
  4390. (
  4391. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4392. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4393. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4394. )
  4395. ) or
  4396. (
  4397. { cmp 0,%reg = test %reg,%reg }
  4398. (taicpu(p_dist).opcode = A_CMP) and
  4399. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4400. )
  4401. ) and
  4402. { Make sure the destination operands are actually the same }
  4403. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4404. GetNextInstruction(p_dist, hp1_dist) and
  4405. MatchInstruction(hp1_dist, A_JCC, []) then
  4406. begin
  4407. if
  4408. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4409. (
  4410. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4411. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4412. ) then
  4413. SecondValue := -1
  4414. else
  4415. SecondValue := taicpu(p_dist).oper[0]^.val;
  4416. { If both of the TEST constants are identical, delete the second
  4417. TEST that is unnecessary. }
  4418. if (FirstValue = SecondValue) then
  4419. begin
  4420. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4421. RemoveInstruction(p_dist);
  4422. { Don't let the flags register become deallocated and reallocated between the jumps }
  4423. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4424. Result := True;
  4425. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4426. begin
  4427. { Since the second jump's condition is a subset of the first, we
  4428. know it will never branch because the first jump dominates it.
  4429. Get it out of the way now rather than wait for the jump
  4430. optimisations for a speed boost. }
  4431. if IsJumpToLabel(taicpu(hp1_dist)) then
  4432. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4433. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4434. RemoveInstruction(hp1_dist);
  4435. end
  4436. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4437. begin
  4438. { If the inverse of the first condition is a subset of the second,
  4439. the second one will definitely branch if the first one doesn't }
  4440. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4441. MakeUnconditional(taicpu(hp1_dist));
  4442. RemoveDeadCodeAfterJump(hp1_dist);
  4443. end;
  4444. Exit;
  4445. end;
  4446. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4447. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4448. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4449. then the second jump will never branch, so it can also be
  4450. removed regardless of where it goes }
  4451. (
  4452. (FirstValue = -1) or
  4453. (SecondValue = -1) or
  4454. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4455. ) then
  4456. begin
  4457. { Same jump location... can be a register since nothing's changed }
  4458. { If any of the entries are equivalent to test %reg,%reg, then the
  4459. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4460. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4461. if IsJumpToLabel(taicpu(hp1_dist)) then
  4462. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4463. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4464. RemoveInstruction(hp1_dist);
  4465. { Only remove the second test if no jumps or other conditional instructions follow }
  4466. TransferUsedRegs(TmpUsedRegs);
  4467. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4468. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4469. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4470. RemoveInstruction(p_dist);
  4471. Result := True;
  4472. Exit;
  4473. end;
  4474. end;
  4475. end;
  4476. { Search for:
  4477. test %reg,%reg
  4478. j(c1) @lbl1
  4479. ...
  4480. @lbl:
  4481. test %reg,%reg (same register)
  4482. j(c2) @lbl2
  4483. If c2 is a subset of c1, change to:
  4484. test %reg,%reg
  4485. j(c1) @lbl2
  4486. (@lbl1 may become a dead label as a result)
  4487. }
  4488. if (taicpu(p).oper[1]^.typ = top_reg) and
  4489. (taicpu(p).oper[0]^.typ = top_reg) and
  4490. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4491. MatchInstruction(hp1, A_JCC, []) and
  4492. IsJumpToLabel(taicpu(hp1)) then
  4493. begin
  4494. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4495. p_label := nil;
  4496. if Assigned(JumpLabel) then
  4497. p_label := getlabelwithsym(JumpLabel);
  4498. if Assigned(p_label) and
  4499. GetNextInstruction(p_label, p_dist) and
  4500. MatchInstruction(p_dist, A_TEST, []) and
  4501. { It's fine if the second test uses smaller sub-registers }
  4502. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4503. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4504. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4505. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4506. GetNextInstruction(p_dist, hp1_dist) and
  4507. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4508. begin
  4509. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4510. if JumpLabel = JumpLabel_dist then
  4511. { This is an infinite loop }
  4512. Exit;
  4513. { Best optimisation when the first condition is a subset (or equal) of the second }
  4514. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4515. begin
  4516. { Any registers used here will already be allocated }
  4517. if Assigned(JumpLabel_dist) then
  4518. JumpLabel_dist.IncRefs;
  4519. if Assigned(JumpLabel) then
  4520. JumpLabel.DecRefs;
  4521. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4522. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4523. Result := True;
  4524. Exit;
  4525. end;
  4526. end;
  4527. end;
  4528. end;
  4529. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4530. var
  4531. hp1, hp2: tai;
  4532. ActiveReg: TRegister;
  4533. OldOffset: asizeint;
  4534. ThisConst: TCGInt;
  4535. function RegDeallocated: Boolean;
  4536. begin
  4537. TransferUsedRegs(TmpUsedRegs);
  4538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4539. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4540. end;
  4541. begin
  4542. result:=false;
  4543. hp1 := nil;
  4544. { replace
  4545. addX const,%reg1
  4546. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4547. dealloc %reg1
  4548. by
  4549. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4550. }
  4551. if MatchOpType(taicpu(p),top_const,top_reg) then
  4552. begin
  4553. ActiveReg := taicpu(p).oper[1]^.reg;
  4554. { Ensures the entire register was updated }
  4555. if (taicpu(p).opsize >= S_L) and
  4556. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4557. MatchInstruction(hp1,A_LEA,[]) and
  4558. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4559. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4560. (
  4561. { Cover the case where the register in the reference is also the destination register }
  4562. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4563. (
  4564. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4565. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4566. RegDeallocated
  4567. )
  4568. ) then
  4569. begin
  4570. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4571. {$push}
  4572. {$R-}{$Q-}
  4573. { Explicitly disable overflow checking for these offset calculation
  4574. as those do not matter for the final result }
  4575. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4576. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4577. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4578. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4579. {$pop}
  4580. {$ifdef x86_64}
  4581. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4582. begin
  4583. { Overflow; abort }
  4584. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4585. end
  4586. else
  4587. {$endif x86_64}
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4590. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4591. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4592. RemoveCurrentP(p, hp1)
  4593. else
  4594. RemoveCurrentP(p);
  4595. result:=true;
  4596. Exit;
  4597. end;
  4598. end;
  4599. if (
  4600. { Save calling GetNextInstructionUsingReg again }
  4601. Assigned(hp1) or
  4602. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4603. ) and
  4604. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4605. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4606. begin
  4607. if taicpu(hp1).oper[0]^.typ = top_const then
  4608. begin
  4609. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4610. if taicpu(hp1).opcode = A_ADD then
  4611. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4612. else
  4613. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4614. Result := True;
  4615. { Handle any overflows }
  4616. case taicpu(p).opsize of
  4617. S_B:
  4618. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4619. S_W:
  4620. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4621. S_L:
  4622. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4623. {$ifdef x86_64}
  4624. S_Q:
  4625. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4626. { Overflow; abort }
  4627. Result := False
  4628. else
  4629. taicpu(p).oper[0]^.val := ThisConst;
  4630. {$endif x86_64}
  4631. else
  4632. InternalError(2021102610);
  4633. end;
  4634. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4635. if Result then
  4636. begin
  4637. if (taicpu(p).oper[0]^.val < 0) and
  4638. (
  4639. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4640. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4641. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4642. ) then
  4643. begin
  4644. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4645. taicpu(p).opcode := A_SUB;
  4646. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4647. end
  4648. else
  4649. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4650. RemoveInstruction(hp1);
  4651. end;
  4652. end
  4653. else
  4654. begin
  4655. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4656. TransferUsedRegs(TmpUsedRegs);
  4657. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4658. hp2 := p;
  4659. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4660. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4661. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4662. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4663. begin
  4664. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4665. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4666. Asml.Remove(p);
  4667. Asml.InsertAfter(p, hp1);
  4668. p := hp1;
  4669. Result := True;
  4670. end;
  4671. end;
  4672. end;
  4673. end;
  4674. end;
  4675. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4676. var
  4677. hp1: tai;
  4678. ref: Integer;
  4679. saveref: treference;
  4680. Multiple: TCGInt;
  4681. Adjacent: Boolean;
  4682. begin
  4683. Result:=false;
  4684. { play save and throw an error if LEA uses a seg register prefix,
  4685. this is most likely an error somewhere else }
  4686. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4687. internalerror(2022022001);
  4688. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4689. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4690. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4691. (
  4692. { do not mess with leas accessing the stack pointer
  4693. unless it's a null operation }
  4694. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4695. (
  4696. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4697. (taicpu(p).oper[0]^.ref^.offset = 0)
  4698. )
  4699. ) and
  4700. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4701. begin
  4702. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4703. begin
  4704. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4705. begin
  4706. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4707. taicpu(p).oper[1]^.reg);
  4708. InsertLLItem(p.previous,p.next, hp1);
  4709. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4710. p.free;
  4711. p:=hp1;
  4712. end
  4713. else
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4716. RemoveCurrentP(p);
  4717. end;
  4718. Result:=true;
  4719. exit;
  4720. end
  4721. else if (
  4722. { continue to use lea to adjust the stack pointer,
  4723. it is the recommended way, but only if not optimizing for size }
  4724. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4725. (cs_opt_size in current_settings.optimizerswitches)
  4726. ) and
  4727. { If the flags register is in use, don't change the instruction
  4728. to an ADD otherwise this will scramble the flags. [Kit] }
  4729. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4730. ConvertLEA(taicpu(p)) then
  4731. begin
  4732. Result:=true;
  4733. exit;
  4734. end;
  4735. end;
  4736. { Don't optimise if the stack or frame pointer is the destination register }
  4737. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4738. Exit;
  4739. if GetNextInstruction(p,hp1) and
  4740. (hp1.typ=ait_instruction) then
  4741. begin
  4742. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4745. begin
  4746. TransferUsedRegs(TmpUsedRegs);
  4747. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4748. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4749. begin
  4750. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4751. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4752. RemoveInstruction(hp1);
  4753. result:=true;
  4754. exit;
  4755. end;
  4756. end;
  4757. { changes
  4758. lea <ref1>, reg1
  4759. <op> ...,<ref. with reg1>,...
  4760. to
  4761. <op> ...,<ref1>,... }
  4762. { find a reference which uses reg1 }
  4763. 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
  4764. ref:=0
  4765. 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
  4766. ref:=1
  4767. else
  4768. ref:=-1;
  4769. if (ref<>-1) and
  4770. { reg1 must be either the base or the index }
  4771. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4772. begin
  4773. { reg1 can be removed from the reference }
  4774. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4775. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4776. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4777. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4778. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4779. else
  4780. Internalerror(2019111201);
  4781. { check if the can insert all data of the lea into the second instruction }
  4782. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4783. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4784. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4785. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4786. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4787. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4788. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4789. {$ifdef x86_64}
  4790. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4791. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4792. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4793. )
  4794. {$endif x86_64}
  4795. then
  4796. begin
  4797. { reg1 might not used by the second instruction after it is remove from the reference }
  4798. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4799. begin
  4800. TransferUsedRegs(TmpUsedRegs);
  4801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4802. { reg1 is not updated so it might not be used afterwards }
  4803. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4804. begin
  4805. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4806. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4807. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4808. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4809. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4810. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4811. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4812. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4813. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4814. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4815. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4816. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4817. RemoveCurrentP(p, hp1);
  4818. result:=true;
  4819. exit;
  4820. end
  4821. end;
  4822. end;
  4823. { recover }
  4824. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4825. end;
  4826. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4827. if Adjacent or
  4828. { Check further ahead (up to 2 instructions ahead for -O2) }
  4829. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4830. begin
  4831. { Check common LEA/LEA conditions }
  4832. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4833. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4834. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4835. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4836. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4837. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4838. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4839. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4840. (
  4841. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4842. calling it (since it calls GetNextInstruction) }
  4843. Adjacent or
  4844. (
  4845. (
  4846. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4847. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4848. ) and (
  4849. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4850. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4851. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4852. )
  4853. )
  4854. ) then
  4855. begin
  4856. { changes
  4857. lea (regX,scale), reg1
  4858. lea offset(reg1,reg1), reg1
  4859. to
  4860. lea offset(regX,scale*2), reg1
  4861. and
  4862. lea (regX,scale1), reg1
  4863. lea offset(reg1,scale2), reg1
  4864. to
  4865. lea offset(regX,scale1*scale2), reg1
  4866. ... so long as the final scale does not exceed 8
  4867. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4868. }
  4869. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4870. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4871. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4872. (
  4873. (
  4874. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4875. ) or (
  4876. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4877. (
  4878. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4879. (
  4880. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4881. Adjacent or
  4882. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4883. )
  4884. )
  4885. )
  4886. ) and (
  4887. (
  4888. { lea (reg1,scale2), reg1 variant }
  4889. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4890. (
  4891. (
  4892. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4893. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4894. ) or (
  4895. { lea (regX,regX), reg1 variant }
  4896. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4897. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4898. )
  4899. )
  4900. ) or (
  4901. { lea (reg1,reg1), reg1 variant }
  4902. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4903. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4904. )
  4905. ) then
  4906. begin
  4907. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4908. { Make everything homogeneous to make calculations easier }
  4909. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4910. begin
  4911. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4912. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4913. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4914. else
  4915. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4916. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4917. end;
  4918. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4919. begin
  4920. { Just to prevent miscalculations }
  4921. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4922. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4923. else
  4924. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4925. end
  4926. else
  4927. begin
  4928. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4929. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4930. end;
  4931. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4932. RemoveCurrentP(p);
  4933. result:=true;
  4934. exit;
  4935. end
  4936. { changes
  4937. lea offset1(regX), reg1
  4938. lea offset2(reg1), reg1
  4939. to
  4940. lea offset1+offset2(regX), reg1 }
  4941. else if
  4942. (
  4943. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4944. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4945. ) or (
  4946. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4947. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4948. (
  4949. (
  4950. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4951. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4952. ) or (
  4953. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4954. (
  4955. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4956. (
  4957. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4958. (
  4959. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4960. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4961. )
  4962. )
  4963. )
  4964. )
  4965. )
  4966. ) then
  4967. begin
  4968. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4969. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4970. begin
  4971. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4972. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4973. { if the register is used as index and base, we have to increase for base as well
  4974. and adapt base }
  4975. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4976. begin
  4977. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4978. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4979. end;
  4980. end
  4981. else
  4982. begin
  4983. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4984. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4985. end;
  4986. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4987. begin
  4988. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4989. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4990. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4991. end;
  4992. RemoveCurrentP(p);
  4993. result:=true;
  4994. exit;
  4995. end;
  4996. end;
  4997. { Change:
  4998. leal/q $x(%reg1),%reg2
  4999. ...
  5000. shll/q $y,%reg2
  5001. To:
  5002. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5003. }
  5004. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5005. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5006. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5007. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5008. (taicpu(hp1).oper[0]^.val <= 3) then
  5009. begin
  5010. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5011. TransferUsedRegs(TmpUsedRegs);
  5012. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5013. if
  5014. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5015. (this works even if scalefactor is zero) }
  5016. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5017. { Ensure offset doesn't go out of bounds }
  5018. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5019. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5020. (
  5021. (
  5022. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5023. (
  5024. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5025. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5026. (
  5027. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5028. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5029. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5030. )
  5031. )
  5032. ) or (
  5033. (
  5034. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5035. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5036. ) and
  5037. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5038. )
  5039. ) then
  5040. begin
  5041. repeat
  5042. with taicpu(p).oper[0]^.ref^ do
  5043. begin
  5044. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5045. if index = base then
  5046. begin
  5047. if Multiple > 4 then
  5048. { Optimisation will no longer work because resultant
  5049. scale factor will exceed 8 }
  5050. Break;
  5051. base := NR_NO;
  5052. scalefactor := 2;
  5053. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5054. end
  5055. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5056. begin
  5057. { Scale factor only works on the index register }
  5058. index := base;
  5059. base := NR_NO;
  5060. end;
  5061. { For safety }
  5062. if scalefactor <= 1 then
  5063. begin
  5064. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5065. scalefactor := Multiple;
  5066. end
  5067. else
  5068. begin
  5069. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5070. scalefactor := scalefactor * Multiple;
  5071. end;
  5072. offset := offset * Multiple;
  5073. end;
  5074. RemoveInstruction(hp1);
  5075. Result := True;
  5076. Exit;
  5077. { This repeat..until loop exists for the benefit of Break }
  5078. until True;
  5079. end;
  5080. end;
  5081. end;
  5082. end;
  5083. end;
  5084. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5085. var
  5086. hp1 : tai;
  5087. begin
  5088. DoSubAddOpt := False;
  5089. if taicpu(p).oper[0]^.typ <> top_const then
  5090. { Should have been confirmed before calling }
  5091. InternalError(2021102601);
  5092. if GetLastInstruction(p, hp1) and
  5093. (hp1.typ = ait_instruction) and
  5094. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5095. case taicpu(hp1).opcode Of
  5096. A_DEC:
  5097. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5098. begin
  5099. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5100. RemoveInstruction(hp1);
  5101. end;
  5102. A_SUB:
  5103. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5104. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5105. begin
  5106. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5107. RemoveInstruction(hp1);
  5108. end;
  5109. A_ADD:
  5110. begin
  5111. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5112. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5113. begin
  5114. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5115. RemoveInstruction(hp1);
  5116. if (taicpu(p).oper[0]^.val = 0) then
  5117. begin
  5118. hp1 := tai(p.next);
  5119. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5120. if not GetLastInstruction(hp1, p) then
  5121. p := hp1;
  5122. DoSubAddOpt := True;
  5123. end
  5124. end;
  5125. end;
  5126. else
  5127. ;
  5128. end;
  5129. end;
  5130. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5131. begin
  5132. Result := False;
  5133. if UpdateTmpUsedRegs then
  5134. TransferUsedRegs(TmpUsedRegs);
  5135. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5136. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5137. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5138. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5139. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5140. (
  5141. (
  5142. (taicpu(hp1).opcode = A_TEST)
  5143. ) or (
  5144. (taicpu(hp1).opcode = A_CMP) and
  5145. { A sanity check more than anything }
  5146. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5147. )
  5148. ) then
  5149. begin
  5150. { change
  5151. mov mem, %reg
  5152. cmp/test x, %reg / test %reg,%reg
  5153. (reg deallocated)
  5154. to
  5155. cmp/test x, mem / cmp 0, mem
  5156. }
  5157. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5158. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5159. begin
  5160. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5161. if (taicpu(hp1).opcode = A_TEST) and
  5162. (
  5163. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5164. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5165. ) then
  5166. begin
  5167. taicpu(hp1).opcode := A_CMP;
  5168. taicpu(hp1).loadconst(0, 0);
  5169. end;
  5170. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5171. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5172. RemoveCurrentP(p, hp1);
  5173. Result := True;
  5174. Exit;
  5175. end;
  5176. end;
  5177. end;
  5178. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5179. var
  5180. hp2, hp3, hp4, hp5, hp6: tai;
  5181. ThisReg: TRegister;
  5182. JumpLoc: TAsmLabel;
  5183. begin
  5184. Result := False;
  5185. {
  5186. Convert:
  5187. j<c> .L1
  5188. .L2:
  5189. mov 1,reg
  5190. jmp .L3 (or ret, although it might not be a RET yet)
  5191. .L1:
  5192. mov 0,reg
  5193. jmp .L3 (or ret)
  5194. ( As long as .L3 <> .L1 or .L2)
  5195. To:
  5196. mov 0,reg
  5197. set<not(c)> reg
  5198. jmp .L3 (or ret)
  5199. .L2:
  5200. mov 1,reg
  5201. jmp .L3 (or ret)
  5202. .L1:
  5203. mov 0,reg
  5204. jmp .L3 (or ret)
  5205. }
  5206. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5207. Exit;
  5208. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5209. if GetNextInstruction(hp_label, hp2) and
  5210. MatchInstruction(hp2,A_MOV,[]) and
  5211. (taicpu(hp2).oper[0]^.typ = top_const) and
  5212. (
  5213. (
  5214. (taicpu(hp2).oper[1]^.typ = top_reg)
  5215. {$ifdef i386}
  5216. { Under i386, ESI, EDI, EBP and ESP
  5217. don't have an 8-bit representation }
  5218. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5219. {$endif i386}
  5220. ) or (
  5221. {$ifdef i386}
  5222. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5223. {$endif i386}
  5224. (taicpu(hp2).opsize = S_B)
  5225. )
  5226. ) and
  5227. GetNextInstruction(hp2, hp3) and
  5228. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5229. (
  5230. (taicpu(hp3).opcode=A_RET) or
  5231. (
  5232. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5233. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5234. )
  5235. ) and
  5236. GetNextInstruction(hp3, hp4) and
  5237. SkipAligns(hp4, hp4) and
  5238. (hp4.typ=ait_label) and
  5239. (tai_label(hp4).labsym=JumpLoc) and
  5240. (
  5241. not (cs_opt_size in current_settings.optimizerswitches) or
  5242. { If the initial jump is the label's only reference, then it will
  5243. become a dead label if the other conditions are met and hence
  5244. remove at least 2 instructions, including a jump }
  5245. (JumpLoc.getrefs = 1)
  5246. ) and
  5247. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5248. that will be optimised out }
  5249. GetNextInstruction(hp4, hp5) and
  5250. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5251. (taicpu(hp5).oper[0]^.typ = top_const) and
  5252. (
  5253. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5254. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5255. ) and
  5256. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5257. GetNextInstruction(hp5,hp6) and
  5258. (
  5259. (hp6.typ<>ait_label) or
  5260. SkipLabels(hp6, hp6)
  5261. ) and
  5262. (hp6.typ=ait_instruction) then
  5263. begin
  5264. { First, let's look at the two jumps that are hp3 and hp6 }
  5265. if not
  5266. (
  5267. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5268. (
  5269. (taicpu(hp6).opcode=A_RET) or
  5270. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5271. )
  5272. ) then
  5273. { If condition is False, then the JMP/RET instructions matched conventionally }
  5274. begin
  5275. { See if one of the jumps can be instantly converted into a RET }
  5276. if (taicpu(hp3).opcode=A_JMP) then
  5277. begin
  5278. { Reuse hp5 }
  5279. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5280. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5281. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5282. Exit;
  5283. if MatchInstruction(hp5, A_RET, []) then
  5284. begin
  5285. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5286. ConvertJumpToRET(hp3, hp5);
  5287. Result := True;
  5288. end
  5289. else
  5290. Exit;
  5291. end;
  5292. if (taicpu(hp6).opcode=A_JMP) then
  5293. begin
  5294. { Reuse hp5 }
  5295. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5296. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5297. Exit;
  5298. if MatchInstruction(hp5, A_RET, []) then
  5299. begin
  5300. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5301. ConvertJumpToRET(hp6, hp5);
  5302. Result := True;
  5303. end
  5304. else
  5305. Exit;
  5306. end;
  5307. if not
  5308. (
  5309. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5310. (
  5311. (taicpu(hp6).opcode=A_RET) or
  5312. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5313. )
  5314. ) then
  5315. { Still doesn't match }
  5316. Exit;
  5317. end;
  5318. if (taicpu(hp2).oper[0]^.val = 1) then
  5319. begin
  5320. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5321. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5322. end
  5323. else
  5324. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5325. if taicpu(hp2).opsize=S_B then
  5326. begin
  5327. if taicpu(hp2).oper[1]^.typ = top_reg then
  5328. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5329. else
  5330. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5331. hp2 := p;
  5332. end
  5333. else
  5334. begin
  5335. { Will be a register because the size can't be S_B otherwise }
  5336. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5337. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5338. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5339. { Inserting it right before p will guarantee that the flags are also tracked }
  5340. Asml.InsertBefore(hp2, p);
  5341. end;
  5342. taicpu(hp4).condition:=taicpu(p).condition;
  5343. asml.InsertBefore(hp4, hp2);
  5344. JumpLoc.decrefs;
  5345. if taicpu(hp3).opcode = A_JMP then
  5346. begin
  5347. MakeUnconditional(taicpu(p));
  5348. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5349. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5350. end
  5351. else
  5352. begin
  5353. taicpu(p).condition := C_None;
  5354. taicpu(p).opcode := A_RET;
  5355. taicpu(p).clearop(0);
  5356. taicpu(p).ops := 0;
  5357. end;
  5358. if (JumpLoc.getrefs = 0) then
  5359. RemoveDeadCodeAfterJump(hp3);
  5360. Result:=true;
  5361. exit;
  5362. end;
  5363. end;
  5364. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5365. var
  5366. hp1, hp2: tai;
  5367. ActiveReg: TRegister;
  5368. OldOffset: asizeint;
  5369. ThisConst: TCGInt;
  5370. function RegDeallocated: Boolean;
  5371. begin
  5372. TransferUsedRegs(TmpUsedRegs);
  5373. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5374. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5375. end;
  5376. begin
  5377. Result:=false;
  5378. hp1 := nil;
  5379. { replace
  5380. subX const,%reg1
  5381. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5382. dealloc %reg1
  5383. by
  5384. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5385. }
  5386. if MatchOpType(taicpu(p),top_const,top_reg) then
  5387. begin
  5388. ActiveReg := taicpu(p).oper[1]^.reg;
  5389. { Ensures the entire register was updated }
  5390. if (taicpu(p).opsize >= S_L) and
  5391. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5392. MatchInstruction(hp1,A_LEA,[]) and
  5393. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5394. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5395. (
  5396. { Cover the case where the register in the reference is also the destination register }
  5397. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5398. (
  5399. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5400. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5401. RegDeallocated
  5402. )
  5403. ) then
  5404. begin
  5405. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5406. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5407. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5408. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5409. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5410. {$ifdef x86_64}
  5411. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5412. begin
  5413. { Overflow; abort }
  5414. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5415. end
  5416. else
  5417. {$endif x86_64}
  5418. begin
  5419. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5420. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5421. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5422. RemoveCurrentP(p, hp1)
  5423. else
  5424. RemoveCurrentP(p);
  5425. result:=true;
  5426. Exit;
  5427. end;
  5428. end;
  5429. if (
  5430. { Save calling GetNextInstructionUsingReg again }
  5431. Assigned(hp1) or
  5432. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5433. ) and
  5434. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5435. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5436. begin
  5437. if taicpu(hp1).oper[0]^.typ = top_const then
  5438. begin
  5439. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5440. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5441. Result := True;
  5442. { Handle any overflows }
  5443. case taicpu(p).opsize of
  5444. S_B:
  5445. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5446. S_W:
  5447. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5448. S_L:
  5449. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5450. {$ifdef x86_64}
  5451. S_Q:
  5452. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5453. { Overflow; abort }
  5454. Result := False
  5455. else
  5456. taicpu(p).oper[0]^.val := ThisConst;
  5457. {$endif x86_64}
  5458. else
  5459. InternalError(2021102610);
  5460. end;
  5461. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5462. if Result then
  5463. begin
  5464. if (taicpu(p).oper[0]^.val < 0) and
  5465. (
  5466. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5467. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5468. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5469. ) then
  5470. begin
  5471. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5472. taicpu(p).opcode := A_SUB;
  5473. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5474. end
  5475. else
  5476. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5477. RemoveInstruction(hp1);
  5478. end;
  5479. end
  5480. else
  5481. begin
  5482. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5483. TransferUsedRegs(TmpUsedRegs);
  5484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5485. hp2 := p;
  5486. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5487. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5488. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5489. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5490. begin
  5491. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5492. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5493. Asml.Remove(p);
  5494. Asml.InsertAfter(p, hp1);
  5495. p := hp1;
  5496. Result := True;
  5497. Exit;
  5498. end;
  5499. end;
  5500. end;
  5501. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5502. { * change "sub/add const1, reg" or "dec reg" followed by
  5503. "sub const2, reg" to one "sub ..., reg" }
  5504. {$ifdef i386}
  5505. if (taicpu(p).oper[0]^.val = 2) and
  5506. (ActiveReg = NR_ESP) and
  5507. { Don't do the sub/push optimization if the sub }
  5508. { comes from setting up the stack frame (JM) }
  5509. (not(GetLastInstruction(p,hp1)) or
  5510. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5511. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5512. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5513. begin
  5514. hp1 := tai(p.next);
  5515. while Assigned(hp1) and
  5516. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5517. not RegReadByInstruction(NR_ESP,hp1) and
  5518. not RegModifiedByInstruction(NR_ESP,hp1) do
  5519. hp1 := tai(hp1.next);
  5520. if Assigned(hp1) and
  5521. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5522. begin
  5523. taicpu(hp1).changeopsize(S_L);
  5524. if taicpu(hp1).oper[0]^.typ=top_reg then
  5525. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5526. hp1 := tai(p.next);
  5527. RemoveCurrentp(p, hp1);
  5528. Result:=true;
  5529. exit;
  5530. end;
  5531. end;
  5532. {$endif i386}
  5533. if DoSubAddOpt(p) then
  5534. Result:=true;
  5535. end;
  5536. end;
  5537. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5538. var
  5539. TmpBool1,TmpBool2 : Boolean;
  5540. tmpref : treference;
  5541. hp1,hp2: tai;
  5542. mask: tcgint;
  5543. begin
  5544. Result:=false;
  5545. { All these optimisations work on "shl/sal const,%reg" }
  5546. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5547. Exit;
  5548. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5549. (taicpu(p).oper[0]^.val <= 3) then
  5550. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5551. begin
  5552. { should we check the next instruction? }
  5553. TmpBool1 := True;
  5554. { have we found an add/sub which could be
  5555. integrated in the lea? }
  5556. TmpBool2 := False;
  5557. reference_reset(tmpref,2,[]);
  5558. TmpRef.index := taicpu(p).oper[1]^.reg;
  5559. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5560. while TmpBool1 and
  5561. GetNextInstruction(p, hp1) and
  5562. (tai(hp1).typ = ait_instruction) and
  5563. ((((taicpu(hp1).opcode = A_ADD) or
  5564. (taicpu(hp1).opcode = A_SUB)) and
  5565. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5566. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5567. (((taicpu(hp1).opcode = A_INC) or
  5568. (taicpu(hp1).opcode = A_DEC)) and
  5569. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5570. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5571. ((taicpu(hp1).opcode = A_LEA) and
  5572. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5573. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5574. (not GetNextInstruction(hp1,hp2) or
  5575. not instrReadsFlags(hp2)) Do
  5576. begin
  5577. TmpBool1 := False;
  5578. if taicpu(hp1).opcode=A_LEA then
  5579. begin
  5580. if (TmpRef.base = NR_NO) and
  5581. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5582. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5583. { Segment register isn't a concern here }
  5584. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5585. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5586. begin
  5587. TmpBool1 := True;
  5588. TmpBool2 := True;
  5589. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5590. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5591. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5592. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5593. RemoveInstruction(hp1);
  5594. end
  5595. end
  5596. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5597. begin
  5598. TmpBool1 := True;
  5599. TmpBool2 := True;
  5600. case taicpu(hp1).opcode of
  5601. A_ADD:
  5602. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5603. A_SUB:
  5604. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5605. else
  5606. internalerror(2019050536);
  5607. end;
  5608. RemoveInstruction(hp1);
  5609. end
  5610. else
  5611. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5612. (((taicpu(hp1).opcode = A_ADD) and
  5613. (TmpRef.base = NR_NO)) or
  5614. (taicpu(hp1).opcode = A_INC) or
  5615. (taicpu(hp1).opcode = A_DEC)) then
  5616. begin
  5617. TmpBool1 := True;
  5618. TmpBool2 := True;
  5619. case taicpu(hp1).opcode of
  5620. A_ADD:
  5621. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5622. A_INC:
  5623. inc(TmpRef.offset);
  5624. A_DEC:
  5625. dec(TmpRef.offset);
  5626. else
  5627. internalerror(2019050535);
  5628. end;
  5629. RemoveInstruction(hp1);
  5630. end;
  5631. end;
  5632. if TmpBool2
  5633. {$ifndef x86_64}
  5634. or
  5635. ((current_settings.optimizecputype < cpu_Pentium2) and
  5636. (taicpu(p).oper[0]^.val <= 3) and
  5637. not(cs_opt_size in current_settings.optimizerswitches))
  5638. {$endif x86_64}
  5639. then
  5640. begin
  5641. if not(TmpBool2) and
  5642. (taicpu(p).oper[0]^.val=1) then
  5643. begin
  5644. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5645. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5646. end
  5647. else
  5648. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5649. taicpu(p).oper[1]^.reg);
  5650. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5651. InsertLLItem(p.previous, p.next, hp1);
  5652. p.free;
  5653. p := hp1;
  5654. end;
  5655. end
  5656. {$ifndef x86_64}
  5657. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5658. begin
  5659. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5660. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5661. (unlike shl, which is only Tairable in the U pipe) }
  5662. if taicpu(p).oper[0]^.val=1 then
  5663. begin
  5664. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5665. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5666. InsertLLItem(p.previous, p.next, hp1);
  5667. p.free;
  5668. p := hp1;
  5669. end
  5670. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5671. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5672. else if (taicpu(p).opsize = S_L) and
  5673. (taicpu(p).oper[0]^.val<= 3) then
  5674. begin
  5675. reference_reset(tmpref,2,[]);
  5676. TmpRef.index := taicpu(p).oper[1]^.reg;
  5677. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5678. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5679. InsertLLItem(p.previous, p.next, hp1);
  5680. p.free;
  5681. p := hp1;
  5682. end;
  5683. end
  5684. {$endif x86_64}
  5685. else if
  5686. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5687. (
  5688. (
  5689. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5690. SetAndTest(hp1, hp2)
  5691. {$ifdef x86_64}
  5692. ) or
  5693. (
  5694. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5695. GetNextInstruction(hp1, hp2) and
  5696. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5697. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5698. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5699. {$endif x86_64}
  5700. )
  5701. ) and
  5702. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5703. begin
  5704. { Change:
  5705. shl x, %reg1
  5706. mov -(1<<x), %reg2
  5707. and %reg2, %reg1
  5708. Or:
  5709. shl x, %reg1
  5710. and -(1<<x), %reg1
  5711. To just:
  5712. shl x, %reg1
  5713. Since the and operation only zeroes bits that are already zero from the shl operation
  5714. }
  5715. case taicpu(p).oper[0]^.val of
  5716. 8:
  5717. mask:=$FFFFFFFFFFFFFF00;
  5718. 16:
  5719. mask:=$FFFFFFFFFFFF0000;
  5720. 32:
  5721. mask:=$FFFFFFFF00000000;
  5722. 63:
  5723. { Constant pre-calculated to prevent overflow errors with Int64 }
  5724. mask:=$8000000000000000;
  5725. else
  5726. begin
  5727. if taicpu(p).oper[0]^.val >= 64 then
  5728. { Shouldn't happen realistically, since the register
  5729. is guaranteed to be set to zero at this point }
  5730. mask := 0
  5731. else
  5732. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5733. end;
  5734. end;
  5735. if taicpu(hp1).oper[0]^.val = mask then
  5736. begin
  5737. { Everything checks out, perform the optimisation, as long as
  5738. the FLAGS register isn't being used}
  5739. TransferUsedRegs(TmpUsedRegs);
  5740. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5741. {$ifdef x86_64}
  5742. if (hp1 <> hp2) then
  5743. begin
  5744. { "shl/mov/and" version }
  5745. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5746. { Don't do the optimisation if the FLAGS register is in use }
  5747. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5748. begin
  5749. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5750. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5751. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5752. begin
  5753. RemoveInstruction(hp1);
  5754. Result := True;
  5755. end;
  5756. { Only set Result to True if the 'mov' instruction was removed }
  5757. RemoveInstruction(hp2);
  5758. end;
  5759. end
  5760. else
  5761. {$endif x86_64}
  5762. begin
  5763. { "shl/and" version }
  5764. { Don't do the optimisation if the FLAGS register is in use }
  5765. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5766. begin
  5767. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5768. RemoveInstruction(hp1);
  5769. Result := True;
  5770. end;
  5771. end;
  5772. Exit;
  5773. end
  5774. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5775. begin
  5776. { Even if the mask doesn't allow for its removal, we might be
  5777. able to optimise the mask for the "shl/and" version, which
  5778. may permit other peephole optimisations }
  5779. {$ifdef DEBUG_AOPTCPU}
  5780. mask := taicpu(hp1).oper[0]^.val and mask;
  5781. if taicpu(hp1).oper[0]^.val <> mask then
  5782. begin
  5783. DebugMsg(
  5784. SPeepholeOptimization +
  5785. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5786. ' to $' + debug_tostr(mask) +
  5787. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5788. taicpu(hp1).oper[0]^.val := mask;
  5789. end;
  5790. {$else DEBUG_AOPTCPU}
  5791. { If debugging is off, just set the operand even if it's the same }
  5792. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5793. {$endif DEBUG_AOPTCPU}
  5794. end;
  5795. end;
  5796. {
  5797. change
  5798. shl/sal const,reg
  5799. <op> ...(...,reg,1),...
  5800. into
  5801. <op> ...(...,reg,1 shl const),...
  5802. if const in 1..3
  5803. }
  5804. if MatchOpType(taicpu(p), top_const, top_reg) and
  5805. (taicpu(p).oper[0]^.val in [1..3]) and
  5806. GetNextInstruction(p, hp1) and
  5807. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5808. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5809. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5810. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5811. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5812. begin
  5813. TransferUsedRegs(TmpUsedRegs);
  5814. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5815. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5816. begin
  5817. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5818. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5819. RemoveCurrentP(p);
  5820. Result:=true;
  5821. end;
  5822. end;
  5823. end;
  5824. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5825. var
  5826. CurrentRef: TReference;
  5827. FullReg: TRegister;
  5828. hp1, hp2: tai;
  5829. begin
  5830. Result := False;
  5831. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5832. Exit;
  5833. { We assume you've checked if the operand is actually a reference by
  5834. this point. If it isn't, you'll most likely get an access violation }
  5835. CurrentRef := first_mov.oper[1]^.ref^;
  5836. { Memory must be aligned }
  5837. if (CurrentRef.offset mod 4) <> 0 then
  5838. Exit;
  5839. Inc(CurrentRef.offset);
  5840. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5841. if MatchOperand(second_mov.oper[0]^, 0) and
  5842. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5843. GetNextInstruction(second_mov, hp1) and
  5844. (hp1.typ = ait_instruction) and
  5845. (taicpu(hp1).opcode = A_MOV) and
  5846. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5847. (taicpu(hp1).oper[0]^.val = 0) then
  5848. begin
  5849. Inc(CurrentRef.offset);
  5850. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5851. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5852. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5853. begin
  5854. case taicpu(hp1).opsize of
  5855. S_B:
  5856. if GetNextInstruction(hp1, hp2) and
  5857. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5858. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5859. (taicpu(hp2).oper[0]^.val = 0) then
  5860. begin
  5861. Inc(CurrentRef.offset);
  5862. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5863. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5864. (taicpu(hp2).opsize = S_B) then
  5865. begin
  5866. RemoveInstruction(hp1);
  5867. RemoveInstruction(hp2);
  5868. first_mov.opsize := S_L;
  5869. if first_mov.oper[0]^.typ = top_reg then
  5870. begin
  5871. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5872. { Reuse second_mov as a MOVZX instruction }
  5873. second_mov.opcode := A_MOVZX;
  5874. second_mov.opsize := S_BL;
  5875. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5876. second_mov.loadreg(1, FullReg);
  5877. first_mov.oper[0]^.reg := FullReg;
  5878. asml.Remove(second_mov);
  5879. asml.InsertBefore(second_mov, first_mov);
  5880. end
  5881. else
  5882. { It's a value }
  5883. begin
  5884. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5885. RemoveInstruction(second_mov);
  5886. end;
  5887. Result := True;
  5888. Exit;
  5889. end;
  5890. end;
  5891. S_W:
  5892. begin
  5893. RemoveInstruction(hp1);
  5894. first_mov.opsize := S_L;
  5895. if first_mov.oper[0]^.typ = top_reg then
  5896. begin
  5897. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5898. { Reuse second_mov as a MOVZX instruction }
  5899. second_mov.opcode := A_MOVZX;
  5900. second_mov.opsize := S_BL;
  5901. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5902. second_mov.loadreg(1, FullReg);
  5903. first_mov.oper[0]^.reg := FullReg;
  5904. asml.Remove(second_mov);
  5905. asml.InsertBefore(second_mov, first_mov);
  5906. end
  5907. else
  5908. { It's a value }
  5909. begin
  5910. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5911. RemoveInstruction(second_mov);
  5912. end;
  5913. Result := True;
  5914. Exit;
  5915. end;
  5916. else
  5917. ;
  5918. end;
  5919. end;
  5920. end;
  5921. end;
  5922. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5923. { returns true if a "continue" should be done after this optimization }
  5924. var
  5925. hp1, hp2: tai;
  5926. begin
  5927. Result := false;
  5928. if MatchOpType(taicpu(p),top_ref) and
  5929. GetNextInstruction(p, hp1) and
  5930. (hp1.typ = ait_instruction) and
  5931. (((taicpu(hp1).opcode = A_FLD) and
  5932. (taicpu(p).opcode = A_FSTP)) or
  5933. ((taicpu(p).opcode = A_FISTP) and
  5934. (taicpu(hp1).opcode = A_FILD))) and
  5935. MatchOpType(taicpu(hp1),top_ref) and
  5936. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5937. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5938. begin
  5939. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5940. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5941. GetNextInstruction(hp1, hp2) and
  5942. (hp2.typ = ait_instruction) and
  5943. IsExitCode(hp2) and
  5944. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5945. not(assigned(current_procinfo.procdef.funcretsym) and
  5946. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5947. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5948. begin
  5949. RemoveInstruction(hp1);
  5950. RemoveCurrentP(p, hp2);
  5951. RemoveLastDeallocForFuncRes(p);
  5952. Result := true;
  5953. end
  5954. else
  5955. { we can do this only in fast math mode as fstp is rounding ...
  5956. ... still disabled as it breaks the compiler and/or rtl }
  5957. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5958. { ... or if another fstp equal to the first one follows }
  5959. (GetNextInstruction(hp1,hp2) and
  5960. (hp2.typ = ait_instruction) and
  5961. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5962. (taicpu(p).opsize=taicpu(hp2).opsize))
  5963. ) and
  5964. { fst can't store an extended/comp value }
  5965. (taicpu(p).opsize <> S_FX) and
  5966. (taicpu(p).opsize <> S_IQ) then
  5967. begin
  5968. if (taicpu(p).opcode = A_FSTP) then
  5969. taicpu(p).opcode := A_FST
  5970. else
  5971. taicpu(p).opcode := A_FIST;
  5972. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5973. RemoveInstruction(hp1);
  5974. end;
  5975. end;
  5976. end;
  5977. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5978. var
  5979. hp1, hp2: tai;
  5980. begin
  5981. result:=false;
  5982. if MatchOpType(taicpu(p),top_reg) and
  5983. GetNextInstruction(p, hp1) and
  5984. (hp1.typ = Ait_Instruction) and
  5985. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5986. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5987. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5988. { change to
  5989. fld reg fxxx reg,st
  5990. fxxxp st, st1 (hp1)
  5991. Remark: non commutative operations must be reversed!
  5992. }
  5993. begin
  5994. case taicpu(hp1).opcode Of
  5995. A_FMULP,A_FADDP,
  5996. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5997. begin
  5998. case taicpu(hp1).opcode Of
  5999. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6000. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6001. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6002. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6003. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6004. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6005. else
  6006. internalerror(2019050534);
  6007. end;
  6008. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6009. taicpu(hp1).oper[1]^.reg := NR_ST;
  6010. RemoveCurrentP(p, hp1);
  6011. Result:=true;
  6012. exit;
  6013. end;
  6014. else
  6015. ;
  6016. end;
  6017. end
  6018. else
  6019. if MatchOpType(taicpu(p),top_ref) and
  6020. GetNextInstruction(p, hp2) and
  6021. (hp2.typ = Ait_Instruction) and
  6022. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6023. (taicpu(p).opsize in [S_FS, S_FL]) and
  6024. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6025. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6026. if GetLastInstruction(p, hp1) and
  6027. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6028. MatchOpType(taicpu(hp1),top_ref) and
  6029. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6030. if ((taicpu(hp2).opcode = A_FMULP) or
  6031. (taicpu(hp2).opcode = A_FADDP)) then
  6032. { change to
  6033. fld/fst mem1 (hp1) fld/fst mem1
  6034. fld mem1 (p) fadd/
  6035. faddp/ fmul st, st
  6036. fmulp st, st1 (hp2) }
  6037. begin
  6038. RemoveCurrentP(p, hp1);
  6039. if (taicpu(hp2).opcode = A_FADDP) then
  6040. taicpu(hp2).opcode := A_FADD
  6041. else
  6042. taicpu(hp2).opcode := A_FMUL;
  6043. taicpu(hp2).oper[1]^.reg := NR_ST;
  6044. end
  6045. else
  6046. { change to
  6047. fld/fst mem1 (hp1) fld/fst mem1
  6048. fld mem1 (p) fld st}
  6049. begin
  6050. taicpu(p).changeopsize(S_FL);
  6051. taicpu(p).loadreg(0,NR_ST);
  6052. end
  6053. else
  6054. begin
  6055. case taicpu(hp2).opcode Of
  6056. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6057. { change to
  6058. fld/fst mem1 (hp1) fld/fst mem1
  6059. fld mem2 (p) fxxx mem2
  6060. fxxxp st, st1 (hp2) }
  6061. begin
  6062. case taicpu(hp2).opcode Of
  6063. A_FADDP: taicpu(p).opcode := A_FADD;
  6064. A_FMULP: taicpu(p).opcode := A_FMUL;
  6065. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6066. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6067. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6068. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6069. else
  6070. internalerror(2019050533);
  6071. end;
  6072. RemoveInstruction(hp2);
  6073. end
  6074. else
  6075. ;
  6076. end
  6077. end
  6078. end;
  6079. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6080. begin
  6081. Result := condition_in(cond1, cond2) or
  6082. { Not strictly subsets due to the actual flags checked, but because we're
  6083. comparing integers, E is a subset of AE and GE and their aliases }
  6084. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6085. end;
  6086. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6087. var
  6088. v: TCGInt;
  6089. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6090. FirstMatch: Boolean;
  6091. NewReg: TRegister;
  6092. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6093. begin
  6094. Result:=false;
  6095. { All these optimisations need a next instruction }
  6096. if not GetNextInstruction(p, hp1) then
  6097. Exit;
  6098. { Search for:
  6099. cmp ###,###
  6100. j(c1) @lbl1
  6101. ...
  6102. @lbl:
  6103. cmp ###.### (same comparison as above)
  6104. j(c2) @lbl2
  6105. If c1 is a subset of c2, change to:
  6106. cmp ###,###
  6107. j(c2) @lbl2
  6108. (@lbl1 may become a dead label as a result)
  6109. }
  6110. { Also handle cases where there are multiple jumps in a row }
  6111. p_jump := hp1;
  6112. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6113. begin
  6114. if IsJumpToLabel(taicpu(p_jump)) then
  6115. begin
  6116. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6117. p_label := nil;
  6118. if Assigned(JumpLabel) then
  6119. p_label := getlabelwithsym(JumpLabel);
  6120. if Assigned(p_label) and
  6121. GetNextInstruction(p_label, p_dist) and
  6122. MatchInstruction(p_dist, A_CMP, []) and
  6123. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6124. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6125. GetNextInstruction(p_dist, hp1_dist) and
  6126. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6127. begin
  6128. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6129. if JumpLabel = JumpLabel_dist then
  6130. { This is an infinite loop }
  6131. Exit;
  6132. { Best optimisation when the first condition is a subset (or equal) of the second }
  6133. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6134. begin
  6135. { Any registers used here will already be allocated }
  6136. if Assigned(JumpLabel_dist) then
  6137. JumpLabel_dist.IncRefs;
  6138. if Assigned(JumpLabel) then
  6139. JumpLabel.DecRefs;
  6140. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6141. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  6142. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  6143. Result := True;
  6144. { Don't exit yet. Since p and p_jump haven't actually been
  6145. removed, we can check for more on this iteration }
  6146. end
  6147. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6148. GetNextInstruction(hp1_dist, hp1_label) and
  6149. SkipAligns(hp1_label, hp1_label) and
  6150. (hp1_label.typ = ait_label) then
  6151. begin
  6152. JumpLabel_far := tai_label(hp1_label).labsym;
  6153. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6154. { This is an infinite loop }
  6155. Exit;
  6156. if Assigned(JumpLabel_far) then
  6157. begin
  6158. { In this situation, if the first jump branches, the second one will never,
  6159. branch so change the destination label to after the second jump }
  6160. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6161. if Assigned(JumpLabel) then
  6162. JumpLabel.DecRefs;
  6163. JumpLabel_far.IncRefs;
  6164. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6165. Result := True;
  6166. { Don't exit yet. Since p and p_jump haven't actually been
  6167. removed, we can check for more on this iteration }
  6168. Continue;
  6169. end;
  6170. end;
  6171. end;
  6172. end;
  6173. { Search for:
  6174. cmp ###,###
  6175. j(c1) @lbl1
  6176. cmp ###,### (same as first)
  6177. Remove second cmp
  6178. }
  6179. if GetNextInstruction(p_jump, hp2) and
  6180. (
  6181. (
  6182. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6183. (
  6184. (
  6185. MatchOpType(taicpu(p), top_const, top_reg) and
  6186. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6187. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6188. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6189. ) or (
  6190. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6191. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6192. )
  6193. )
  6194. ) or (
  6195. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6196. MatchOperand(taicpu(p).oper[0]^, 0) and
  6197. (taicpu(p).oper[1]^.typ = top_reg) and
  6198. MatchInstruction(hp2, A_TEST, []) and
  6199. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6200. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6201. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6202. )
  6203. ) then
  6204. begin
  6205. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6206. RemoveInstruction(hp2);
  6207. Result := True;
  6208. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6209. end;
  6210. GetNextInstruction(p_jump, p_jump);
  6211. end;
  6212. {
  6213. Try to optimise the following:
  6214. cmp $x,### ($x and $y can be registers or constants)
  6215. je @lbl1 (only reference)
  6216. cmp $y,### (### are identical)
  6217. @Lbl:
  6218. sete %reg1
  6219. Change to:
  6220. cmp $x,###
  6221. sete %reg2 (allocate new %reg2)
  6222. cmp $y,###
  6223. sete %reg1
  6224. orb %reg2,%reg1
  6225. (dealloc %reg2)
  6226. This adds an instruction (so don't perform under -Os), but it removes
  6227. a conditional branch.
  6228. }
  6229. if not (cs_opt_size in current_settings.optimizerswitches) and
  6230. (
  6231. (hp1 = p_jump) or
  6232. GetNextInstruction(p, hp1)
  6233. ) and
  6234. MatchInstruction(hp1, A_Jcc, []) and
  6235. IsJumpToLabel(taicpu(hp1)) and
  6236. (taicpu(hp1).condition in [C_E, C_Z]) and
  6237. GetNextInstruction(hp1, hp2) and
  6238. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6239. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6240. { The first operand of CMP instructions can only be a register or
  6241. immediate anyway, so no need to check }
  6242. GetNextInstruction(hp2, p_label) and
  6243. (
  6244. (p_label.typ = ait_label) or
  6245. (
  6246. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6247. to potentially cut down on the iterations of Pass 1 }
  6248. MatchInstruction(p_label, A_Jcc, []) and
  6249. IsJumpToLabel(taicpu(p_label)) and
  6250. { Use p_dist to hold the jump briefly }
  6251. SetAndTest(p_label, p_dist) and
  6252. GetNextInstruction(p_dist, p_label) and
  6253. (p_label.typ = ait_label) and
  6254. (tai_label(p_label).labsym.getrefs >= 2) and
  6255. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6256. { We might as well collapse the jump now }
  6257. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6258. )
  6259. ) and
  6260. (tai_label(p_label).labsym.getrefs = 1) and
  6261. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6262. GetNextInstruction(p_label, p_dist) and
  6263. MatchInstruction(p_dist, A_SETcc, []) and
  6264. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6265. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6266. { Get the instruction after the SETcc instruction so we can
  6267. allocate a new register over the entire range }
  6268. GetNextInstruction(p_dist, hp1_dist) then
  6269. begin
  6270. TransferUsedRegs(TmpUsedRegs);
  6271. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6272. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6273. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6274. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6275. { Register can appear in p if it's not used afterwards, so only
  6276. allocate between hp1 and hp1_dist }
  6277. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6278. if (NewReg <> NR_NO) and
  6279. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6280. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6281. begin
  6282. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6283. { Change the jump instruction into a SETcc instruction }
  6284. taicpu(hp1).opcode := A_SETcc;
  6285. taicpu(hp1).opsize := S_B;
  6286. taicpu(hp1).loadreg(0, NewReg);
  6287. { This is now a dead label }
  6288. tai_label(p_label).labsym.decrefs;
  6289. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6290. { Try to add the instruction right after the flags get deallocated, since
  6291. the flags may become allocated again before the next instruction
  6292. (reuse p_dist, not hp1, since that needs to remain as the
  6293. instruction immediately after p) }
  6294. if SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), p_dist) then
  6295. AsmL.InsertAfter(hp2, p_dist)
  6296. else
  6297. AsmL.InsertBefore(hp2, hp1_dist);
  6298. Result := True;
  6299. { Don't exit yet, as p wasn't changed and hp1, while
  6300. modified, is still intact and might be optimised by the
  6301. SETcc optimisation below }
  6302. end;
  6303. end;
  6304. if taicpu(p).oper[0]^.typ = top_const then
  6305. begin
  6306. if (taicpu(p).oper[0]^.val = 0) and
  6307. (taicpu(p).oper[1]^.typ = top_reg) and
  6308. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6309. begin
  6310. hp2 := p;
  6311. FirstMatch := True;
  6312. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6313. anything meaningful once it's converted to "test %reg,%reg";
  6314. additionally, some jumps will always (or never) branch, so
  6315. evaluate every jump immediately following the
  6316. comparison, optimising the conditions if possible.
  6317. Similarly with SETcc... those that are always set to 0 or 1
  6318. are changed to MOV instructions }
  6319. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6320. (
  6321. GetNextInstruction(hp2, hp1) and
  6322. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6323. ) do
  6324. begin
  6325. FirstMatch := False;
  6326. case taicpu(hp1).condition of
  6327. C_B, C_C, C_NAE, C_O:
  6328. { For B/NAE:
  6329. Will never branch since an unsigned integer can never be below zero
  6330. For C/O:
  6331. Result cannot overflow because 0 is being subtracted
  6332. }
  6333. begin
  6334. if taicpu(hp1).opcode = A_Jcc then
  6335. begin
  6336. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6337. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6338. RemoveInstruction(hp1);
  6339. { Since hp1 was deleted, hp2 must not be updated }
  6340. Continue;
  6341. end
  6342. else
  6343. begin
  6344. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6345. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6346. taicpu(hp1).opcode := A_MOV;
  6347. taicpu(hp1).ops := 2;
  6348. taicpu(hp1).condition := C_None;
  6349. taicpu(hp1).opsize := S_B;
  6350. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6351. taicpu(hp1).loadconst(0, 0);
  6352. end;
  6353. end;
  6354. C_BE, C_NA:
  6355. begin
  6356. { Will only branch if equal to zero }
  6357. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6358. taicpu(hp1).condition := C_E;
  6359. end;
  6360. C_A, C_NBE:
  6361. begin
  6362. { Will only branch if not equal to zero }
  6363. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6364. taicpu(hp1).condition := C_NE;
  6365. end;
  6366. C_AE, C_NB, C_NC, C_NO:
  6367. begin
  6368. { Will always branch }
  6369. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6370. if taicpu(hp1).opcode = A_Jcc then
  6371. begin
  6372. MakeUnconditional(taicpu(hp1));
  6373. { Any jumps/set that follow will now be dead code }
  6374. RemoveDeadCodeAfterJump(taicpu(hp1));
  6375. Break;
  6376. end
  6377. else
  6378. begin
  6379. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6380. taicpu(hp1).opcode := A_MOV;
  6381. taicpu(hp1).ops := 2;
  6382. taicpu(hp1).condition := C_None;
  6383. taicpu(hp1).opsize := S_B;
  6384. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6385. taicpu(hp1).loadconst(0, 1);
  6386. end;
  6387. end;
  6388. C_None:
  6389. InternalError(2020012201);
  6390. C_P, C_PE, C_NP, C_PO:
  6391. { We can't handle parity checks and they should never be generated
  6392. after a general-purpose CMP (it's used in some floating-point
  6393. comparisons that don't use CMP) }
  6394. InternalError(2020012202);
  6395. else
  6396. { Zero/Equality, Sign, their complements and all of the
  6397. signed comparisons do not need to be converted };
  6398. end;
  6399. hp2 := hp1;
  6400. end;
  6401. { Convert the instruction to a TEST }
  6402. taicpu(p).opcode := A_TEST;
  6403. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6404. Result := True;
  6405. Exit;
  6406. end
  6407. else if (taicpu(p).oper[0]^.val = 1) and
  6408. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6409. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6410. begin
  6411. { Convert; To:
  6412. cmp $1,r/m cmp $0,r/m
  6413. jl @lbl jle @lbl
  6414. }
  6415. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6416. taicpu(p).oper[0]^.val := 0;
  6417. taicpu(hp1).condition := C_LE;
  6418. { If the instruction is now "cmp $0,%reg", convert it to a
  6419. TEST (and effectively do the work of the "cmp $0,%reg" in
  6420. the block above)
  6421. If it's a reference, we can get away with not setting
  6422. Result to True because he haven't evaluated the jump
  6423. in this pass yet.
  6424. }
  6425. if (taicpu(p).oper[1]^.typ = top_reg) then
  6426. begin
  6427. taicpu(p).opcode := A_TEST;
  6428. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6429. Result := True;
  6430. end;
  6431. Exit;
  6432. end
  6433. else if (taicpu(p).oper[1]^.typ = top_reg)
  6434. {$ifdef x86_64}
  6435. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6436. {$endif x86_64}
  6437. then
  6438. begin
  6439. { cmp register,$8000 neg register
  6440. je target --> jo target
  6441. .... only if register is deallocated before jump.}
  6442. case Taicpu(p).opsize of
  6443. S_B: v:=$80;
  6444. S_W: v:=$8000;
  6445. S_L: v:=qword($80000000);
  6446. else
  6447. internalerror(2013112905);
  6448. end;
  6449. if (taicpu(p).oper[0]^.val=v) and
  6450. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6451. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6452. begin
  6453. TransferUsedRegs(TmpUsedRegs);
  6454. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6455. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6456. begin
  6457. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6458. Taicpu(p).opcode:=A_NEG;
  6459. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6460. Taicpu(p).clearop(1);
  6461. Taicpu(p).ops:=1;
  6462. if Taicpu(hp1).condition=C_E then
  6463. Taicpu(hp1).condition:=C_O
  6464. else
  6465. Taicpu(hp1).condition:=C_NO;
  6466. Result:=true;
  6467. exit;
  6468. end;
  6469. end;
  6470. end;
  6471. end;
  6472. if TrySwapMovCmp(p, hp1) then
  6473. begin
  6474. Result := True;
  6475. Exit;
  6476. end;
  6477. end;
  6478. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6479. var
  6480. hp1: tai;
  6481. begin
  6482. {
  6483. remove the second (v)pxor from
  6484. pxor reg,reg
  6485. ...
  6486. pxor reg,reg
  6487. }
  6488. Result:=false;
  6489. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6490. MatchOpType(taicpu(p),top_reg,top_reg) and
  6491. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6492. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6493. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6494. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6495. begin
  6496. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6497. RemoveInstruction(hp1);
  6498. Result:=true;
  6499. Exit;
  6500. end
  6501. {
  6502. replace
  6503. pxor reg1,reg1
  6504. movapd/s reg1,reg2
  6505. dealloc reg1
  6506. by
  6507. pxor reg2,reg2
  6508. }
  6509. else if GetNextInstruction(p,hp1) and
  6510. { we mix single and double opperations here because we assume that the compiler
  6511. generates vmovapd only after double operations and vmovaps only after single operations }
  6512. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6513. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6514. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6515. (taicpu(p).oper[0]^.typ=top_reg) then
  6516. begin
  6517. TransferUsedRegs(TmpUsedRegs);
  6518. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6519. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6520. begin
  6521. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6522. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6523. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6524. RemoveInstruction(hp1);
  6525. result:=true;
  6526. end;
  6527. end;
  6528. end;
  6529. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6530. var
  6531. hp1: tai;
  6532. begin
  6533. {
  6534. remove the second (v)pxor from
  6535. (v)pxor reg,reg
  6536. ...
  6537. (v)pxor reg,reg
  6538. }
  6539. Result:=false;
  6540. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6541. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6542. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6543. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6544. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6545. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6546. begin
  6547. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6548. RemoveInstruction(hp1);
  6549. Result:=true;
  6550. Exit;
  6551. end
  6552. else
  6553. Result:=OptPass1VOP(p);
  6554. end;
  6555. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6556. var
  6557. hp1 : tai;
  6558. begin
  6559. result:=false;
  6560. { replace
  6561. IMul const,%mreg1,%mreg2
  6562. Mov %reg2,%mreg3
  6563. dealloc %mreg3
  6564. by
  6565. Imul const,%mreg1,%mreg23
  6566. }
  6567. if (taicpu(p).ops=3) and
  6568. GetNextInstruction(p,hp1) and
  6569. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6570. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6571. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6572. begin
  6573. TransferUsedRegs(TmpUsedRegs);
  6574. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6575. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6576. begin
  6577. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6578. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6579. RemoveInstruction(hp1);
  6580. result:=true;
  6581. end;
  6582. end;
  6583. end;
  6584. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6585. var
  6586. hp1 : tai;
  6587. begin
  6588. result:=false;
  6589. { replace
  6590. IMul %reg0,%reg1,%reg2
  6591. Mov %reg2,%reg3
  6592. dealloc %reg2
  6593. by
  6594. Imul %reg0,%reg1,%reg3
  6595. }
  6596. if GetNextInstruction(p,hp1) and
  6597. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6598. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6599. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6600. begin
  6601. TransferUsedRegs(TmpUsedRegs);
  6602. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6603. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6604. begin
  6605. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6606. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6607. RemoveInstruction(hp1);
  6608. result:=true;
  6609. end;
  6610. end;
  6611. end;
  6612. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6613. var
  6614. hp1: tai;
  6615. begin
  6616. Result:=false;
  6617. { get rid of
  6618. (v)cvtss2sd reg0,<reg1,>reg2
  6619. (v)cvtss2sd reg2,<reg2,>reg0
  6620. }
  6621. if GetNextInstruction(p,hp1) and
  6622. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6623. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6624. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6625. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6626. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6627. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6628. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6629. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6630. )
  6631. ) then
  6632. begin
  6633. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6634. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6635. begin
  6636. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6637. RemoveCurrentP(p);
  6638. RemoveInstruction(hp1);
  6639. end
  6640. else
  6641. begin
  6642. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6643. if taicpu(hp1).opcode=A_CVTSD2SS then
  6644. begin
  6645. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6646. taicpu(p).opcode:=A_MOVAPS;
  6647. end
  6648. else
  6649. begin
  6650. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6651. taicpu(p).opcode:=A_VMOVAPS;
  6652. end;
  6653. taicpu(p).ops:=2;
  6654. RemoveInstruction(hp1);
  6655. end;
  6656. Result:=true;
  6657. Exit;
  6658. end;
  6659. end;
  6660. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6661. var
  6662. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6663. ThisReg: TRegister;
  6664. begin
  6665. Result := False;
  6666. if not GetNextInstruction(p,hp1) then
  6667. Exit;
  6668. {
  6669. convert
  6670. j<c> .L1
  6671. mov 1,reg
  6672. jmp .L2
  6673. .L1
  6674. mov 0,reg
  6675. .L2
  6676. into
  6677. mov 0,reg
  6678. set<not(c)> reg
  6679. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6680. would destroy the flag contents
  6681. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6682. executed at the same time as a previous comparison.
  6683. set<not(c)> reg
  6684. movzx reg, reg
  6685. }
  6686. if MatchInstruction(hp1,A_MOV,[]) and
  6687. (taicpu(hp1).oper[0]^.typ = top_const) and
  6688. (
  6689. (
  6690. (taicpu(hp1).oper[1]^.typ = top_reg)
  6691. {$ifdef i386}
  6692. { Under i386, ESI, EDI, EBP and ESP
  6693. don't have an 8-bit representation }
  6694. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6695. {$endif i386}
  6696. ) or (
  6697. {$ifdef i386}
  6698. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6699. {$endif i386}
  6700. (taicpu(hp1).opsize = S_B)
  6701. )
  6702. ) and
  6703. GetNextInstruction(hp1,hp2) and
  6704. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6705. GetNextInstruction(hp2,hp3) and
  6706. SkipAligns(hp3, hp3) and
  6707. (hp3.typ=ait_label) and
  6708. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6709. GetNextInstruction(hp3,hp4) and
  6710. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6711. (taicpu(hp4).oper[0]^.typ = top_const) and
  6712. (
  6713. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6714. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6715. ) and
  6716. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6717. GetNextInstruction(hp4,hp5) and
  6718. SkipAligns(hp5, hp5) and
  6719. (hp5.typ=ait_label) and
  6720. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6721. begin
  6722. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6723. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6724. tai_label(hp3).labsym.DecRefs;
  6725. { If this isn't the only reference to the middle label, we can
  6726. still make a saving - only that the first jump and everything
  6727. that follows will remain. }
  6728. if (tai_label(hp3).labsym.getrefs = 0) then
  6729. begin
  6730. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6731. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6732. else
  6733. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6734. { remove jump, first label and second MOV (also catching any aligns) }
  6735. repeat
  6736. if not GetNextInstruction(hp2, hp3) then
  6737. InternalError(2021040810);
  6738. RemoveInstruction(hp2);
  6739. hp2 := hp3;
  6740. until hp2 = hp5;
  6741. { Don't decrement reference count before the removal loop
  6742. above, otherwise GetNextInstruction won't stop on the
  6743. the label }
  6744. tai_label(hp5).labsym.DecRefs;
  6745. end
  6746. else
  6747. begin
  6748. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6749. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6750. else
  6751. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6752. end;
  6753. taicpu(p).opcode:=A_SETcc;
  6754. taicpu(p).opsize:=S_B;
  6755. taicpu(p).is_jmp:=False;
  6756. if taicpu(hp1).opsize=S_B then
  6757. begin
  6758. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6759. if taicpu(hp1).oper[1]^.typ = top_reg then
  6760. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6761. RemoveInstruction(hp1);
  6762. end
  6763. else
  6764. begin
  6765. { Will be a register because the size can't be S_B otherwise }
  6766. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6767. taicpu(p).loadreg(0, ThisReg);
  6768. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6769. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6770. begin
  6771. case taicpu(hp1).opsize of
  6772. S_W:
  6773. taicpu(hp1).opsize := S_BW;
  6774. S_L:
  6775. taicpu(hp1).opsize := S_BL;
  6776. {$ifdef x86_64}
  6777. S_Q:
  6778. begin
  6779. taicpu(hp1).opsize := S_BL;
  6780. { Change the destination register to 32-bit }
  6781. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6782. end;
  6783. {$endif x86_64}
  6784. else
  6785. InternalError(2021040820);
  6786. end;
  6787. taicpu(hp1).opcode := A_MOVZX;
  6788. taicpu(hp1).loadreg(0, ThisReg);
  6789. end
  6790. else
  6791. begin
  6792. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6793. { hp1 is already a MOV instruction with the correct register }
  6794. taicpu(hp1).loadconst(0, 0);
  6795. { Inserting it right before p will guarantee that the flags are also tracked }
  6796. asml.Remove(hp1);
  6797. asml.InsertBefore(hp1, p);
  6798. end;
  6799. end;
  6800. Result:=true;
  6801. exit;
  6802. end
  6803. else if (hp1.typ = ait_label) then
  6804. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6805. end;
  6806. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6807. var
  6808. hp1, hp2, hp3: tai;
  6809. SourceRef, TargetRef: TReference;
  6810. CurrentReg: TRegister;
  6811. begin
  6812. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6813. if not UseAVX then
  6814. InternalError(2021100501);
  6815. Result := False;
  6816. { Look for the following to simplify:
  6817. vmovdqa/u x(mem1), %xmmreg
  6818. vmovdqa/u %xmmreg, y(mem2)
  6819. vmovdqa/u x+16(mem1), %xmmreg
  6820. vmovdqa/u %xmmreg, y+16(mem2)
  6821. Change to:
  6822. vmovdqa/u x(mem1), %ymmreg
  6823. vmovdqa/u %ymmreg, y(mem2)
  6824. vpxor %ymmreg, %ymmreg, %ymmreg
  6825. ( The VPXOR instruction is to zero the upper half, thus removing the
  6826. need to call the potentially expensive VZEROUPPER instruction. Other
  6827. peephole optimisations can remove VPXOR if it's unnecessary )
  6828. }
  6829. TransferUsedRegs(TmpUsedRegs);
  6830. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6831. { NOTE: In the optimisations below, if the references dictate that an
  6832. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6833. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6834. if (taicpu(p).opsize = S_XMM) and
  6835. MatchOpType(taicpu(p), top_ref, top_reg) and
  6836. GetNextInstruction(p, hp1) and
  6837. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6838. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6839. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6840. begin
  6841. SourceRef := taicpu(p).oper[0]^.ref^;
  6842. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6843. if GetNextInstruction(hp1, hp2) and
  6844. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6845. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6846. begin
  6847. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6848. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6849. Inc(SourceRef.offset, 16);
  6850. { Reuse the register in the first block move }
  6851. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6852. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6853. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6854. begin
  6855. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6856. Inc(TargetRef.offset, 16);
  6857. if GetNextInstruction(hp2, hp3) and
  6858. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6859. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6860. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6861. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6862. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6863. begin
  6864. { Update the register tracking to the new size }
  6865. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6866. { Remember that the offsets are 16 ahead }
  6867. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6868. if not (
  6869. ((SourceRef.offset mod 32) = 16) and
  6870. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6871. ) then
  6872. taicpu(p).opcode := A_VMOVDQU;
  6873. taicpu(p).opsize := S_YMM;
  6874. taicpu(p).oper[1]^.reg := CurrentReg;
  6875. if not (
  6876. ((TargetRef.offset mod 32) = 16) and
  6877. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6878. ) then
  6879. taicpu(hp1).opcode := A_VMOVDQU;
  6880. taicpu(hp1).opsize := S_YMM;
  6881. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6882. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6883. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6884. if (pi_uses_ymm in current_procinfo.flags) then
  6885. RemoveInstruction(hp2)
  6886. else
  6887. begin
  6888. taicpu(hp2).opcode := A_VPXOR;
  6889. taicpu(hp2).opsize := S_YMM;
  6890. taicpu(hp2).loadreg(0, CurrentReg);
  6891. taicpu(hp2).loadreg(1, CurrentReg);
  6892. taicpu(hp2).loadreg(2, CurrentReg);
  6893. taicpu(hp2).ops := 3;
  6894. end;
  6895. RemoveInstruction(hp3);
  6896. Result := True;
  6897. Exit;
  6898. end;
  6899. end
  6900. else
  6901. begin
  6902. { See if the next references are 16 less rather than 16 greater }
  6903. Dec(SourceRef.offset, 32); { -16 the other way }
  6904. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6905. begin
  6906. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6907. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6908. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6909. GetNextInstruction(hp2, hp3) and
  6910. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6911. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6912. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6913. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6914. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6915. begin
  6916. { Update the register tracking to the new size }
  6917. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6918. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6919. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6920. if not(
  6921. ((SourceRef.offset mod 32) = 0) and
  6922. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6923. ) then
  6924. taicpu(hp2).opcode := A_VMOVDQU;
  6925. taicpu(hp2).opsize := S_YMM;
  6926. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6927. if not (
  6928. ((TargetRef.offset mod 32) = 0) and
  6929. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6930. ) then
  6931. taicpu(hp3).opcode := A_VMOVDQU;
  6932. taicpu(hp3).opsize := S_YMM;
  6933. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6934. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6935. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6936. if (pi_uses_ymm in current_procinfo.flags) then
  6937. RemoveInstruction(hp1)
  6938. else
  6939. begin
  6940. taicpu(hp1).opcode := A_VPXOR;
  6941. taicpu(hp1).opsize := S_YMM;
  6942. taicpu(hp1).loadreg(0, CurrentReg);
  6943. taicpu(hp1).loadreg(1, CurrentReg);
  6944. taicpu(hp1).loadreg(2, CurrentReg);
  6945. taicpu(hp1).ops := 3;
  6946. Asml.Remove(hp1);
  6947. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6948. end;
  6949. RemoveCurrentP(p, hp2);
  6950. Result := True;
  6951. Exit;
  6952. end;
  6953. end;
  6954. end;
  6955. end;
  6956. end;
  6957. end;
  6958. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6959. var
  6960. hp2, hp3, first_assignment: tai;
  6961. IncCount, OperIdx: Integer;
  6962. OrigLabel: TAsmLabel;
  6963. begin
  6964. Count := 0;
  6965. Result := False;
  6966. first_assignment := nil;
  6967. if (LoopCount >= 20) then
  6968. begin
  6969. { Guard against infinite loops }
  6970. Exit;
  6971. end;
  6972. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6973. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6974. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6975. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6976. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6977. Exit;
  6978. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6979. {
  6980. change
  6981. jmp .L1
  6982. ...
  6983. .L1:
  6984. mov ##, ## ( multiple movs possible )
  6985. jmp/ret
  6986. into
  6987. mov ##, ##
  6988. jmp/ret
  6989. }
  6990. if not Assigned(hp1) then
  6991. begin
  6992. hp1 := GetLabelWithSym(OrigLabel);
  6993. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6994. Exit;
  6995. end;
  6996. hp2 := hp1;
  6997. while Assigned(hp2) do
  6998. begin
  6999. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7000. SkipLabels(hp2,hp2);
  7001. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7002. Break;
  7003. case taicpu(hp2).opcode of
  7004. A_MOVSS:
  7005. begin
  7006. if taicpu(hp2).ops = 0 then
  7007. { Wrong MOVSS }
  7008. Break;
  7009. Inc(Count);
  7010. if Count >= 5 then
  7011. { Too many to be worthwhile }
  7012. Break;
  7013. GetNextInstruction(hp2, hp2);
  7014. Continue;
  7015. end;
  7016. A_MOV,
  7017. A_MOVD,
  7018. A_MOVQ,
  7019. A_MOVSX,
  7020. {$ifdef x86_64}
  7021. A_MOVSXD,
  7022. {$endif x86_64}
  7023. A_MOVZX,
  7024. A_MOVAPS,
  7025. A_MOVUPS,
  7026. A_MOVSD,
  7027. A_MOVAPD,
  7028. A_MOVUPD,
  7029. A_MOVDQA,
  7030. A_MOVDQU,
  7031. A_VMOVSS,
  7032. A_VMOVAPS,
  7033. A_VMOVUPS,
  7034. A_VMOVSD,
  7035. A_VMOVAPD,
  7036. A_VMOVUPD,
  7037. A_VMOVDQA,
  7038. A_VMOVDQU:
  7039. begin
  7040. Inc(Count);
  7041. if Count >= 5 then
  7042. { Too many to be worthwhile }
  7043. Break;
  7044. GetNextInstruction(hp2, hp2);
  7045. Continue;
  7046. end;
  7047. A_JMP:
  7048. begin
  7049. { Guard against infinite loops }
  7050. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7051. Exit;
  7052. { Analyse this jump first in case it also duplicates assignments }
  7053. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7054. begin
  7055. { Something did change! }
  7056. Result := True;
  7057. Inc(Count, IncCount);
  7058. if Count >= 5 then
  7059. begin
  7060. { Too many to be worthwhile }
  7061. Exit;
  7062. end;
  7063. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7064. Break;
  7065. end;
  7066. Result := True;
  7067. Break;
  7068. end;
  7069. A_RET:
  7070. begin
  7071. Result := True;
  7072. Break;
  7073. end;
  7074. else
  7075. Break;
  7076. end;
  7077. end;
  7078. if Result then
  7079. begin
  7080. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7081. if Count = 0 then
  7082. begin
  7083. Result := False;
  7084. Exit;
  7085. end;
  7086. hp3 := p;
  7087. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7088. while True do
  7089. begin
  7090. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7091. SkipLabels(hp1,hp1);
  7092. if (hp1.typ <> ait_instruction) then
  7093. InternalError(2021040720);
  7094. case taicpu(hp1).opcode of
  7095. A_JMP:
  7096. begin
  7097. { Change the original jump to the new destination }
  7098. OrigLabel.decrefs;
  7099. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7100. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7101. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7102. if not Assigned(first_assignment) then
  7103. InternalError(2021040810)
  7104. else
  7105. p := first_assignment;
  7106. Exit;
  7107. end;
  7108. A_RET:
  7109. begin
  7110. { Now change the jump into a RET instruction }
  7111. ConvertJumpToRET(p, hp1);
  7112. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7113. if not Assigned(first_assignment) then
  7114. InternalError(2021040811)
  7115. else
  7116. p := first_assignment;
  7117. Exit;
  7118. end;
  7119. else
  7120. begin
  7121. { Duplicate the MOV instruction }
  7122. hp3:=tai(hp1.getcopy);
  7123. if first_assignment = nil then
  7124. first_assignment := hp3;
  7125. asml.InsertBefore(hp3, p);
  7126. { Make sure the compiler knows about any final registers written here }
  7127. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7128. with taicpu(hp3).oper[OperIdx]^ do
  7129. begin
  7130. case typ of
  7131. top_ref:
  7132. begin
  7133. if (ref^.base <> NR_NO) and
  7134. (getsupreg(ref^.base) <> RS_ESP) and
  7135. (getsupreg(ref^.base) <> RS_EBP)
  7136. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7137. then
  7138. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7139. if (ref^.index <> NR_NO) and
  7140. (getsupreg(ref^.index) <> RS_ESP) and
  7141. (getsupreg(ref^.index) <> RS_EBP)
  7142. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7143. (ref^.index <> ref^.base) then
  7144. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7145. end;
  7146. top_reg:
  7147. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7148. else
  7149. ;
  7150. end;
  7151. end;
  7152. end;
  7153. end;
  7154. if not GetNextInstruction(hp1, hp1) then
  7155. { Should have dropped out earlier }
  7156. InternalError(2021040710);
  7157. end;
  7158. end;
  7159. end;
  7160. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7161. var
  7162. hp2: tai;
  7163. X: Integer;
  7164. const
  7165. WriteOp: array[0..3] of set of TInsChange = (
  7166. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7167. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7168. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7169. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7170. RegWriteFlags: array[0..7] of set of TInsChange = (
  7171. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7172. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7173. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7174. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7175. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7176. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7177. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7178. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7179. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7180. begin
  7181. { If we have something like:
  7182. cmp ###,%reg1
  7183. mov 0,%reg2
  7184. And no modified registers are shared, move the instruction to before
  7185. the comparison as this means it can be optimised without worrying
  7186. about the FLAGS register. (CMP/MOV is generated by
  7187. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7188. As long as the second instruction doesn't use the flags or one of the
  7189. registers used by CMP or TEST (also check any references that use the
  7190. registers), then it can be moved prior to the comparison.
  7191. }
  7192. Result := False;
  7193. if (hp1.typ <> ait_instruction) or
  7194. taicpu(hp1).is_jmp or
  7195. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7196. Exit;
  7197. { NOP is a pipeline fence, likely marking the beginning of the function
  7198. epilogue, so drop out. Similarly, drop out if POP or RET are
  7199. encountered }
  7200. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7201. Exit;
  7202. if (taicpu(hp1).opcode = A_MOVSS) and
  7203. (taicpu(hp1).ops = 0) then
  7204. { Wrong MOVSS }
  7205. Exit;
  7206. { Check for writes to specific registers first }
  7207. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7208. for X := 0 to 7 do
  7209. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7210. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7211. Exit;
  7212. for X := 0 to taicpu(hp1).ops - 1 do
  7213. begin
  7214. { Check to see if this operand writes to something }
  7215. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7216. { And matches something in the CMP/TEST instruction }
  7217. (
  7218. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7219. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7220. (
  7221. { If it's a register, make sure the register written to doesn't
  7222. appear in the cmp instruction as part of a reference }
  7223. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7224. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7225. )
  7226. ) then
  7227. Exit;
  7228. end;
  7229. { The instruction can be safely moved }
  7230. asml.Remove(hp1);
  7231. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7232. can be optimised into "xor %reg,%reg" later }
  7233. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7234. asml.InsertBefore(hp1, hp2)
  7235. else
  7236. { Note, if p.Previous is nil (even if it should logically never be the
  7237. case), FindRegAllocBackward immediately exits with False and so we
  7238. safely land here (we can't just pass p because FindRegAllocBackward
  7239. immediately exits on an instruction). [Kit] }
  7240. asml.InsertBefore(hp1, p);
  7241. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7242. for X := 0 to taicpu(hp1).ops - 1 do
  7243. case taicpu(hp1).oper[X]^.typ of
  7244. top_reg:
  7245. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7246. top_ref:
  7247. begin
  7248. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7249. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7250. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7251. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7252. end;
  7253. else
  7254. ;
  7255. end;
  7256. if taicpu(hp1).opcode = A_LEA then
  7257. { The flags will be overwritten by the CMP/TEST instruction }
  7258. ConvertLEA(taicpu(hp1));
  7259. Result := True;
  7260. end;
  7261. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7262. function IsXCHGAcceptable: Boolean; inline;
  7263. begin
  7264. { Always accept if optimising for size }
  7265. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7266. (
  7267. {$ifdef x86_64}
  7268. { XCHG takes 3 cycles on AMD Athlon64 }
  7269. (current_settings.optimizecputype >= cpu_core_i)
  7270. {$else x86_64}
  7271. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7272. than 3, so it becomes a saving compared to three MOVs with two of
  7273. them able to execute simultaneously. [Kit] }
  7274. (current_settings.optimizecputype >= cpu_PentiumM)
  7275. {$endif x86_64}
  7276. );
  7277. end;
  7278. var
  7279. NewRef: TReference;
  7280. hp1, hp2, hp3, hp4: Tai;
  7281. {$ifndef x86_64}
  7282. OperIdx: Integer;
  7283. {$endif x86_64}
  7284. NewInstr : Taicpu;
  7285. NewAligh : Tai_align;
  7286. DestLabel: TAsmLabel;
  7287. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7288. var
  7289. NextInstr: tai;
  7290. begin
  7291. Result := False;
  7292. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7293. if not GetNextInstruction(InputInstr, NextInstr) or
  7294. (
  7295. { The FLAGS register isn't always tracked properly, so do not
  7296. perform this optimisation if a conditional statement follows }
  7297. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7298. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7299. ) then
  7300. begin
  7301. reference_reset(NewRef, 1, []);
  7302. NewRef.base := taicpu(p).oper[0]^.reg;
  7303. NewRef.scalefactor := 1;
  7304. if taicpu(InputInstr).opcode = A_ADD then
  7305. begin
  7306. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7307. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7308. end
  7309. else
  7310. begin
  7311. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7312. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7313. end;
  7314. taicpu(p).opcode := A_LEA;
  7315. taicpu(p).loadref(0, NewRef);
  7316. RemoveInstruction(InputInstr);
  7317. Result := True;
  7318. end;
  7319. end;
  7320. begin
  7321. Result:=false;
  7322. { This optimisation adds an instruction, so only do it for speed }
  7323. if not (cs_opt_size in current_settings.optimizerswitches) and
  7324. MatchOpType(taicpu(p), top_const, top_reg) and
  7325. (taicpu(p).oper[0]^.val = 0) then
  7326. begin
  7327. { To avoid compiler warning }
  7328. DestLabel := nil;
  7329. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7330. InternalError(2021040750);
  7331. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7332. Exit;
  7333. case hp1.typ of
  7334. ait_label:
  7335. begin
  7336. { Change:
  7337. mov $0,%reg mov $0,%reg
  7338. @Lbl1: @Lbl1:
  7339. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7340. je @Lbl2 jne @Lbl2
  7341. To: To:
  7342. mov $0,%reg mov $0,%reg
  7343. jmp @Lbl2 jmp @Lbl3
  7344. (align) (align)
  7345. @Lbl1: @Lbl1:
  7346. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7347. je @Lbl2 je @Lbl2
  7348. @Lbl3: <-- Only if label exists
  7349. (Not if it's optimised for size)
  7350. }
  7351. if not GetNextInstruction(hp1, hp2) then
  7352. Exit;
  7353. if not (cs_opt_size in current_settings.optimizerswitches) and
  7354. (hp2.typ = ait_instruction) and
  7355. (
  7356. { Register sizes must exactly match }
  7357. (
  7358. (taicpu(hp2).opcode = A_CMP) and
  7359. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7360. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7361. ) or (
  7362. (taicpu(hp2).opcode = A_TEST) and
  7363. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7364. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7365. )
  7366. ) and GetNextInstruction(hp2, hp3) and
  7367. (hp3.typ = ait_instruction) and
  7368. (taicpu(hp3).opcode = A_JCC) and
  7369. (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
  7370. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7371. begin
  7372. { Check condition of jump }
  7373. { Always true? }
  7374. if condition_in(C_E, taicpu(hp3).condition) then
  7375. begin
  7376. { Copy label symbol and obtain matching label entry for the
  7377. conditional jump, as this will be our destination}
  7378. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7379. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7380. Result := True;
  7381. end
  7382. { Always false? }
  7383. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7384. begin
  7385. { This is only worth it if there's a jump to take }
  7386. case hp2.typ of
  7387. ait_instruction:
  7388. begin
  7389. if taicpu(hp2).opcode = A_JMP then
  7390. begin
  7391. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7392. { An unconditional jump follows the conditional jump which will always be false,
  7393. so use this jump's destination for the new jump }
  7394. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7395. Result := True;
  7396. end
  7397. else if taicpu(hp2).opcode = A_JCC then
  7398. begin
  7399. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7400. if condition_in(C_E, taicpu(hp2).condition) then
  7401. begin
  7402. { A second conditional jump follows the conditional jump which will always be false,
  7403. while the second jump is always True, so use this jump's destination for the new jump }
  7404. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7405. Result := True;
  7406. end;
  7407. { Don't risk it if the jump isn't always true (Result remains False) }
  7408. end;
  7409. end;
  7410. else
  7411. { If anything else don't optimise };
  7412. end;
  7413. end;
  7414. if Result then
  7415. begin
  7416. { Just so we have something to insert as a paremeter}
  7417. reference_reset(NewRef, 1, []);
  7418. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7419. { Now actually load the correct parameter }
  7420. NewInstr.loadsymbol(0, DestLabel, 0);
  7421. { Get instruction before original label (may not be p under -O3) }
  7422. if not GetLastInstruction(hp1, hp2) then
  7423. { Shouldn't fail here }
  7424. InternalError(2021040701);
  7425. DestLabel.increfs;
  7426. AsmL.InsertAfter(NewInstr, hp2);
  7427. { Add new alignment field }
  7428. (* AsmL.InsertAfter(
  7429. cai_align.create_max(
  7430. current_settings.alignment.jumpalign,
  7431. current_settings.alignment.jumpalignskipmax
  7432. ),
  7433. NewInstr
  7434. ); *)
  7435. end;
  7436. Exit;
  7437. end;
  7438. end;
  7439. else
  7440. ;
  7441. end;
  7442. end;
  7443. if not GetNextInstruction(p, hp1) then
  7444. Exit;
  7445. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7446. and DoMovCmpMemOpt(p, hp1, True) then
  7447. begin
  7448. Result := True;
  7449. Exit;
  7450. end
  7451. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7452. begin
  7453. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7454. further, but we can't just put this jump optimisation in pass 1
  7455. because it tends to perform worse when conditional jumps are
  7456. nearby (e.g. when converting CMOV instructions). [Kit] }
  7457. if OptPass2JMP(hp1) then
  7458. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7459. Result := OptPass1MOV(p)
  7460. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7461. returned True and the instruction is still a MOV, thus checking
  7462. the optimisations below }
  7463. { If OptPass2JMP returned False, no optimisations were done to
  7464. the jump and there are no further optimisations that can be done
  7465. to the MOV instruction on this pass }
  7466. end
  7467. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7468. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7469. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7470. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7471. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7472. begin
  7473. { Change:
  7474. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7475. addl/q $x,%reg2 subl/q $x,%reg2
  7476. To:
  7477. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7478. }
  7479. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7480. { be lazy, checking separately for sub would be slightly better }
  7481. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7482. begin
  7483. TransferUsedRegs(TmpUsedRegs);
  7484. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7485. if TryMovArith2Lea(hp1) then
  7486. begin
  7487. Result := True;
  7488. Exit;
  7489. end
  7490. end
  7491. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7492. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7493. { Same as above, but also adds or subtracts to %reg2 in between.
  7494. It's still valid as long as the flags aren't in use }
  7495. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7496. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7497. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7498. { be lazy, checking separately for sub would be slightly better }
  7499. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7500. begin
  7501. TransferUsedRegs(TmpUsedRegs);
  7502. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7503. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7504. if TryMovArith2Lea(hp2) then
  7505. begin
  7506. Result := True;
  7507. Exit;
  7508. end;
  7509. end;
  7510. end
  7511. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7512. {$ifdef x86_64}
  7513. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7514. {$else x86_64}
  7515. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7516. {$endif x86_64}
  7517. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7518. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7519. { mov reg1, reg2 mov reg1, reg2
  7520. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7521. begin
  7522. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7523. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7524. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7525. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7526. TransferUsedRegs(TmpUsedRegs);
  7527. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7528. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7529. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7530. then
  7531. begin
  7532. RemoveCurrentP(p, hp1);
  7533. Result:=true;
  7534. end;
  7535. exit;
  7536. end
  7537. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7538. IsXCHGAcceptable and
  7539. { XCHG doesn't support 8-byte registers }
  7540. (taicpu(p).opsize <> S_B) and
  7541. MatchInstruction(hp1, A_MOV, []) and
  7542. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7543. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7544. GetNextInstruction(hp1, hp2) and
  7545. MatchInstruction(hp2, A_MOV, []) and
  7546. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7547. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7548. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7549. begin
  7550. { mov %reg1,%reg2
  7551. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7552. mov %reg2,%reg3
  7553. (%reg2 not used afterwards)
  7554. Note that xchg takes 3 cycles to execute, and generally mov's take
  7555. only one cycle apiece, but the first two mov's can be executed in
  7556. parallel, only taking 2 cycles overall. Older processors should
  7557. therefore only optimise for size. [Kit]
  7558. }
  7559. TransferUsedRegs(TmpUsedRegs);
  7560. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7561. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7562. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7563. begin
  7564. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7565. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7566. taicpu(hp1).opcode := A_XCHG;
  7567. RemoveCurrentP(p, hp1);
  7568. RemoveInstruction(hp2);
  7569. Result := True;
  7570. Exit;
  7571. end;
  7572. end
  7573. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7574. MatchInstruction(hp1, A_SAR, []) then
  7575. begin
  7576. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7577. begin
  7578. { the use of %edx also covers the opsize being S_L }
  7579. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7580. begin
  7581. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7582. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7583. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7584. begin
  7585. { Change:
  7586. movl %eax,%edx
  7587. sarl $31,%edx
  7588. To:
  7589. cltd
  7590. }
  7591. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7592. RemoveInstruction(hp1);
  7593. taicpu(p).opcode := A_CDQ;
  7594. taicpu(p).opsize := S_NO;
  7595. taicpu(p).clearop(1);
  7596. taicpu(p).clearop(0);
  7597. taicpu(p).ops:=0;
  7598. Result := True;
  7599. end
  7600. else if (cs_opt_size in current_settings.optimizerswitches) and
  7601. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7602. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7603. begin
  7604. { Change:
  7605. movl %edx,%eax
  7606. sarl $31,%edx
  7607. To:
  7608. movl %edx,%eax
  7609. cltd
  7610. Note that this creates a dependency between the two instructions,
  7611. so only perform if optimising for size.
  7612. }
  7613. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7614. taicpu(hp1).opcode := A_CDQ;
  7615. taicpu(hp1).opsize := S_NO;
  7616. taicpu(hp1).clearop(1);
  7617. taicpu(hp1).clearop(0);
  7618. taicpu(hp1).ops:=0;
  7619. end;
  7620. {$ifndef x86_64}
  7621. end
  7622. { Don't bother if CMOV is supported, because a more optimal
  7623. sequence would have been generated for the Abs() intrinsic }
  7624. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7625. { the use of %eax also covers the opsize being S_L }
  7626. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7627. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7628. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7629. GetNextInstruction(hp1, hp2) and
  7630. MatchInstruction(hp2, A_XOR, [S_L]) and
  7631. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7632. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7633. GetNextInstruction(hp2, hp3) and
  7634. MatchInstruction(hp3, A_SUB, [S_L]) and
  7635. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7636. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7637. begin
  7638. { Change:
  7639. movl %eax,%edx
  7640. sarl $31,%eax
  7641. xorl %eax,%edx
  7642. subl %eax,%edx
  7643. (Instruction that uses %edx)
  7644. (%eax deallocated)
  7645. (%edx deallocated)
  7646. To:
  7647. cltd
  7648. xorl %edx,%eax <-- Note the registers have swapped
  7649. subl %edx,%eax
  7650. (Instruction that uses %eax) <-- %eax rather than %edx
  7651. }
  7652. TransferUsedRegs(TmpUsedRegs);
  7653. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7654. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7655. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7656. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7657. begin
  7658. if GetNextInstruction(hp3, hp4) and
  7659. not RegModifiedByInstruction(NR_EDX, hp4) and
  7660. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7661. begin
  7662. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7663. taicpu(p).opcode := A_CDQ;
  7664. taicpu(p).clearop(1);
  7665. taicpu(p).clearop(0);
  7666. taicpu(p).ops:=0;
  7667. RemoveInstruction(hp1);
  7668. taicpu(hp2).loadreg(0, NR_EDX);
  7669. taicpu(hp2).loadreg(1, NR_EAX);
  7670. taicpu(hp3).loadreg(0, NR_EDX);
  7671. taicpu(hp3).loadreg(1, NR_EAX);
  7672. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7673. { Convert references in the following instruction (hp4) from %edx to %eax }
  7674. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7675. with taicpu(hp4).oper[OperIdx]^ do
  7676. case typ of
  7677. top_reg:
  7678. if getsupreg(reg) = RS_EDX then
  7679. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7680. top_ref:
  7681. begin
  7682. if getsupreg(reg) = RS_EDX then
  7683. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7684. if getsupreg(reg) = RS_EDX then
  7685. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7686. end;
  7687. else
  7688. ;
  7689. end;
  7690. end;
  7691. end;
  7692. {$else x86_64}
  7693. end;
  7694. end
  7695. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7696. { the use of %rdx also covers the opsize being S_Q }
  7697. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7698. begin
  7699. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7700. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7701. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7702. begin
  7703. { Change:
  7704. movq %rax,%rdx
  7705. sarq $63,%rdx
  7706. To:
  7707. cqto
  7708. }
  7709. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7710. RemoveInstruction(hp1);
  7711. taicpu(p).opcode := A_CQO;
  7712. taicpu(p).opsize := S_NO;
  7713. taicpu(p).clearop(1);
  7714. taicpu(p).clearop(0);
  7715. taicpu(p).ops:=0;
  7716. Result := True;
  7717. end
  7718. else if (cs_opt_size in current_settings.optimizerswitches) and
  7719. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7720. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7721. begin
  7722. { Change:
  7723. movq %rdx,%rax
  7724. sarq $63,%rdx
  7725. To:
  7726. movq %rdx,%rax
  7727. cqto
  7728. Note that this creates a dependency between the two instructions,
  7729. so only perform if optimising for size.
  7730. }
  7731. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7732. taicpu(hp1).opcode := A_CQO;
  7733. taicpu(hp1).opsize := S_NO;
  7734. taicpu(hp1).clearop(1);
  7735. taicpu(hp1).clearop(0);
  7736. taicpu(hp1).ops:=0;
  7737. {$endif x86_64}
  7738. end;
  7739. end;
  7740. end
  7741. else if MatchInstruction(hp1, A_MOV, []) and
  7742. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7743. { Though "GetNextInstruction" could be factored out, along with
  7744. the instructions that depend on hp2, it is an expensive call that
  7745. should be delayed for as long as possible, hence we do cheaper
  7746. checks first that are likely to be False. [Kit] }
  7747. begin
  7748. if (
  7749. (
  7750. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7751. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7752. (
  7753. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7754. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7755. )
  7756. ) or
  7757. (
  7758. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7759. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7760. (
  7761. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7762. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7763. )
  7764. )
  7765. ) and
  7766. GetNextInstruction(hp1, hp2) and
  7767. MatchInstruction(hp2, A_SAR, []) and
  7768. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7769. begin
  7770. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7771. begin
  7772. { Change:
  7773. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7774. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7775. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7776. To:
  7777. movl r/m,%eax <- Note the change in register
  7778. cltd
  7779. }
  7780. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7781. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7782. taicpu(p).loadreg(1, NR_EAX);
  7783. taicpu(hp1).opcode := A_CDQ;
  7784. taicpu(hp1).clearop(1);
  7785. taicpu(hp1).clearop(0);
  7786. taicpu(hp1).ops:=0;
  7787. RemoveInstruction(hp2);
  7788. (*
  7789. {$ifdef x86_64}
  7790. end
  7791. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7792. { This code sequence does not get generated - however it might become useful
  7793. if and when 128-bit signed integer types make an appearance, so the code
  7794. is kept here for when it is eventually needed. [Kit] }
  7795. (
  7796. (
  7797. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7798. (
  7799. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7800. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7801. )
  7802. ) or
  7803. (
  7804. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7805. (
  7806. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7807. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7808. )
  7809. )
  7810. ) and
  7811. GetNextInstruction(hp1, hp2) and
  7812. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7813. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7814. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7815. begin
  7816. { Change:
  7817. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7818. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7819. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7820. To:
  7821. movq r/m,%rax <- Note the change in register
  7822. cqto
  7823. }
  7824. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7825. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7826. taicpu(p).loadreg(1, NR_RAX);
  7827. taicpu(hp1).opcode := A_CQO;
  7828. taicpu(hp1).clearop(1);
  7829. taicpu(hp1).clearop(0);
  7830. taicpu(hp1).ops:=0;
  7831. RemoveInstruction(hp2);
  7832. {$endif x86_64}
  7833. *)
  7834. end;
  7835. end;
  7836. {$ifdef x86_64}
  7837. end
  7838. else if (taicpu(p).opsize = S_L) and
  7839. (taicpu(p).oper[1]^.typ = top_reg) and
  7840. (
  7841. MatchInstruction(hp1, A_MOV,[]) and
  7842. (taicpu(hp1).opsize = S_L) and
  7843. (taicpu(hp1).oper[1]^.typ = top_reg)
  7844. ) and (
  7845. GetNextInstruction(hp1, hp2) and
  7846. (tai(hp2).typ=ait_instruction) and
  7847. (taicpu(hp2).opsize = S_Q) and
  7848. (
  7849. (
  7850. MatchInstruction(hp2, A_ADD,[]) and
  7851. (taicpu(hp2).opsize = S_Q) and
  7852. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7853. (
  7854. (
  7855. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7856. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7857. ) or (
  7858. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7859. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7860. )
  7861. )
  7862. ) or (
  7863. MatchInstruction(hp2, A_LEA,[]) and
  7864. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7865. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7866. (
  7867. (
  7868. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7869. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7870. ) or (
  7871. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7872. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7873. )
  7874. ) and (
  7875. (
  7876. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7877. ) or (
  7878. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7879. )
  7880. )
  7881. )
  7882. )
  7883. ) and (
  7884. GetNextInstruction(hp2, hp3) and
  7885. MatchInstruction(hp3, A_SHR,[]) and
  7886. (taicpu(hp3).opsize = S_Q) and
  7887. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7888. (taicpu(hp3).oper[0]^.val = 1) and
  7889. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7890. ) then
  7891. begin
  7892. { Change movl x, reg1d movl x, reg1d
  7893. movl y, reg2d movl y, reg2d
  7894. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7895. shrq $1, reg1q shrq $1, reg1q
  7896. ( reg1d and reg2d can be switched around in the first two instructions )
  7897. To movl x, reg1d
  7898. addl y, reg1d
  7899. rcrl $1, reg1d
  7900. This corresponds to the common expression (x + y) shr 1, where
  7901. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7902. smaller code, but won't account for x + y causing an overflow). [Kit]
  7903. }
  7904. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7905. { Change first MOV command to have the same register as the final output }
  7906. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7907. else
  7908. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7909. { Change second MOV command to an ADD command. This is easier than
  7910. converting the existing command because it means we don't have to
  7911. touch 'y', which might be a complicated reference, and also the
  7912. fact that the third command might either be ADD or LEA. [Kit] }
  7913. taicpu(hp1).opcode := A_ADD;
  7914. { Delete old ADD/LEA instruction }
  7915. RemoveInstruction(hp2);
  7916. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7917. taicpu(hp3).opcode := A_RCR;
  7918. taicpu(hp3).changeopsize(S_L);
  7919. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7920. {$endif x86_64}
  7921. end;
  7922. end;
  7923. {$push}
  7924. {$q-}{$r-}
  7925. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7926. var
  7927. ThisReg: TRegister;
  7928. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7929. TargetSubReg: TSubRegister;
  7930. hp1, hp2: tai;
  7931. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7932. { Store list of found instructions so we don't have to call
  7933. GetNextInstructionUsingReg multiple times }
  7934. InstrList: array of taicpu;
  7935. InstrMax, Index: Integer;
  7936. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7937. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7938. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7939. WorkingValue: TCgInt;
  7940. PreMessage: string;
  7941. { Data flow analysis }
  7942. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7943. BitwiseOnly, OrXorUsed,
  7944. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7945. function CheckOverflowConditions: Boolean;
  7946. begin
  7947. Result := True;
  7948. if (TestValSignedMax > SignedUpperLimit) then
  7949. UpperSignedOverflow := True;
  7950. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7951. LowerSignedOverflow := True;
  7952. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7953. LowerUnsignedOverflow := True;
  7954. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7955. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7956. begin
  7957. { Absolute overflow }
  7958. Result := False;
  7959. Exit;
  7960. end;
  7961. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7962. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7963. ShiftDownOverflow := True;
  7964. if (TestValMin < 0) or (TestValMax < 0) then
  7965. begin
  7966. LowerUnsignedOverflow := True;
  7967. UpperUnsignedOverflow := True;
  7968. end;
  7969. end;
  7970. function AdjustInitialLoadAndSize: Boolean;
  7971. begin
  7972. Result := False;
  7973. if not p_removed then
  7974. begin
  7975. if TargetSize = MinSize then
  7976. begin
  7977. { Convert the input MOVZX to a MOV }
  7978. if (taicpu(p).oper[0]^.typ = top_reg) and
  7979. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7980. begin
  7981. { Or remove it completely! }
  7982. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7983. RemoveCurrentP(p);
  7984. p_removed := True;
  7985. end
  7986. else
  7987. begin
  7988. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7989. taicpu(p).opcode := A_MOV;
  7990. taicpu(p).oper[1]^.reg := ThisReg;
  7991. taicpu(p).opsize := TargetSize;
  7992. end;
  7993. Result := True;
  7994. end
  7995. else if TargetSize <> MaxSize then
  7996. begin
  7997. case MaxSize of
  7998. S_L:
  7999. if TargetSize = S_W then
  8000. begin
  8001. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8002. taicpu(p).opsize := S_BW;
  8003. taicpu(p).oper[1]^.reg := ThisReg;
  8004. Result := True;
  8005. end
  8006. else
  8007. InternalError(2020112341);
  8008. S_W:
  8009. if TargetSize = S_L then
  8010. begin
  8011. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8012. taicpu(p).opsize := S_BL;
  8013. taicpu(p).oper[1]^.reg := ThisReg;
  8014. Result := True;
  8015. end
  8016. else
  8017. InternalError(2020112342);
  8018. else
  8019. ;
  8020. end;
  8021. end
  8022. else if not hp1_removed and not RegInUse then
  8023. begin
  8024. { If we have something like:
  8025. movzbl (oper),%regd
  8026. add x, %regd
  8027. movzbl %regb, %regd
  8028. We can reduce the register size to the input of the final
  8029. movzbl instruction. Overflows won't have any effect.
  8030. }
  8031. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8032. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8033. begin
  8034. TargetSize := S_B;
  8035. setsubreg(ThisReg, R_SUBL);
  8036. Result := True;
  8037. end
  8038. else if (taicpu(p).opsize = S_WL) and
  8039. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8040. begin
  8041. TargetSize := S_W;
  8042. setsubreg(ThisReg, R_SUBW);
  8043. Result := True;
  8044. end;
  8045. if Result then
  8046. begin
  8047. { Convert the input MOVZX to a MOV }
  8048. if (taicpu(p).oper[0]^.typ = top_reg) and
  8049. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8050. begin
  8051. { Or remove it completely! }
  8052. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8053. RemoveCurrentP(p);
  8054. p_removed := True;
  8055. end
  8056. else
  8057. begin
  8058. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8059. taicpu(p).opcode := A_MOV;
  8060. taicpu(p).oper[1]^.reg := ThisReg;
  8061. taicpu(p).opsize := TargetSize;
  8062. end;
  8063. end;
  8064. end;
  8065. end;
  8066. end;
  8067. procedure AdjustFinalLoad;
  8068. begin
  8069. if not LowerUnsignedOverflow then
  8070. begin
  8071. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8072. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8073. begin
  8074. { Convert the output MOVZX to a MOV }
  8075. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8076. begin
  8077. { Or remove it completely! }
  8078. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8079. { Be careful; if p = hp1 and p was also removed, p
  8080. will become a dangling pointer }
  8081. if p = hp1 then
  8082. begin
  8083. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8084. p_removed := True;
  8085. end
  8086. else
  8087. RemoveInstruction(hp1);
  8088. hp1_removed := True;
  8089. end
  8090. else
  8091. begin
  8092. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8093. taicpu(hp1).opcode := A_MOV;
  8094. taicpu(hp1).oper[0]^.reg := ThisReg;
  8095. taicpu(hp1).opsize := TargetSize;
  8096. end;
  8097. end
  8098. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8099. begin
  8100. { Need to change the size of the output }
  8101. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8102. taicpu(hp1).oper[0]^.reg := ThisReg;
  8103. taicpu(hp1).opsize := S_BL;
  8104. end;
  8105. end;
  8106. end;
  8107. function CompressInstructions: Boolean;
  8108. var
  8109. LocalIndex: Integer;
  8110. begin
  8111. Result := False;
  8112. { The objective here is to try to find a combination that
  8113. removes one of the MOV/Z instructions. }
  8114. if (
  8115. (taicpu(p).oper[0]^.typ <> top_reg) or
  8116. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8117. ) and
  8118. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8119. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8120. begin
  8121. { Make a preference to remove the second MOVZX instruction }
  8122. case taicpu(hp1).opsize of
  8123. S_BL, S_WL:
  8124. begin
  8125. TargetSize := S_L;
  8126. TargetSubReg := R_SUBD;
  8127. end;
  8128. S_BW:
  8129. begin
  8130. TargetSize := S_W;
  8131. TargetSubReg := R_SUBW;
  8132. end;
  8133. else
  8134. InternalError(2020112302);
  8135. end;
  8136. end
  8137. else
  8138. begin
  8139. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8140. begin
  8141. { Exceeded lower bound but not upper bound }
  8142. TargetSize := MaxSize;
  8143. end
  8144. else if not LowerUnsignedOverflow then
  8145. begin
  8146. { Size didn't exceed lower bound }
  8147. TargetSize := MinSize;
  8148. end
  8149. else
  8150. Exit;
  8151. end;
  8152. case TargetSize of
  8153. S_B:
  8154. TargetSubReg := R_SUBL;
  8155. S_W:
  8156. TargetSubReg := R_SUBW;
  8157. S_L:
  8158. TargetSubReg := R_SUBD;
  8159. else
  8160. InternalError(2020112350);
  8161. end;
  8162. { Update the register to its new size }
  8163. setsubreg(ThisReg, TargetSubReg);
  8164. RegInUse := False;
  8165. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8166. begin
  8167. { Check to see if the active register is used afterwards;
  8168. if not, we can change it and make a saving. }
  8169. TransferUsedRegs(TmpUsedRegs);
  8170. { The target register may be marked as in use to cross
  8171. a jump to a distant label, so exclude it }
  8172. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8173. hp2 := p;
  8174. repeat
  8175. { Explicitly check for the excluded register (don't include the first
  8176. instruction as it may be reading from here }
  8177. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8178. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8179. begin
  8180. RegInUse := True;
  8181. Break;
  8182. end;
  8183. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8184. if not GetNextInstruction(hp2, hp2) then
  8185. InternalError(2020112340);
  8186. until (hp2 = hp1);
  8187. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8188. { We might still be able to get away with this }
  8189. RegInUse := not
  8190. (
  8191. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8192. (hp2.typ = ait_instruction) and
  8193. (
  8194. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8195. instruction that doesn't actually contain ThisReg }
  8196. (cs_opt_level3 in current_settings.optimizerswitches) or
  8197. RegInInstruction(ThisReg, hp2)
  8198. ) and
  8199. RegLoadedWithNewValue(ThisReg, hp2)
  8200. );
  8201. if not RegInUse then
  8202. begin
  8203. { Force the register size to the same as this instruction so it can be removed}
  8204. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8205. begin
  8206. TargetSize := S_L;
  8207. TargetSubReg := R_SUBD;
  8208. end
  8209. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8210. begin
  8211. TargetSize := S_W;
  8212. TargetSubReg := R_SUBW;
  8213. end;
  8214. ThisReg := taicpu(hp1).oper[1]^.reg;
  8215. setsubreg(ThisReg, TargetSubReg);
  8216. RegChanged := True;
  8217. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8218. TransferUsedRegs(TmpUsedRegs);
  8219. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8220. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8221. if p = hp1 then
  8222. begin
  8223. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8224. p_removed := True;
  8225. end
  8226. else
  8227. RemoveInstruction(hp1);
  8228. hp1_removed := True;
  8229. { Instruction will become "mov %reg,%reg" }
  8230. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8231. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8232. begin
  8233. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8234. RemoveCurrentP(p);
  8235. p_removed := True;
  8236. end
  8237. else
  8238. taicpu(p).oper[1]^.reg := ThisReg;
  8239. Result := True;
  8240. end
  8241. else
  8242. begin
  8243. if TargetSize <> MaxSize then
  8244. begin
  8245. { Since the register is in use, we have to force it to
  8246. MaxSize otherwise part of it may become undefined later on }
  8247. TargetSize := MaxSize;
  8248. case TargetSize of
  8249. S_B:
  8250. TargetSubReg := R_SUBL;
  8251. S_W:
  8252. TargetSubReg := R_SUBW;
  8253. S_L:
  8254. TargetSubReg := R_SUBD;
  8255. else
  8256. InternalError(2020112351);
  8257. end;
  8258. setsubreg(ThisReg, TargetSubReg);
  8259. end;
  8260. AdjustFinalLoad;
  8261. end;
  8262. end
  8263. else
  8264. AdjustFinalLoad;
  8265. Result := AdjustInitialLoadAndSize or Result;
  8266. { Now go through every instruction we found and change the
  8267. size. If TargetSize = MaxSize, then almost no changes are
  8268. needed and Result can remain False if it hasn't been set
  8269. yet.
  8270. If RegChanged is True, then the register requires changing
  8271. and so the point about TargetSize = MaxSize doesn't apply. }
  8272. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8273. begin
  8274. for LocalIndex := 0 to InstrMax do
  8275. begin
  8276. { If p_removed is true, then the original MOV/Z was removed
  8277. and removing the AND instruction may not be safe if it
  8278. appears first }
  8279. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8280. InternalError(2020112310);
  8281. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8282. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8283. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8284. InstrList[LocalIndex].opsize := TargetSize;
  8285. end;
  8286. Result := True;
  8287. end;
  8288. end;
  8289. begin
  8290. Result := False;
  8291. p_removed := False;
  8292. hp1_removed := False;
  8293. ThisReg := taicpu(p).oper[1]^.reg;
  8294. { Check for:
  8295. movs/z ###,%ecx (or %cx or %rcx)
  8296. ...
  8297. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8298. (dealloc %ecx)
  8299. Change to:
  8300. mov ###,%cl (if ### = %cl, then remove completely)
  8301. ...
  8302. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8303. }
  8304. if (getsupreg(ThisReg) = RS_ECX) and
  8305. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8306. (hp1.typ = ait_instruction) and
  8307. (
  8308. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8309. instruction that doesn't actually contain ECX }
  8310. (cs_opt_level3 in current_settings.optimizerswitches) or
  8311. RegInInstruction(NR_ECX, hp1) or
  8312. (
  8313. { It's common for the shift/rotate's read/write register to be
  8314. initialised in between, so under -O2 and under, search ahead
  8315. one more instruction
  8316. }
  8317. GetNextInstruction(hp1, hp1) and
  8318. (hp1.typ = ait_instruction) and
  8319. RegInInstruction(NR_ECX, hp1)
  8320. )
  8321. ) and
  8322. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8323. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8324. begin
  8325. TransferUsedRegs(TmpUsedRegs);
  8326. hp2 := p;
  8327. repeat
  8328. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8329. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8330. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8331. begin
  8332. case taicpu(p).opsize of
  8333. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8334. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8335. begin
  8336. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8337. RemoveCurrentP(p);
  8338. end
  8339. else
  8340. begin
  8341. taicpu(p).opcode := A_MOV;
  8342. taicpu(p).opsize := S_B;
  8343. taicpu(p).oper[1]^.reg := NR_CL;
  8344. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8345. end;
  8346. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8347. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8348. begin
  8349. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8350. RemoveCurrentP(p);
  8351. end
  8352. else
  8353. begin
  8354. taicpu(p).opcode := A_MOV;
  8355. taicpu(p).opsize := S_W;
  8356. taicpu(p).oper[1]^.reg := NR_CX;
  8357. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8358. end;
  8359. {$ifdef x86_64}
  8360. S_LQ:
  8361. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8362. begin
  8363. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8364. RemoveCurrentP(p);
  8365. end
  8366. else
  8367. begin
  8368. taicpu(p).opcode := A_MOV;
  8369. taicpu(p).opsize := S_L;
  8370. taicpu(p).oper[1]^.reg := NR_ECX;
  8371. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8372. end;
  8373. {$endif x86_64}
  8374. else
  8375. InternalError(2021120401);
  8376. end;
  8377. Result := True;
  8378. Exit;
  8379. end;
  8380. end;
  8381. { This is anything but quick! }
  8382. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8383. Exit;
  8384. SetLength(InstrList, 0);
  8385. InstrMax := -1;
  8386. case taicpu(p).opsize of
  8387. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8388. begin
  8389. {$if defined(i386) or defined(i8086)}
  8390. { If the target size is 8-bit, make sure we can actually encode it }
  8391. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8392. Exit;
  8393. {$endif i386 or i8086}
  8394. LowerLimit := $FF;
  8395. SignedLowerLimit := $7F;
  8396. SignedLowerLimitBottom := -128;
  8397. MinSize := S_B;
  8398. if taicpu(p).opsize = S_BW then
  8399. begin
  8400. MaxSize := S_W;
  8401. UpperLimit := $FFFF;
  8402. SignedUpperLimit := $7FFF;
  8403. SignedUpperLimitBottom := -32768;
  8404. end
  8405. else
  8406. begin
  8407. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8408. MaxSize := S_L;
  8409. UpperLimit := $FFFFFFFF;
  8410. SignedUpperLimit := $7FFFFFFF;
  8411. SignedUpperLimitBottom := -2147483648;
  8412. end;
  8413. end;
  8414. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8415. begin
  8416. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8417. LowerLimit := $FFFF;
  8418. SignedLowerLimit := $7FFF;
  8419. SignedLowerLimitBottom := -32768;
  8420. UpperLimit := $FFFFFFFF;
  8421. SignedUpperLimit := $7FFFFFFF;
  8422. SignedUpperLimitBottom := -2147483648;
  8423. MinSize := S_W;
  8424. MaxSize := S_L;
  8425. end;
  8426. {$ifdef x86_64}
  8427. S_LQ:
  8428. begin
  8429. { Both the lower and upper limits are set to 32-bit. If a limit
  8430. is breached, then optimisation is impossible }
  8431. LowerLimit := $FFFFFFFF;
  8432. SignedLowerLimit := $7FFFFFFF;
  8433. SignedLowerLimitBottom := -2147483648;
  8434. UpperLimit := $FFFFFFFF;
  8435. SignedUpperLimit := $7FFFFFFF;
  8436. SignedUpperLimitBottom := -2147483648;
  8437. MinSize := S_L;
  8438. MaxSize := S_L;
  8439. end;
  8440. {$endif x86_64}
  8441. else
  8442. InternalError(2020112301);
  8443. end;
  8444. TestValMin := 0;
  8445. TestValMax := LowerLimit;
  8446. TestValSignedMax := SignedLowerLimit;
  8447. TryShiftDownLimit := LowerLimit;
  8448. TryShiftDown := S_NO;
  8449. ShiftDownOverflow := False;
  8450. RegChanged := False;
  8451. BitwiseOnly := True;
  8452. OrXorUsed := False;
  8453. UpperSignedOverflow := False;
  8454. LowerSignedOverflow := False;
  8455. UpperUnsignedOverflow := False;
  8456. LowerUnsignedOverflow := False;
  8457. hp1 := p;
  8458. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8459. (hp1.typ = ait_instruction) and
  8460. (
  8461. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8462. instruction that doesn't actually contain ThisReg }
  8463. (cs_opt_level3 in current_settings.optimizerswitches) or
  8464. { This allows this Movx optimisation to work through the SETcc instructions
  8465. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8466. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8467. skip over these SETcc instructions). }
  8468. (taicpu(hp1).opcode = A_SETcc) or
  8469. RegInInstruction(ThisReg, hp1)
  8470. ) do
  8471. begin
  8472. case taicpu(hp1).opcode of
  8473. A_INC,A_DEC:
  8474. begin
  8475. { Has to be an exact match on the register }
  8476. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8477. Break;
  8478. if taicpu(hp1).opcode = A_INC then
  8479. begin
  8480. Inc(TestValMin);
  8481. Inc(TestValMax);
  8482. Inc(TestValSignedMax);
  8483. end
  8484. else
  8485. begin
  8486. Dec(TestValMin);
  8487. Dec(TestValMax);
  8488. Dec(TestValSignedMax);
  8489. end;
  8490. end;
  8491. A_TEST, A_CMP:
  8492. begin
  8493. if (
  8494. { Too high a risk of non-linear behaviour that breaks DFA
  8495. here, unless it's cmp $0,%reg, which is equivalent to
  8496. test %reg,%reg }
  8497. OrXorUsed and
  8498. (taicpu(hp1).opcode = A_CMP) and
  8499. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8500. ) or
  8501. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8502. { Has to be an exact match on the register }
  8503. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8504. (
  8505. { Permit "test %reg,%reg" }
  8506. (taicpu(hp1).opcode = A_TEST) and
  8507. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8508. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8509. ) or
  8510. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8511. { Make sure the comparison value is not smaller than the
  8512. smallest allowed signed value for the minimum size (e.g.
  8513. -128 for 8-bit) }
  8514. not (
  8515. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8516. { Is it in the negative range? }
  8517. (
  8518. (taicpu(hp1).oper[0]^.val < 0) and
  8519. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8520. )
  8521. ) then
  8522. Break;
  8523. { Check to see if the active register is used afterwards }
  8524. TransferUsedRegs(TmpUsedRegs);
  8525. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8526. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8527. begin
  8528. { Make sure the comparison or any previous instructions
  8529. hasn't pushed the test values outside of the range of
  8530. MinSize }
  8531. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8532. begin
  8533. { Exceeded lower bound but not upper bound }
  8534. Exit;
  8535. end
  8536. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8537. begin
  8538. { Size didn't exceed lower bound }
  8539. TargetSize := MinSize;
  8540. end
  8541. else
  8542. Break;
  8543. case TargetSize of
  8544. S_B:
  8545. TargetSubReg := R_SUBL;
  8546. S_W:
  8547. TargetSubReg := R_SUBW;
  8548. S_L:
  8549. TargetSubReg := R_SUBD;
  8550. else
  8551. InternalError(2021051002);
  8552. end;
  8553. if TargetSize <> MaxSize then
  8554. begin
  8555. { Update the register to its new size }
  8556. setsubreg(ThisReg, TargetSubReg);
  8557. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8558. taicpu(hp1).oper[1]^.reg := ThisReg;
  8559. taicpu(hp1).opsize := TargetSize;
  8560. { Convert the input MOVZX to a MOV if necessary }
  8561. AdjustInitialLoadAndSize;
  8562. if (InstrMax >= 0) then
  8563. begin
  8564. for Index := 0 to InstrMax do
  8565. begin
  8566. { If p_removed is true, then the original MOV/Z was removed
  8567. and removing the AND instruction may not be safe if it
  8568. appears first }
  8569. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8570. InternalError(2020112311);
  8571. if InstrList[Index].oper[0]^.typ = top_reg then
  8572. InstrList[Index].oper[0]^.reg := ThisReg;
  8573. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8574. InstrList[Index].opsize := MinSize;
  8575. end;
  8576. end;
  8577. Result := True;
  8578. end;
  8579. Exit;
  8580. end;
  8581. end;
  8582. A_SETcc:
  8583. begin
  8584. { This allows this Movx optimisation to work through the SETcc instructions
  8585. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8586. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8587. skip over these SETcc instructions). }
  8588. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8589. { Of course, break out if the current register is used }
  8590. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8591. Break
  8592. else
  8593. { We must use Continue so the instruction doesn't get added
  8594. to InstrList }
  8595. Continue;
  8596. end;
  8597. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8598. begin
  8599. if
  8600. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8601. { Has to be an exact match on the register }
  8602. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8603. (
  8604. (
  8605. (taicpu(hp1).oper[0]^.typ = top_const) and
  8606. (
  8607. (
  8608. (taicpu(hp1).opcode = A_SHL) and
  8609. (
  8610. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8611. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8612. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8613. )
  8614. ) or (
  8615. (taicpu(hp1).opcode <> A_SHL) and
  8616. (
  8617. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8618. { Is it in the negative range? }
  8619. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8620. )
  8621. )
  8622. )
  8623. ) or (
  8624. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8625. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8626. )
  8627. ) then
  8628. Break;
  8629. { Only process OR and XOR if there are only bitwise operations,
  8630. since otherwise they can too easily fool the data flow
  8631. analysis (they can cause non-linear behaviour) }
  8632. case taicpu(hp1).opcode of
  8633. A_ADD:
  8634. begin
  8635. if OrXorUsed then
  8636. { Too high a risk of non-linear behaviour that breaks DFA here }
  8637. Break
  8638. else
  8639. BitwiseOnly := False;
  8640. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8641. begin
  8642. TestValMin := TestValMin * 2;
  8643. TestValMax := TestValMax * 2;
  8644. TestValSignedMax := TestValSignedMax * 2;
  8645. end
  8646. else
  8647. begin
  8648. WorkingValue := taicpu(hp1).oper[0]^.val;
  8649. TestValMin := TestValMin + WorkingValue;
  8650. TestValMax := TestValMax + WorkingValue;
  8651. TestValSignedMax := TestValSignedMax + WorkingValue;
  8652. end;
  8653. end;
  8654. A_SUB:
  8655. begin
  8656. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8657. begin
  8658. TestValMin := 0;
  8659. TestValMax := 0;
  8660. TestValSignedMax := 0;
  8661. end
  8662. else
  8663. begin
  8664. if OrXorUsed then
  8665. { Too high a risk of non-linear behaviour that breaks DFA here }
  8666. Break
  8667. else
  8668. BitwiseOnly := False;
  8669. WorkingValue := taicpu(hp1).oper[0]^.val;
  8670. TestValMin := TestValMin - WorkingValue;
  8671. TestValMax := TestValMax - WorkingValue;
  8672. TestValSignedMax := TestValSignedMax - WorkingValue;
  8673. end;
  8674. end;
  8675. A_AND:
  8676. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8677. begin
  8678. { we might be able to go smaller if AND appears first }
  8679. if InstrMax = -1 then
  8680. case MinSize of
  8681. S_B:
  8682. ;
  8683. S_W:
  8684. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8685. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8686. begin
  8687. TryShiftDown := S_B;
  8688. TryShiftDownLimit := $FF;
  8689. end;
  8690. S_L:
  8691. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8692. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8693. begin
  8694. TryShiftDown := S_B;
  8695. TryShiftDownLimit := $FF;
  8696. end
  8697. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8698. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8699. begin
  8700. TryShiftDown := S_W;
  8701. TryShiftDownLimit := $FFFF;
  8702. end;
  8703. else
  8704. InternalError(2020112320);
  8705. end;
  8706. WorkingValue := taicpu(hp1).oper[0]^.val;
  8707. TestValMin := TestValMin and WorkingValue;
  8708. TestValMax := TestValMax and WorkingValue;
  8709. TestValSignedMax := TestValSignedMax and WorkingValue;
  8710. end;
  8711. A_OR:
  8712. begin
  8713. if not BitwiseOnly then
  8714. Break;
  8715. OrXorUsed := True;
  8716. WorkingValue := taicpu(hp1).oper[0]^.val;
  8717. TestValMin := TestValMin or WorkingValue;
  8718. TestValMax := TestValMax or WorkingValue;
  8719. TestValSignedMax := TestValSignedMax or WorkingValue;
  8720. end;
  8721. A_XOR:
  8722. begin
  8723. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8724. begin
  8725. TestValMin := 0;
  8726. TestValMax := 0;
  8727. TestValSignedMax := 0;
  8728. end
  8729. else
  8730. begin
  8731. if not BitwiseOnly then
  8732. Break;
  8733. OrXorUsed := True;
  8734. WorkingValue := taicpu(hp1).oper[0]^.val;
  8735. TestValMin := TestValMin xor WorkingValue;
  8736. TestValMax := TestValMax xor WorkingValue;
  8737. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8738. end;
  8739. end;
  8740. A_SHL:
  8741. begin
  8742. BitwiseOnly := False;
  8743. WorkingValue := taicpu(hp1).oper[0]^.val;
  8744. TestValMin := TestValMin shl WorkingValue;
  8745. TestValMax := TestValMax shl WorkingValue;
  8746. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8747. end;
  8748. A_SHR,
  8749. { The first instruction was MOVZX, so the value won't be negative }
  8750. A_SAR:
  8751. begin
  8752. if InstrMax <> -1 then
  8753. BitwiseOnly := False
  8754. else
  8755. { we might be able to go smaller if SHR appears first }
  8756. case MinSize of
  8757. S_B:
  8758. ;
  8759. S_W:
  8760. if (taicpu(hp1).oper[0]^.val >= 8) then
  8761. begin
  8762. TryShiftDown := S_B;
  8763. TryShiftDownLimit := $FF;
  8764. TryShiftDownSignedLimit := $7F;
  8765. TryShiftDownSignedLimitLower := -128;
  8766. end;
  8767. S_L:
  8768. if (taicpu(hp1).oper[0]^.val >= 24) then
  8769. begin
  8770. TryShiftDown := S_B;
  8771. TryShiftDownLimit := $FF;
  8772. TryShiftDownSignedLimit := $7F;
  8773. TryShiftDownSignedLimitLower := -128;
  8774. end
  8775. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8776. begin
  8777. TryShiftDown := S_W;
  8778. TryShiftDownLimit := $FFFF;
  8779. TryShiftDownSignedLimit := $7FFF;
  8780. TryShiftDownSignedLimitLower := -32768;
  8781. end;
  8782. else
  8783. InternalError(2020112321);
  8784. end;
  8785. WorkingValue := taicpu(hp1).oper[0]^.val;
  8786. if taicpu(hp1).opcode = A_SAR then
  8787. begin
  8788. TestValMin := SarInt64(TestValMin, WorkingValue);
  8789. TestValMax := SarInt64(TestValMax, WorkingValue);
  8790. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8791. end
  8792. else
  8793. begin
  8794. TestValMin := TestValMin shr WorkingValue;
  8795. TestValMax := TestValMax shr WorkingValue;
  8796. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8797. end;
  8798. end;
  8799. else
  8800. InternalError(2020112303);
  8801. end;
  8802. end;
  8803. (*
  8804. A_IMUL:
  8805. case taicpu(hp1).ops of
  8806. 2:
  8807. begin
  8808. if not MatchOpType(hp1, top_reg, top_reg) or
  8809. { Has to be an exact match on the register }
  8810. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8811. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8812. Break;
  8813. TestValMin := TestValMin * TestValMin;
  8814. TestValMax := TestValMax * TestValMax;
  8815. TestValSignedMax := TestValSignedMax * TestValMax;
  8816. end;
  8817. 3:
  8818. begin
  8819. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8820. { Has to be an exact match on the register }
  8821. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8822. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8823. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8824. { Is it in the negative range? }
  8825. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8826. Break;
  8827. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8828. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8829. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8830. end;
  8831. else
  8832. Break;
  8833. end;
  8834. A_IDIV:
  8835. case taicpu(hp1).ops of
  8836. 3:
  8837. begin
  8838. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8839. { Has to be an exact match on the register }
  8840. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8841. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8842. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8843. { Is it in the negative range? }
  8844. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8845. Break;
  8846. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8847. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8848. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8849. end;
  8850. else
  8851. Break;
  8852. end;
  8853. *)
  8854. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8855. begin
  8856. { If there are no instructions in between, then we might be able to make a saving }
  8857. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8858. Break;
  8859. { We have something like:
  8860. movzbw %dl,%dx
  8861. ...
  8862. movswl %dx,%edx
  8863. Change the latter to a zero-extension then enter the
  8864. A_MOVZX case branch.
  8865. }
  8866. {$ifdef x86_64}
  8867. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8868. begin
  8869. { this becomes a zero extension from 32-bit to 64-bit, but
  8870. the upper 32 bits are already zero, so just delete the
  8871. instruction }
  8872. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8873. RemoveInstruction(hp1);
  8874. Result := True;
  8875. Exit;
  8876. end
  8877. else
  8878. {$endif x86_64}
  8879. begin
  8880. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8881. taicpu(hp1).opcode := A_MOVZX;
  8882. {$ifdef x86_64}
  8883. case taicpu(hp1).opsize of
  8884. S_BQ:
  8885. begin
  8886. taicpu(hp1).opsize := S_BL;
  8887. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8888. end;
  8889. S_WQ:
  8890. begin
  8891. taicpu(hp1).opsize := S_WL;
  8892. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8893. end;
  8894. S_LQ:
  8895. begin
  8896. taicpu(hp1).opcode := A_MOV;
  8897. taicpu(hp1).opsize := S_L;
  8898. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8899. { In this instance, we need to break out because the
  8900. instruction is no longer MOVZX or MOVSXD }
  8901. Result := True;
  8902. Exit;
  8903. end;
  8904. else
  8905. ;
  8906. end;
  8907. {$endif x86_64}
  8908. Result := CompressInstructions;
  8909. Exit;
  8910. end;
  8911. end;
  8912. A_MOVZX:
  8913. begin
  8914. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8915. Break;
  8916. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8917. begin
  8918. if (InstrMax = -1) and
  8919. { Will return false if the second parameter isn't ThisReg
  8920. (can happen on -O2 and under) }
  8921. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8922. begin
  8923. { The two MOVZX instructions are adjacent, so remove the first one }
  8924. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8925. RemoveCurrentP(p);
  8926. Result := True;
  8927. Exit;
  8928. end;
  8929. Break;
  8930. end;
  8931. Result := CompressInstructions;
  8932. Exit;
  8933. end;
  8934. else
  8935. { This includes ADC, SBB and IDIV }
  8936. Break;
  8937. end;
  8938. if not CheckOverflowConditions then
  8939. Break;
  8940. { Contains highest index (so instruction count - 1) }
  8941. Inc(InstrMax);
  8942. if InstrMax > High(InstrList) then
  8943. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8944. InstrList[InstrMax] := taicpu(hp1);
  8945. end;
  8946. end;
  8947. {$pop}
  8948. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8949. var
  8950. hp1 : tai;
  8951. begin
  8952. Result:=false;
  8953. if (taicpu(p).ops >= 2) and
  8954. ((taicpu(p).oper[0]^.typ = top_const) or
  8955. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8956. (taicpu(p).oper[1]^.typ = top_reg) and
  8957. ((taicpu(p).ops = 2) or
  8958. ((taicpu(p).oper[2]^.typ = top_reg) and
  8959. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8960. GetLastInstruction(p,hp1) and
  8961. MatchInstruction(hp1,A_MOV,[]) and
  8962. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8963. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8964. begin
  8965. TransferUsedRegs(TmpUsedRegs);
  8966. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8967. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8968. { change
  8969. mov reg1,reg2
  8970. imul y,reg2 to imul y,reg1,reg2 }
  8971. begin
  8972. taicpu(p).ops := 3;
  8973. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8974. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8975. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8976. RemoveInstruction(hp1);
  8977. result:=true;
  8978. end;
  8979. end;
  8980. end;
  8981. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8982. var
  8983. ThisLabel: TAsmLabel;
  8984. begin
  8985. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8986. ThisLabel.decrefs;
  8987. taicpu(p).opcode := A_RET;
  8988. taicpu(p).is_jmp := false;
  8989. taicpu(p).ops := taicpu(ret_p).ops;
  8990. case taicpu(ret_p).ops of
  8991. 0:
  8992. taicpu(p).clearop(0);
  8993. 1:
  8994. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8995. else
  8996. internalerror(2016041301);
  8997. end;
  8998. { If the original label is now dead, it might turn out that the label
  8999. immediately follows p. As a result, everything beyond it, which will
  9000. be just some final register configuration and a RET instruction, is
  9001. now dead code. [Kit] }
  9002. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9003. running RemoveDeadCodeAfterJump for each RET instruction, because
  9004. this optimisation rarely happens and most RETs appear at the end of
  9005. routines where there is nothing that can be stripped. [Kit] }
  9006. if not ThisLabel.is_used then
  9007. RemoveDeadCodeAfterJump(p);
  9008. end;
  9009. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9010. var
  9011. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9012. Unconditional, PotentialModified: Boolean;
  9013. OperPtr: POper;
  9014. NewRef: TReference;
  9015. InstrList: array of taicpu;
  9016. InstrMax, Index: Integer;
  9017. const
  9018. {$ifdef DEBUG_AOPTCPU}
  9019. SNoFlags: shortstring = ' so the flags aren''t modified';
  9020. {$else DEBUG_AOPTCPU}
  9021. SNoFlags = '';
  9022. {$endif DEBUG_AOPTCPU}
  9023. begin
  9024. Result:=false;
  9025. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9026. begin
  9027. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9028. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9029. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9030. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9031. GetNextInstruction(hp1, hp2) and
  9032. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9033. { Change from: To:
  9034. set(C) %reg j(~C) label
  9035. test %reg,%reg/cmp $0,%reg
  9036. je label
  9037. set(C) %reg j(C) label
  9038. test %reg,%reg/cmp $0,%reg
  9039. jne label
  9040. (Also do something similar with sete/setne instead of je/jne)
  9041. }
  9042. begin
  9043. { Before we do anything else, we need to check the instructions
  9044. in between SETcc and TEST to make sure they don't modify the
  9045. FLAGS register - if -O2 or under, there won't be any
  9046. instructions between SET and TEST }
  9047. TransferUsedRegs(TmpUsedRegs);
  9048. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9049. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9050. begin
  9051. next := p;
  9052. SetLength(InstrList, 0);
  9053. InstrMax := -1;
  9054. PotentialModified := False;
  9055. { Make a note of every instruction that modifies the FLAGS
  9056. register }
  9057. while GetNextInstruction(next, next) and (next <> hp1) do
  9058. begin
  9059. if next.typ <> ait_instruction then
  9060. { GetNextInstructionUsingReg should have returned False }
  9061. InternalError(2021051701);
  9062. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9063. begin
  9064. case taicpu(next).opcode of
  9065. A_SETcc,
  9066. A_CMOVcc,
  9067. A_Jcc:
  9068. begin
  9069. if PotentialModified then
  9070. { Not safe because the flags were modified earlier }
  9071. Exit
  9072. else
  9073. { Condition is the same as the initial SETcc, so this is safe
  9074. (don't add to instruction list though) }
  9075. Continue;
  9076. end;
  9077. A_ADD:
  9078. begin
  9079. if (taicpu(next).opsize = S_B) or
  9080. { LEA doesn't support 8-bit operands }
  9081. (taicpu(next).oper[1]^.typ <> top_reg) or
  9082. { Must write to a register }
  9083. (taicpu(next).oper[0]^.typ = top_ref) then
  9084. { Require a constant or a register }
  9085. Exit;
  9086. PotentialModified := True;
  9087. end;
  9088. A_SUB:
  9089. begin
  9090. if (taicpu(next).opsize = S_B) or
  9091. { LEA doesn't support 8-bit operands }
  9092. (taicpu(next).oper[1]^.typ <> top_reg) or
  9093. { Must write to a register }
  9094. (taicpu(next).oper[0]^.typ <> top_const) or
  9095. (taicpu(next).oper[0]^.val = $80000000) then
  9096. { Can't subtract a register with LEA - also
  9097. check that the value isn't -2^31, as this
  9098. can't be negated }
  9099. Exit;
  9100. PotentialModified := True;
  9101. end;
  9102. A_SAL,
  9103. A_SHL:
  9104. begin
  9105. if (taicpu(next).opsize = S_B) or
  9106. { LEA doesn't support 8-bit operands }
  9107. (taicpu(next).oper[1]^.typ <> top_reg) or
  9108. { Must write to a register }
  9109. (taicpu(next).oper[0]^.typ <> top_const) or
  9110. (taicpu(next).oper[0]^.val < 0) or
  9111. (taicpu(next).oper[0]^.val > 3) then
  9112. Exit;
  9113. PotentialModified := True;
  9114. end;
  9115. A_IMUL:
  9116. begin
  9117. if (taicpu(next).ops <> 3) or
  9118. (taicpu(next).oper[1]^.typ <> top_reg) or
  9119. { Must write to a register }
  9120. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9121. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9122. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9123. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9124. Exit
  9125. else
  9126. PotentialModified := True;
  9127. end;
  9128. else
  9129. { Don't know how to change this, so abort }
  9130. Exit;
  9131. end;
  9132. { Contains highest index (so instruction count - 1) }
  9133. Inc(InstrMax);
  9134. if InstrMax > High(InstrList) then
  9135. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9136. InstrList[InstrMax] := taicpu(next);
  9137. end;
  9138. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9139. end;
  9140. if not Assigned(next) or (next <> hp1) then
  9141. { It should be equal to hp1 }
  9142. InternalError(2021051702);
  9143. { Cycle through each instruction and check to see if we can
  9144. change them to versions that don't modify the flags }
  9145. if (InstrMax >= 0) then
  9146. begin
  9147. for Index := 0 to InstrMax do
  9148. case InstrList[Index].opcode of
  9149. A_ADD:
  9150. begin
  9151. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9152. InstrList[Index].opcode := A_LEA;
  9153. reference_reset(NewRef, 1, []);
  9154. NewRef.base := InstrList[Index].oper[1]^.reg;
  9155. if InstrList[Index].oper[0]^.typ = top_reg then
  9156. begin
  9157. NewRef.index := InstrList[Index].oper[0]^.reg;
  9158. NewRef.scalefactor := 1;
  9159. end
  9160. else
  9161. NewRef.offset := InstrList[Index].oper[0]^.val;
  9162. InstrList[Index].loadref(0, NewRef);
  9163. end;
  9164. A_SUB:
  9165. begin
  9166. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9167. InstrList[Index].opcode := A_LEA;
  9168. reference_reset(NewRef, 1, []);
  9169. NewRef.base := InstrList[Index].oper[1]^.reg;
  9170. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9171. InstrList[Index].loadref(0, NewRef);
  9172. end;
  9173. A_SHL,
  9174. A_SAL:
  9175. begin
  9176. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9177. InstrList[Index].opcode := A_LEA;
  9178. reference_reset(NewRef, 1, []);
  9179. NewRef.index := InstrList[Index].oper[1]^.reg;
  9180. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9181. InstrList[Index].loadref(0, NewRef);
  9182. end;
  9183. A_IMUL:
  9184. begin
  9185. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9186. InstrList[Index].opcode := A_LEA;
  9187. reference_reset(NewRef, 1, []);
  9188. NewRef.index := InstrList[Index].oper[1]^.reg;
  9189. case InstrList[Index].oper[0]^.val of
  9190. 2, 4, 8:
  9191. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9192. else {3, 5 and 9}
  9193. begin
  9194. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9195. NewRef.base := InstrList[Index].oper[1]^.reg;
  9196. end;
  9197. end;
  9198. InstrList[Index].loadref(0, NewRef);
  9199. end;
  9200. else
  9201. InternalError(2021051710);
  9202. end;
  9203. end;
  9204. { Mark the FLAGS register as used across this whole block }
  9205. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9206. end;
  9207. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9208. JumpC := taicpu(hp2).condition;
  9209. Unconditional := False;
  9210. if conditions_equal(JumpC, C_E) then
  9211. SetC := inverse_cond(taicpu(p).condition)
  9212. else if conditions_equal(JumpC, C_NE) then
  9213. SetC := taicpu(p).condition
  9214. else
  9215. { We've got something weird here (and inefficent) }
  9216. begin
  9217. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9218. SetC := C_NONE;
  9219. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9220. if condition_in(C_AE, JumpC) then
  9221. Unconditional := True
  9222. else
  9223. { Not sure what to do with this jump - drop out }
  9224. Exit;
  9225. end;
  9226. RemoveInstruction(hp1);
  9227. if Unconditional then
  9228. MakeUnconditional(taicpu(hp2))
  9229. else
  9230. begin
  9231. if SetC = C_NONE then
  9232. InternalError(2018061402);
  9233. taicpu(hp2).SetCondition(SetC);
  9234. end;
  9235. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9236. TmpUsedRegs }
  9237. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9238. begin
  9239. RemoveCurrentp(p, hp2);
  9240. if taicpu(hp2).opcode = A_SETcc then
  9241. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9242. else
  9243. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9244. end
  9245. else
  9246. if taicpu(hp2).opcode = A_SETcc then
  9247. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9248. else
  9249. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9250. Result := True;
  9251. end
  9252. else if
  9253. { Make sure the instructions are adjacent }
  9254. (
  9255. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9256. GetNextInstruction(p, hp1)
  9257. ) and
  9258. MatchInstruction(hp1, A_MOV, [S_B]) and
  9259. { Writing to memory is allowed }
  9260. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9261. begin
  9262. {
  9263. Watch out for sequences such as:
  9264. set(c)b %regb
  9265. movb %regb,(ref)
  9266. movb $0,1(ref)
  9267. movb $0,2(ref)
  9268. movb $0,3(ref)
  9269. Much more efficient to turn it into:
  9270. movl $0,%regl
  9271. set(c)b %regb
  9272. movl %regl,(ref)
  9273. Or:
  9274. set(c)b %regb
  9275. movzbl %regb,%regl
  9276. movl %regl,(ref)
  9277. }
  9278. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9279. GetNextInstruction(hp1, hp2) and
  9280. MatchInstruction(hp2, A_MOV, [S_B]) and
  9281. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9282. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9283. begin
  9284. { Don't do anything else except set Result to True }
  9285. end
  9286. else
  9287. begin
  9288. if taicpu(p).oper[0]^.typ = top_reg then
  9289. begin
  9290. TransferUsedRegs(TmpUsedRegs);
  9291. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9292. end;
  9293. { If it's not a register, it's a memory address }
  9294. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9295. begin
  9296. { Even if the register is still in use, we can minimise the
  9297. pipeline stall by changing the MOV into another SETcc. }
  9298. taicpu(hp1).opcode := A_SETcc;
  9299. taicpu(hp1).condition := taicpu(p).condition;
  9300. if taicpu(hp1).oper[1]^.typ = top_ref then
  9301. begin
  9302. { Swapping the operand pointers like this is probably a
  9303. bit naughty, but it is far faster than using loadoper
  9304. to transfer the reference from oper[1] to oper[0] if
  9305. you take into account the extra procedure calls and
  9306. the memory allocation and deallocation required }
  9307. OperPtr := taicpu(hp1).oper[1];
  9308. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9309. taicpu(hp1).oper[0] := OperPtr;
  9310. end
  9311. else
  9312. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9313. taicpu(hp1).clearop(1);
  9314. taicpu(hp1).ops := 1;
  9315. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9316. end
  9317. else
  9318. begin
  9319. if taicpu(hp1).oper[1]^.typ = top_reg then
  9320. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9321. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9322. RemoveInstruction(hp1);
  9323. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9324. end
  9325. end;
  9326. Result := True;
  9327. end;
  9328. end;
  9329. end;
  9330. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9331. var
  9332. hp1: tai;
  9333. Count: Integer;
  9334. OrigLabel: TAsmLabel;
  9335. begin
  9336. result := False;
  9337. { Sometimes, the optimisations below can permit this }
  9338. RemoveDeadCodeAfterJump(p);
  9339. 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
  9340. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9341. begin
  9342. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9343. { Also a side-effect of optimisations }
  9344. if CollapseZeroDistJump(p, OrigLabel) then
  9345. begin
  9346. Result := True;
  9347. Exit;
  9348. end;
  9349. hp1 := GetLabelWithSym(OrigLabel);
  9350. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9351. begin
  9352. case taicpu(hp1).opcode of
  9353. A_RET:
  9354. {
  9355. change
  9356. jmp .L1
  9357. ...
  9358. .L1:
  9359. ret
  9360. into
  9361. ret
  9362. }
  9363. begin
  9364. ConvertJumpToRET(p, hp1);
  9365. result:=true;
  9366. end;
  9367. { Check any kind of direct assignment instruction }
  9368. A_MOV,
  9369. A_MOVD,
  9370. A_MOVQ,
  9371. A_MOVSX,
  9372. {$ifdef x86_64}
  9373. A_MOVSXD,
  9374. {$endif x86_64}
  9375. A_MOVZX,
  9376. A_MOVAPS,
  9377. A_MOVUPS,
  9378. A_MOVSD,
  9379. A_MOVAPD,
  9380. A_MOVUPD,
  9381. A_MOVDQA,
  9382. A_MOVDQU,
  9383. A_VMOVSS,
  9384. A_VMOVAPS,
  9385. A_VMOVUPS,
  9386. A_VMOVSD,
  9387. A_VMOVAPD,
  9388. A_VMOVUPD,
  9389. A_VMOVDQA,
  9390. A_VMOVDQU:
  9391. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9392. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9393. begin
  9394. Result := True;
  9395. Exit;
  9396. end;
  9397. else
  9398. ;
  9399. end;
  9400. end;
  9401. end;
  9402. end;
  9403. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9404. begin
  9405. CanBeCMOV:=assigned(p) and
  9406. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9407. { we can't use cmov ref,reg because
  9408. ref could be nil and cmov still throws an exception
  9409. if ref=nil but the mov isn't done (FK)
  9410. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9411. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9412. }
  9413. (taicpu(p).oper[1]^.typ = top_reg) and
  9414. (
  9415. (taicpu(p).oper[0]^.typ = top_reg) or
  9416. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9417. it is not expected that this can cause a seg. violation }
  9418. (
  9419. (taicpu(p).oper[0]^.typ = top_ref) and
  9420. IsRefSafe(taicpu(p).oper[0]^.ref)
  9421. )
  9422. );
  9423. end;
  9424. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9425. var
  9426. hp1,hp2: tai;
  9427. {$ifndef i8086}
  9428. hp3,hp4,hpmov2, hp5: tai;
  9429. l : Longint;
  9430. condition : TAsmCond;
  9431. {$endif i8086}
  9432. carryadd_opcode : TAsmOp;
  9433. symbol: TAsmSymbol;
  9434. increg, tmpreg: TRegister;
  9435. begin
  9436. result:=false;
  9437. if GetNextInstruction(p,hp1) then
  9438. begin
  9439. if (hp1.typ=ait_label) then
  9440. begin
  9441. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9442. Exit;
  9443. end
  9444. else if (hp1.typ<>ait_instruction) then
  9445. Exit;
  9446. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9447. if (
  9448. (
  9449. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9450. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9451. (Taicpu(hp1).oper[0]^.val=1)
  9452. ) or
  9453. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9454. ) and
  9455. GetNextInstruction(hp1,hp2) and
  9456. SkipAligns(hp2, hp2) and
  9457. (hp2.typ = ait_label) and
  9458. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9459. { jb @@1 cmc
  9460. inc/dec operand --> adc/sbb operand,0
  9461. @@1:
  9462. ... and ...
  9463. jnb @@1
  9464. inc/dec operand --> adc/sbb operand,0
  9465. @@1: }
  9466. begin
  9467. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9468. begin
  9469. case taicpu(hp1).opcode of
  9470. A_INC,
  9471. A_ADD:
  9472. carryadd_opcode:=A_ADC;
  9473. A_DEC,
  9474. A_SUB:
  9475. carryadd_opcode:=A_SBB;
  9476. else
  9477. InternalError(2021011001);
  9478. end;
  9479. Taicpu(p).clearop(0);
  9480. Taicpu(p).ops:=0;
  9481. Taicpu(p).is_jmp:=false;
  9482. Taicpu(p).opcode:=A_CMC;
  9483. Taicpu(p).condition:=C_NONE;
  9484. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9485. Taicpu(hp1).ops:=2;
  9486. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9487. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9488. else
  9489. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9490. Taicpu(hp1).loadconst(0,0);
  9491. Taicpu(hp1).opcode:=carryadd_opcode;
  9492. result:=true;
  9493. exit;
  9494. end
  9495. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9496. begin
  9497. case taicpu(hp1).opcode of
  9498. A_INC,
  9499. A_ADD:
  9500. carryadd_opcode:=A_ADC;
  9501. A_DEC,
  9502. A_SUB:
  9503. carryadd_opcode:=A_SBB;
  9504. else
  9505. InternalError(2021011002);
  9506. end;
  9507. Taicpu(hp1).ops:=2;
  9508. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9509. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9510. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9511. else
  9512. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9513. Taicpu(hp1).loadconst(0,0);
  9514. Taicpu(hp1).opcode:=carryadd_opcode;
  9515. RemoveCurrentP(p, hp1);
  9516. result:=true;
  9517. exit;
  9518. end
  9519. {
  9520. jcc @@1 setcc tmpreg
  9521. inc/dec/add/sub operand -> (movzx tmpreg)
  9522. @@1: add/sub tmpreg,operand
  9523. While this increases code size slightly, it makes the code much faster if the
  9524. jump is unpredictable
  9525. }
  9526. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9527. begin
  9528. { search for an available register which is volatile }
  9529. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9530. if increg <> NR_NO then
  9531. begin
  9532. { We don't need to check if tmpreg is in hp1 or not, because
  9533. it will be marked as in use at p (if not, this is
  9534. indictive of a compiler bug). }
  9535. TAsmLabel(symbol).decrefs;
  9536. Taicpu(p).clearop(0);
  9537. Taicpu(p).ops:=1;
  9538. Taicpu(p).is_jmp:=false;
  9539. Taicpu(p).opcode:=A_SETcc;
  9540. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9541. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9542. Taicpu(p).loadreg(0,increg);
  9543. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9544. begin
  9545. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9546. R_SUBW:
  9547. begin
  9548. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9549. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9550. end;
  9551. R_SUBD:
  9552. begin
  9553. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9554. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9555. end;
  9556. {$ifdef x86_64}
  9557. R_SUBQ:
  9558. begin
  9559. { MOVZX doesn't have a 64-bit variant, because
  9560. the 32-bit version implicitly zeroes the
  9561. upper 32-bits of the destination register }
  9562. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9563. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9564. setsubreg(tmpreg, R_SUBQ);
  9565. end;
  9566. {$endif x86_64}
  9567. else
  9568. Internalerror(2020030601);
  9569. end;
  9570. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9571. asml.InsertAfter(hp2,p);
  9572. end
  9573. else
  9574. tmpreg := increg;
  9575. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9576. begin
  9577. Taicpu(hp1).ops:=2;
  9578. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9579. end;
  9580. Taicpu(hp1).loadreg(0,tmpreg);
  9581. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9582. Result := True;
  9583. { p is no longer a Jcc instruction, so exit }
  9584. Exit;
  9585. end;
  9586. end;
  9587. end;
  9588. { Detect the following:
  9589. jmp<cond> @Lbl1
  9590. jmp @Lbl2
  9591. ...
  9592. @Lbl1:
  9593. ret
  9594. Change to:
  9595. jmp<inv_cond> @Lbl2
  9596. ret
  9597. }
  9598. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9599. begin
  9600. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9601. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9602. MatchInstruction(hp2,A_RET,[S_NO]) then
  9603. begin
  9604. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9605. { Change label address to that of the unconditional jump }
  9606. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9607. TAsmLabel(symbol).DecRefs;
  9608. taicpu(hp1).opcode := A_RET;
  9609. taicpu(hp1).is_jmp := false;
  9610. taicpu(hp1).ops := taicpu(hp2).ops;
  9611. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9612. case taicpu(hp2).ops of
  9613. 0:
  9614. taicpu(hp1).clearop(0);
  9615. 1:
  9616. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9617. else
  9618. internalerror(2016041302);
  9619. end;
  9620. end;
  9621. {$ifndef i8086}
  9622. end
  9623. {
  9624. convert
  9625. j<c> .L1
  9626. mov 1,reg
  9627. jmp .L2
  9628. .L1
  9629. mov 0,reg
  9630. .L2
  9631. into
  9632. mov 0,reg
  9633. set<not(c)> reg
  9634. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9635. would destroy the flag contents
  9636. }
  9637. else if MatchInstruction(hp1,A_MOV,[]) and
  9638. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9639. {$ifdef i386}
  9640. (
  9641. { Under i386, ESI, EDI, EBP and ESP
  9642. don't have an 8-bit representation }
  9643. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9644. ) and
  9645. {$endif i386}
  9646. (taicpu(hp1).oper[0]^.val=1) and
  9647. GetNextInstruction(hp1,hp2) and
  9648. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9649. GetNextInstruction(hp2,hp3) and
  9650. { skip align }
  9651. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9652. (hp3.typ=ait_label) and
  9653. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9654. (tai_label(hp3).labsym.getrefs=1) and
  9655. GetNextInstruction(hp3,hp4) and
  9656. MatchInstruction(hp4,A_MOV,[]) and
  9657. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9658. (taicpu(hp4).oper[0]^.val=0) and
  9659. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9660. GetNextInstruction(hp4,hp5) and
  9661. (hp5.typ=ait_label) and
  9662. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9663. (tai_label(hp5).labsym.getrefs=1) then
  9664. begin
  9665. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9666. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9667. { remove last label }
  9668. RemoveInstruction(hp5);
  9669. { remove second label }
  9670. RemoveInstruction(hp3);
  9671. { if align is present remove it }
  9672. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9673. RemoveInstruction(hp3);
  9674. { remove jmp }
  9675. RemoveInstruction(hp2);
  9676. if taicpu(hp1).opsize=S_B then
  9677. RemoveInstruction(hp1)
  9678. else
  9679. taicpu(hp1).loadconst(0,0);
  9680. taicpu(hp4).opcode:=A_SETcc;
  9681. taicpu(hp4).opsize:=S_B;
  9682. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9683. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9684. taicpu(hp4).opercnt:=1;
  9685. taicpu(hp4).ops:=1;
  9686. taicpu(hp4).freeop(1);
  9687. RemoveCurrentP(p);
  9688. Result:=true;
  9689. exit;
  9690. end
  9691. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9692. begin
  9693. { check for
  9694. jCC xxx
  9695. <several movs>
  9696. xxx:
  9697. Also spot:
  9698. Jcc xxx
  9699. <several movs>
  9700. jmp xxx
  9701. Change to:
  9702. <several cmovs with inverted condition>
  9703. jmp xxx
  9704. }
  9705. l:=0;
  9706. while assigned(hp1) and
  9707. CanBeCMOV(hp1) and
  9708. { stop on labels }
  9709. not(hp1.typ=ait_label) do
  9710. begin
  9711. inc(l);
  9712. hp5 := hp1;
  9713. GetNextInstruction(hp1,hp1);
  9714. end;
  9715. if assigned(hp1) then
  9716. begin
  9717. TransferUsedRegs(TmpUsedRegs);
  9718. if (
  9719. MatchInstruction(hp1, A_JMP, []) and
  9720. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9721. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9722. ) or
  9723. FindLabel(tasmlabel(symbol),hp1) then
  9724. begin
  9725. if (l<=4) and (l>0) then
  9726. begin
  9727. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9728. condition:=inverse_cond(taicpu(p).condition);
  9729. UpdateUsedRegs(tai(p.next));
  9730. GetNextInstruction(p,hp1);
  9731. repeat
  9732. if not Assigned(hp1) then
  9733. InternalError(2018062900);
  9734. taicpu(hp1).opcode:=A_CMOVcc;
  9735. taicpu(hp1).condition:=condition;
  9736. UpdateUsedRegs(tai(hp1.next));
  9737. GetNextInstruction(hp1,hp1);
  9738. until not(CanBeCMOV(hp1));
  9739. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9740. hp2 := hp1;
  9741. repeat
  9742. if not Assigned(hp2) then
  9743. InternalError(2018062910);
  9744. case hp2.typ of
  9745. ait_label:
  9746. { What we expected - break out of the loop (it won't be a dead label at the top of
  9747. a cluster because that was optimised at an earlier stage) }
  9748. Break;
  9749. ait_align:
  9750. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9751. begin
  9752. hp2 := tai(hp2.Next);
  9753. Continue;
  9754. end;
  9755. ait_instruction:
  9756. begin
  9757. if taicpu(hp2).opcode<>A_JMP then
  9758. InternalError(2018062912);
  9759. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9760. Break;
  9761. end
  9762. else
  9763. begin
  9764. { Might be a comment or temporary allocation entry }
  9765. if not (hp2.typ in SkipInstr) then
  9766. InternalError(2018062911);
  9767. hp2 := tai(hp2.Next);
  9768. Continue;
  9769. end;
  9770. end;
  9771. until False;
  9772. { Now we can safely decrement the reference count }
  9773. tasmlabel(symbol).decrefs;
  9774. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9775. { Remove the original jump }
  9776. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9777. if hp2.typ=ait_instruction then
  9778. begin
  9779. p:=hp2;
  9780. Result:=True;
  9781. end
  9782. else
  9783. begin
  9784. UpdateUsedRegs(tai(hp2.next));
  9785. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9786. { Remove the label if this is its final reference }
  9787. if (tasmlabel(symbol).getrefs=0) then
  9788. StripLabelFast(hp1);
  9789. end;
  9790. exit;
  9791. end;
  9792. end
  9793. else
  9794. begin
  9795. { check further for
  9796. jCC xxx
  9797. <several movs 1>
  9798. jmp yyy
  9799. xxx:
  9800. <several movs 2>
  9801. yyy:
  9802. }
  9803. { hp2 points to jmp yyy }
  9804. hp2:=hp1;
  9805. { skip hp1 to xxx (or an align right before it) }
  9806. GetNextInstruction(hp1, hp1);
  9807. if assigned(hp2) and
  9808. assigned(hp1) and
  9809. (l<=3) and
  9810. (hp2.typ=ait_instruction) and
  9811. (taicpu(hp2).is_jmp) and
  9812. (taicpu(hp2).condition=C_None) and
  9813. { real label and jump, no further references to the
  9814. label are allowed }
  9815. (tasmlabel(symbol).getrefs=1) and
  9816. FindLabel(tasmlabel(symbol),hp1) then
  9817. begin
  9818. l:=0;
  9819. { skip hp1 to <several moves 2> }
  9820. if (hp1.typ = ait_align) then
  9821. GetNextInstruction(hp1, hp1);
  9822. GetNextInstruction(hp1, hpmov2);
  9823. hp1 := hpmov2;
  9824. while assigned(hp1) and
  9825. CanBeCMOV(hp1) do
  9826. begin
  9827. inc(l);
  9828. hp5 := hp1;
  9829. GetNextInstruction(hp1, hp1);
  9830. end;
  9831. { hp1 points to yyy (or an align right before it) }
  9832. hp3 := hp1;
  9833. if assigned(hp1) and
  9834. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9835. begin
  9836. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9837. condition:=inverse_cond(taicpu(p).condition);
  9838. UpdateUsedRegs(tai(p.next));
  9839. GetNextInstruction(p,hp1);
  9840. repeat
  9841. taicpu(hp1).opcode:=A_CMOVcc;
  9842. taicpu(hp1).condition:=condition;
  9843. UpdateUsedRegs(tai(hp1.next));
  9844. GetNextInstruction(hp1,hp1);
  9845. until not(assigned(hp1)) or
  9846. not(CanBeCMOV(hp1));
  9847. condition:=inverse_cond(condition);
  9848. if GetLastInstruction(hpmov2,hp1) then
  9849. UpdateUsedRegs(tai(hp1.next));
  9850. hp1 := hpmov2;
  9851. { hp1 is now at <several movs 2> }
  9852. while Assigned(hp1) and CanBeCMOV(hp1) do
  9853. begin
  9854. taicpu(hp1).opcode:=A_CMOVcc;
  9855. taicpu(hp1).condition:=condition;
  9856. UpdateUsedRegs(tai(hp1.next));
  9857. GetNextInstruction(hp1,hp1);
  9858. end;
  9859. hp1 := p;
  9860. { Get first instruction after label }
  9861. UpdateUsedRegs(tai(hp3.next));
  9862. GetNextInstruction(hp3, p);
  9863. if assigned(p) and (hp3.typ = ait_align) then
  9864. GetNextInstruction(p, p);
  9865. { Don't dereference yet, as doing so will cause
  9866. GetNextInstruction to skip the label and
  9867. optional align marker. [Kit] }
  9868. GetNextInstruction(hp2, hp4);
  9869. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9870. { remove jCC }
  9871. RemoveInstruction(hp1);
  9872. { Now we can safely decrement it }
  9873. tasmlabel(symbol).decrefs;
  9874. { Remove label xxx (it will have a ref of zero due to the initial check }
  9875. StripLabelFast(hp4);
  9876. { remove jmp }
  9877. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9878. RemoveInstruction(hp2);
  9879. { As before, now we can safely decrement it }
  9880. tasmlabel(symbol).decrefs;
  9881. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9882. if tasmlabel(symbol).getrefs = 0 then
  9883. StripLabelFast(hp3);
  9884. if Assigned(p) then
  9885. result:=true;
  9886. exit;
  9887. end;
  9888. end;
  9889. end;
  9890. end;
  9891. {$endif i8086}
  9892. end;
  9893. end;
  9894. end;
  9895. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9896. var
  9897. hp1,hp2,hp3: tai;
  9898. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9899. NewSize: TOpSize;
  9900. NewRegSize: TSubRegister;
  9901. Limit: TCgInt;
  9902. SwapOper: POper;
  9903. begin
  9904. result:=false;
  9905. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9906. GetNextInstruction(p,hp1) and
  9907. (hp1.typ = ait_instruction);
  9908. if reg_and_hp1_is_instr and
  9909. (
  9910. (taicpu(hp1).opcode <> A_LEA) or
  9911. { If the LEA instruction can be converted into an arithmetic instruction,
  9912. it may be possible to then fold it. }
  9913. (
  9914. { If the flags register is in use, don't change the instruction
  9915. to an ADD otherwise this will scramble the flags. [Kit] }
  9916. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9917. ConvertLEA(taicpu(hp1))
  9918. )
  9919. ) and
  9920. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9921. GetNextInstruction(hp1,hp2) and
  9922. MatchInstruction(hp2,A_MOV,[]) and
  9923. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9924. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9925. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9926. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9927. {$ifdef i386}
  9928. { not all registers have byte size sub registers on i386 }
  9929. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9930. {$endif i386}
  9931. (((taicpu(hp1).ops=2) and
  9932. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9933. ((taicpu(hp1).ops=1) and
  9934. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9935. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9936. begin
  9937. { change movsX/movzX reg/ref, reg2
  9938. add/sub/or/... reg3/$const, reg2
  9939. mov reg2 reg/ref
  9940. to add/sub/or/... reg3/$const, reg/ref }
  9941. { by example:
  9942. movswl %si,%eax movswl %si,%eax p
  9943. decl %eax addl %edx,%eax hp1
  9944. movw %ax,%si movw %ax,%si hp2
  9945. ->
  9946. movswl %si,%eax movswl %si,%eax p
  9947. decw %eax addw %edx,%eax hp1
  9948. movw %ax,%si movw %ax,%si hp2
  9949. }
  9950. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9951. {
  9952. ->
  9953. movswl %si,%eax movswl %si,%eax p
  9954. decw %si addw %dx,%si hp1
  9955. movw %ax,%si movw %ax,%si hp2
  9956. }
  9957. case taicpu(hp1).ops of
  9958. 1:
  9959. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9960. 2:
  9961. begin
  9962. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9963. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9964. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9965. end;
  9966. else
  9967. internalerror(2008042702);
  9968. end;
  9969. {
  9970. ->
  9971. decw %si addw %dx,%si p
  9972. }
  9973. DebugMsg(SPeepholeOptimization + 'var3',p);
  9974. RemoveCurrentP(p, hp1);
  9975. RemoveInstruction(hp2);
  9976. Result := True;
  9977. Exit;
  9978. end;
  9979. if reg_and_hp1_is_instr and
  9980. (taicpu(hp1).opcode = A_MOV) and
  9981. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9982. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9983. {$ifdef x86_64}
  9984. { check for implicit extension to 64 bit }
  9985. or
  9986. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9987. (taicpu(hp1).opsize=S_Q) and
  9988. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9989. )
  9990. {$endif x86_64}
  9991. )
  9992. then
  9993. begin
  9994. { change
  9995. movx %reg1,%reg2
  9996. mov %reg2,%reg3
  9997. dealloc %reg2
  9998. into
  9999. movx %reg,%reg3
  10000. }
  10001. TransferUsedRegs(TmpUsedRegs);
  10002. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10003. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10004. begin
  10005. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10006. {$ifdef x86_64}
  10007. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10008. (taicpu(hp1).opsize=S_Q) then
  10009. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10010. else
  10011. {$endif x86_64}
  10012. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10013. RemoveInstruction(hp1);
  10014. Result := True;
  10015. Exit;
  10016. end;
  10017. end;
  10018. if reg_and_hp1_is_instr and
  10019. ((taicpu(hp1).opcode=A_MOV) or
  10020. (taicpu(hp1).opcode=A_ADD) or
  10021. (taicpu(hp1).opcode=A_SUB) or
  10022. (taicpu(hp1).opcode=A_CMP) or
  10023. (taicpu(hp1).opcode=A_OR) or
  10024. (taicpu(hp1).opcode=A_XOR) or
  10025. (taicpu(hp1).opcode=A_AND)
  10026. ) and
  10027. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10028. begin
  10029. AndTest := (taicpu(hp1).opcode=A_AND) and
  10030. GetNextInstruction(hp1, hp2) and
  10031. (hp2.typ = ait_instruction) and
  10032. (
  10033. (
  10034. (taicpu(hp2).opcode=A_TEST) and
  10035. (
  10036. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10037. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10038. (
  10039. { If the AND and TEST instructions share a constant, this is also valid }
  10040. (taicpu(hp1).oper[0]^.typ = top_const) and
  10041. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10042. )
  10043. ) and
  10044. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10045. ) or
  10046. (
  10047. (taicpu(hp2).opcode=A_CMP) and
  10048. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10049. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10050. )
  10051. );
  10052. { change
  10053. movx (oper),%reg2
  10054. and $x,%reg2
  10055. test %reg2,%reg2
  10056. dealloc %reg2
  10057. into
  10058. op %reg1,%reg3
  10059. if the second op accesses only the bits stored in reg1
  10060. }
  10061. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10062. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10063. (taicpu(hp1).oper[0]^.typ = top_const) and
  10064. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10065. AndTest then
  10066. begin
  10067. { Check if the AND constant is in range }
  10068. case taicpu(p).opsize of
  10069. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10070. begin
  10071. NewSize := S_B;
  10072. Limit := $FF;
  10073. end;
  10074. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10075. begin
  10076. NewSize := S_W;
  10077. Limit := $FFFF;
  10078. end;
  10079. {$ifdef x86_64}
  10080. S_LQ:
  10081. begin
  10082. NewSize := S_L;
  10083. Limit := $FFFFFFFF;
  10084. end;
  10085. {$endif x86_64}
  10086. else
  10087. InternalError(2021120303);
  10088. end;
  10089. if (
  10090. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10091. { Check for negative operands }
  10092. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10093. ) and
  10094. GetNextInstruction(hp2,hp3) and
  10095. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10096. (taicpu(hp3).condition in [C_E,C_NE]) then
  10097. begin
  10098. TransferUsedRegs(TmpUsedRegs);
  10099. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10100. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10101. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10102. begin
  10103. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10104. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10105. taicpu(hp1).opcode := A_TEST;
  10106. taicpu(hp1).opsize := NewSize;
  10107. RemoveInstruction(hp2);
  10108. RemoveCurrentP(p, hp1);
  10109. Result:=true;
  10110. exit;
  10111. end;
  10112. end;
  10113. end;
  10114. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10115. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10116. (taicpu(hp1).opsize=S_B)) or
  10117. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10118. (taicpu(hp1).opsize=S_W))
  10119. {$ifdef x86_64}
  10120. or ((taicpu(p).opsize=S_LQ) and
  10121. (taicpu(hp1).opsize=S_L))
  10122. {$endif x86_64}
  10123. ) and
  10124. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10125. begin
  10126. { change
  10127. movx %reg1,%reg2
  10128. op %reg2,%reg3
  10129. dealloc %reg2
  10130. into
  10131. op %reg1,%reg3
  10132. if the second op accesses only the bits stored in reg1
  10133. }
  10134. TransferUsedRegs(TmpUsedRegs);
  10135. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10136. if AndTest then
  10137. begin
  10138. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10139. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10140. end
  10141. else
  10142. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10143. if not RegUsed then
  10144. begin
  10145. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10146. if taicpu(p).oper[0]^.typ=top_reg then
  10147. begin
  10148. case taicpu(hp1).opsize of
  10149. S_B:
  10150. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10151. S_W:
  10152. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10153. S_L:
  10154. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10155. else
  10156. Internalerror(2020102301);
  10157. end;
  10158. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10159. end
  10160. else
  10161. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10162. RemoveCurrentP(p);
  10163. if AndTest then
  10164. RemoveInstruction(hp2);
  10165. result:=true;
  10166. exit;
  10167. end;
  10168. end
  10169. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10170. (
  10171. { Bitwise operations only }
  10172. (taicpu(hp1).opcode=A_AND) or
  10173. (taicpu(hp1).opcode=A_TEST) or
  10174. (
  10175. (taicpu(hp1).oper[0]^.typ = top_const) and
  10176. (
  10177. (taicpu(hp1).opcode=A_OR) or
  10178. (taicpu(hp1).opcode=A_XOR)
  10179. )
  10180. )
  10181. ) and
  10182. (
  10183. (taicpu(hp1).oper[0]^.typ = top_const) or
  10184. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10185. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10186. ) then
  10187. begin
  10188. { change
  10189. movx %reg2,%reg2
  10190. op const,%reg2
  10191. into
  10192. op const,%reg2 (smaller version)
  10193. movx %reg2,%reg2
  10194. also change
  10195. movx %reg1,%reg2
  10196. and/test (oper),%reg2
  10197. dealloc %reg2
  10198. into
  10199. and/test (oper),%reg1
  10200. }
  10201. case taicpu(p).opsize of
  10202. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10203. begin
  10204. NewSize := S_B;
  10205. NewRegSize := R_SUBL;
  10206. Limit := $FF;
  10207. end;
  10208. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10209. begin
  10210. NewSize := S_W;
  10211. NewRegSize := R_SUBW;
  10212. Limit := $FFFF;
  10213. end;
  10214. {$ifdef x86_64}
  10215. S_LQ:
  10216. begin
  10217. NewSize := S_L;
  10218. NewRegSize := R_SUBD;
  10219. Limit := $FFFFFFFF;
  10220. end;
  10221. {$endif x86_64}
  10222. else
  10223. Internalerror(2021120302);
  10224. end;
  10225. TransferUsedRegs(TmpUsedRegs);
  10226. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10227. if AndTest then
  10228. begin
  10229. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10230. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10231. end
  10232. else
  10233. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10234. if
  10235. (
  10236. (taicpu(p).opcode = A_MOVZX) and
  10237. (
  10238. (taicpu(hp1).opcode=A_AND) or
  10239. (taicpu(hp1).opcode=A_TEST)
  10240. ) and
  10241. not (
  10242. { If both are references, then the final instruction will have
  10243. both operands as references, which is not allowed }
  10244. (taicpu(p).oper[0]^.typ = top_ref) and
  10245. (taicpu(hp1).oper[0]^.typ = top_ref)
  10246. ) and
  10247. not RegUsed
  10248. ) or
  10249. (
  10250. (
  10251. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10252. not RegUsed
  10253. ) and
  10254. (taicpu(p).oper[0]^.typ = top_reg) and
  10255. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10256. (taicpu(hp1).oper[0]^.typ = top_const) and
  10257. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10258. ) then
  10259. begin
  10260. {$if defined(i386) or defined(i8086)}
  10261. { If the target size is 8-bit, make sure we can actually encode it }
  10262. 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
  10263. Exit;
  10264. {$endif i386 or i8086}
  10265. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10266. taicpu(hp1).opsize := NewSize;
  10267. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10268. if AndTest then
  10269. begin
  10270. RemoveInstruction(hp2);
  10271. if not RegUsed then
  10272. begin
  10273. taicpu(hp1).opcode := A_TEST;
  10274. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10275. begin
  10276. { Make sure the reference is the second operand }
  10277. SwapOper := taicpu(hp1).oper[0];
  10278. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10279. taicpu(hp1).oper[1] := SwapOper;
  10280. end;
  10281. end;
  10282. end;
  10283. case taicpu(hp1).oper[0]^.typ of
  10284. top_reg:
  10285. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10286. top_const:
  10287. { For the AND/TEST case }
  10288. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10289. else
  10290. ;
  10291. end;
  10292. if RegUsed then
  10293. begin
  10294. AsmL.Remove(p);
  10295. AsmL.InsertAfter(p, hp1);
  10296. p := hp1;
  10297. end
  10298. else
  10299. RemoveCurrentP(p, hp1);
  10300. result:=true;
  10301. exit;
  10302. end;
  10303. end;
  10304. end;
  10305. if reg_and_hp1_is_instr and
  10306. (taicpu(p).oper[0]^.typ = top_reg) and
  10307. (
  10308. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10309. ) and
  10310. (taicpu(hp1).oper[0]^.typ = top_const) and
  10311. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10312. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10313. { Minimum shift value allowed is the bit difference between the sizes }
  10314. (taicpu(hp1).oper[0]^.val >=
  10315. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10316. 8 * (
  10317. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10318. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10319. )
  10320. ) then
  10321. begin
  10322. { For:
  10323. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10324. shl/sal ##, %reg1
  10325. Remove the movsx/movzx instruction if the shift overwrites the
  10326. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10327. }
  10328. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10329. RemoveCurrentP(p, hp1);
  10330. Result := True;
  10331. Exit;
  10332. end
  10333. else if reg_and_hp1_is_instr and
  10334. (taicpu(p).oper[0]^.typ = top_reg) and
  10335. (
  10336. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10337. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10338. ) and
  10339. (taicpu(hp1).oper[0]^.typ = top_const) and
  10340. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10341. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10342. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10343. (taicpu(hp1).oper[0]^.val <
  10344. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10345. 8 * (
  10346. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10347. )
  10348. ) then
  10349. begin
  10350. { For:
  10351. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10352. sar ##, %reg1 shr ##, %reg1
  10353. Move the shift to before the movx instruction if the shift value
  10354. is not too large.
  10355. }
  10356. asml.Remove(hp1);
  10357. asml.InsertBefore(hp1, p);
  10358. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10359. case taicpu(p).opsize of
  10360. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10361. taicpu(hp1).opsize := S_B;
  10362. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10363. taicpu(hp1).opsize := S_W;
  10364. {$ifdef x86_64}
  10365. S_LQ:
  10366. taicpu(hp1).opsize := S_L;
  10367. {$endif}
  10368. else
  10369. InternalError(2020112401);
  10370. end;
  10371. if (taicpu(hp1).opcode = A_SHR) then
  10372. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10373. else
  10374. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10375. Result := True;
  10376. end;
  10377. if reg_and_hp1_is_instr and
  10378. (taicpu(p).oper[0]^.typ = top_reg) and
  10379. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10380. (
  10381. (taicpu(hp1).opcode = taicpu(p).opcode)
  10382. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10383. {$ifdef x86_64}
  10384. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10385. {$endif x86_64}
  10386. ) then
  10387. begin
  10388. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10389. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10390. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10391. begin
  10392. {
  10393. For example:
  10394. movzbw %al,%ax
  10395. movzwl %ax,%eax
  10396. Compress into:
  10397. movzbl %al,%eax
  10398. }
  10399. RegUsed := False;
  10400. case taicpu(p).opsize of
  10401. S_BW:
  10402. case taicpu(hp1).opsize of
  10403. S_WL:
  10404. begin
  10405. taicpu(p).opsize := S_BL;
  10406. RegUsed := True;
  10407. end;
  10408. {$ifdef x86_64}
  10409. S_WQ:
  10410. begin
  10411. if taicpu(p).opcode = A_MOVZX then
  10412. begin
  10413. taicpu(p).opsize := S_BL;
  10414. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10415. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10416. end
  10417. else
  10418. taicpu(p).opsize := S_BQ;
  10419. RegUsed := True;
  10420. end;
  10421. {$endif x86_64}
  10422. else
  10423. ;
  10424. end;
  10425. {$ifdef x86_64}
  10426. S_BL:
  10427. case taicpu(hp1).opsize of
  10428. S_LQ:
  10429. begin
  10430. if taicpu(p).opcode = A_MOVZX then
  10431. begin
  10432. taicpu(p).opsize := S_BL;
  10433. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10434. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10435. end
  10436. else
  10437. taicpu(p).opsize := S_BQ;
  10438. RegUsed := True;
  10439. end;
  10440. else
  10441. ;
  10442. end;
  10443. S_WL:
  10444. case taicpu(hp1).opsize of
  10445. S_LQ:
  10446. begin
  10447. if taicpu(p).opcode = A_MOVZX then
  10448. begin
  10449. taicpu(p).opsize := S_WL;
  10450. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10451. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10452. end
  10453. else
  10454. taicpu(p).opsize := S_WQ;
  10455. RegUsed := True;
  10456. end;
  10457. else
  10458. ;
  10459. end;
  10460. {$endif x86_64}
  10461. else
  10462. ;
  10463. end;
  10464. if RegUsed then
  10465. begin
  10466. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10467. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10468. RemoveInstruction(hp1);
  10469. Result := True;
  10470. Exit;
  10471. end;
  10472. end;
  10473. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10474. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10475. GetNextInstruction(hp1, hp2) and
  10476. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10477. (
  10478. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10479. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10480. {$ifdef x86_64}
  10481. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10482. {$endif x86_64}
  10483. ) and
  10484. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10485. (
  10486. (
  10487. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10488. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10489. ) or
  10490. (
  10491. { Only allow the operands in reverse order for TEST instructions }
  10492. (taicpu(hp2).opcode = A_TEST) and
  10493. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10494. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10495. )
  10496. ) then
  10497. begin
  10498. {
  10499. For example:
  10500. movzbl %al,%eax
  10501. movzbl (ref),%edx
  10502. andl %edx,%eax
  10503. (%edx deallocated)
  10504. Change to:
  10505. andb (ref),%al
  10506. movzbl %al,%eax
  10507. Rules are:
  10508. - First two instructions have the same opcode and opsize
  10509. - First instruction's operands are the same super-register
  10510. - Second instruction operates on a different register
  10511. - Third instruction is AND, OR, XOR or TEST
  10512. - Third instruction's operands are the destination registers of the first two instructions
  10513. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10514. - Second instruction's destination register is deallocated afterwards
  10515. }
  10516. TransferUsedRegs(TmpUsedRegs);
  10517. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10518. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10519. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10520. begin
  10521. case taicpu(p).opsize of
  10522. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10523. NewSize := S_B;
  10524. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10525. NewSize := S_W;
  10526. {$ifdef x86_64}
  10527. S_LQ:
  10528. NewSize := S_L;
  10529. {$endif x86_64}
  10530. else
  10531. InternalError(2021120301);
  10532. end;
  10533. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10534. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10535. taicpu(hp2).opsize := NewSize;
  10536. RemoveInstruction(hp1);
  10537. { With TEST, it's best to keep the MOVX instruction at the top }
  10538. if (taicpu(hp2).opcode <> A_TEST) then
  10539. begin
  10540. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10541. asml.Remove(p);
  10542. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10543. asml.InsertAfter(p, hp2);
  10544. p := hp2;
  10545. end
  10546. else
  10547. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10548. Result := True;
  10549. Exit;
  10550. end;
  10551. end;
  10552. end;
  10553. if taicpu(p).opcode=A_MOVZX then
  10554. begin
  10555. { removes superfluous And's after movzx's }
  10556. if reg_and_hp1_is_instr and
  10557. (taicpu(hp1).opcode = A_AND) and
  10558. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10559. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10560. {$ifdef x86_64}
  10561. { check for implicit extension to 64 bit }
  10562. or
  10563. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10564. (taicpu(hp1).opsize=S_Q) and
  10565. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10566. )
  10567. {$endif x86_64}
  10568. )
  10569. then
  10570. begin
  10571. case taicpu(p).opsize Of
  10572. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10573. if (taicpu(hp1).oper[0]^.val = $ff) then
  10574. begin
  10575. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10576. RemoveInstruction(hp1);
  10577. Result:=true;
  10578. exit;
  10579. end;
  10580. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10581. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10582. begin
  10583. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10584. RemoveInstruction(hp1);
  10585. Result:=true;
  10586. exit;
  10587. end;
  10588. {$ifdef x86_64}
  10589. S_LQ:
  10590. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10591. begin
  10592. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10593. RemoveInstruction(hp1);
  10594. Result:=true;
  10595. exit;
  10596. end;
  10597. {$endif x86_64}
  10598. else
  10599. ;
  10600. end;
  10601. { we cannot get rid of the and, but can we get rid of the movz ?}
  10602. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10603. begin
  10604. case taicpu(p).opsize Of
  10605. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10606. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10607. begin
  10608. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10609. RemoveCurrentP(p,hp1);
  10610. Result:=true;
  10611. exit;
  10612. end;
  10613. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10614. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10615. begin
  10616. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10617. RemoveCurrentP(p,hp1);
  10618. Result:=true;
  10619. exit;
  10620. end;
  10621. {$ifdef x86_64}
  10622. S_LQ:
  10623. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10624. begin
  10625. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10626. RemoveCurrentP(p,hp1);
  10627. Result:=true;
  10628. exit;
  10629. end;
  10630. {$endif x86_64}
  10631. else
  10632. ;
  10633. end;
  10634. end;
  10635. end;
  10636. { changes some movzx constructs to faster synonyms (all examples
  10637. are given with eax/ax, but are also valid for other registers)}
  10638. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10639. begin
  10640. case taicpu(p).opsize of
  10641. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10642. (the machine code is equivalent to movzbl %al,%eax), but the
  10643. code generator still generates that assembler instruction and
  10644. it is silently converted. This should probably be checked.
  10645. [Kit] }
  10646. S_BW:
  10647. begin
  10648. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10649. (
  10650. not IsMOVZXAcceptable
  10651. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10652. or (
  10653. (cs_opt_size in current_settings.optimizerswitches) and
  10654. (taicpu(p).oper[1]^.reg = NR_AX)
  10655. )
  10656. ) then
  10657. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10658. begin
  10659. DebugMsg(SPeepholeOptimization + 'var7',p);
  10660. taicpu(p).opcode := A_AND;
  10661. taicpu(p).changeopsize(S_W);
  10662. taicpu(p).loadConst(0,$ff);
  10663. Result := True;
  10664. end
  10665. else if not IsMOVZXAcceptable and
  10666. GetNextInstruction(p, hp1) and
  10667. (tai(hp1).typ = ait_instruction) and
  10668. (taicpu(hp1).opcode = A_AND) and
  10669. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10670. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10671. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10672. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10673. begin
  10674. DebugMsg(SPeepholeOptimization + 'var8',p);
  10675. taicpu(p).opcode := A_MOV;
  10676. taicpu(p).changeopsize(S_W);
  10677. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10678. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10679. Result := True;
  10680. end;
  10681. end;
  10682. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10683. S_BL:
  10684. begin
  10685. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10686. (
  10687. not IsMOVZXAcceptable
  10688. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10689. or (
  10690. (cs_opt_size in current_settings.optimizerswitches) and
  10691. (taicpu(p).oper[1]^.reg = NR_EAX)
  10692. )
  10693. ) then
  10694. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10695. begin
  10696. DebugMsg(SPeepholeOptimization + 'var9',p);
  10697. taicpu(p).opcode := A_AND;
  10698. taicpu(p).changeopsize(S_L);
  10699. taicpu(p).loadConst(0,$ff);
  10700. Result := True;
  10701. end
  10702. else if not IsMOVZXAcceptable and
  10703. GetNextInstruction(p, hp1) and
  10704. (tai(hp1).typ = ait_instruction) and
  10705. (taicpu(hp1).opcode = A_AND) and
  10706. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10707. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10708. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10709. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10710. begin
  10711. DebugMsg(SPeepholeOptimization + 'var10',p);
  10712. taicpu(p).opcode := A_MOV;
  10713. taicpu(p).changeopsize(S_L);
  10714. { do not use R_SUBWHOLE
  10715. as movl %rdx,%eax
  10716. is invalid in assembler PM }
  10717. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10718. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10719. Result := True;
  10720. end;
  10721. end;
  10722. {$endif i8086}
  10723. S_WL:
  10724. if not IsMOVZXAcceptable then
  10725. begin
  10726. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10727. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10728. begin
  10729. DebugMsg(SPeepholeOptimization + 'var11',p);
  10730. taicpu(p).opcode := A_AND;
  10731. taicpu(p).changeopsize(S_L);
  10732. taicpu(p).loadConst(0,$ffff);
  10733. Result := True;
  10734. end
  10735. else if GetNextInstruction(p, hp1) and
  10736. (tai(hp1).typ = ait_instruction) and
  10737. (taicpu(hp1).opcode = A_AND) and
  10738. (taicpu(hp1).oper[0]^.typ = top_const) and
  10739. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10740. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10741. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10742. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10743. begin
  10744. DebugMsg(SPeepholeOptimization + 'var12',p);
  10745. taicpu(p).opcode := A_MOV;
  10746. taicpu(p).changeopsize(S_L);
  10747. { do not use R_SUBWHOLE
  10748. as movl %rdx,%eax
  10749. is invalid in assembler PM }
  10750. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10751. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10752. Result := True;
  10753. end;
  10754. end;
  10755. else
  10756. InternalError(2017050705);
  10757. end;
  10758. end
  10759. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10760. begin
  10761. if GetNextInstruction(p, hp1) and
  10762. (tai(hp1).typ = ait_instruction) and
  10763. (taicpu(hp1).opcode = A_AND) and
  10764. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10765. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10766. begin
  10767. //taicpu(p).opcode := A_MOV;
  10768. case taicpu(p).opsize Of
  10769. S_BL:
  10770. begin
  10771. DebugMsg(SPeepholeOptimization + 'var13',p);
  10772. taicpu(hp1).changeopsize(S_L);
  10773. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10774. end;
  10775. S_WL:
  10776. begin
  10777. DebugMsg(SPeepholeOptimization + 'var14',p);
  10778. taicpu(hp1).changeopsize(S_L);
  10779. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10780. end;
  10781. S_BW:
  10782. begin
  10783. DebugMsg(SPeepholeOptimization + 'var15',p);
  10784. taicpu(hp1).changeopsize(S_W);
  10785. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10786. end;
  10787. else
  10788. Internalerror(2017050704)
  10789. end;
  10790. Result := True;
  10791. end;
  10792. end;
  10793. end;
  10794. end;
  10795. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10796. var
  10797. hp1, hp2 : tai;
  10798. MaskLength : Cardinal;
  10799. MaskedBits : TCgInt;
  10800. ActiveReg : TRegister;
  10801. begin
  10802. Result:=false;
  10803. { There are no optimisations for reference targets }
  10804. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10805. Exit;
  10806. while GetNextInstruction(p, hp1) and
  10807. (hp1.typ = ait_instruction) do
  10808. begin
  10809. if (taicpu(p).oper[0]^.typ = top_const) then
  10810. begin
  10811. case taicpu(hp1).opcode of
  10812. A_AND:
  10813. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10814. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10815. { the second register must contain the first one, so compare their subreg types }
  10816. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10817. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10818. { change
  10819. and const1, reg
  10820. and const2, reg
  10821. to
  10822. and (const1 and const2), reg
  10823. }
  10824. begin
  10825. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10826. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10827. RemoveCurrentP(p, hp1);
  10828. Result:=true;
  10829. exit;
  10830. end;
  10831. A_CMP:
  10832. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10833. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10834. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10835. { Just check that the condition on the next instruction is compatible }
  10836. GetNextInstruction(hp1, hp2) and
  10837. (hp2.typ = ait_instruction) and
  10838. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10839. then
  10840. { change
  10841. and 2^n, reg
  10842. cmp 2^n, reg
  10843. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10844. to
  10845. and 2^n, reg
  10846. test reg, reg
  10847. j(~c) / set(~c) / cmov(~c)
  10848. }
  10849. begin
  10850. { Keep TEST instruction in, rather than remove it, because
  10851. it may trigger other optimisations such as MovAndTest2Test }
  10852. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10853. taicpu(hp1).opcode := A_TEST;
  10854. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10855. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10856. Result := True;
  10857. Exit;
  10858. end;
  10859. A_MOVZX:
  10860. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10861. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10862. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10863. (
  10864. (
  10865. (taicpu(p).opsize=S_W) and
  10866. (taicpu(hp1).opsize=S_BW)
  10867. ) or
  10868. (
  10869. (taicpu(p).opsize=S_L) and
  10870. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10871. )
  10872. {$ifdef x86_64}
  10873. or
  10874. (
  10875. (taicpu(p).opsize=S_Q) and
  10876. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10877. )
  10878. {$endif x86_64}
  10879. ) then
  10880. begin
  10881. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10882. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10883. ) or
  10884. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10885. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10886. then
  10887. begin
  10888. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10889. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10890. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10891. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10892. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10893. }
  10894. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10895. RemoveInstruction(hp1);
  10896. { See if there are other optimisations possible }
  10897. Continue;
  10898. end;
  10899. end;
  10900. A_SHL:
  10901. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10902. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10903. begin
  10904. {$ifopt R+}
  10905. {$define RANGE_WAS_ON}
  10906. {$R-}
  10907. {$endif}
  10908. { get length of potential and mask }
  10909. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10910. { really a mask? }
  10911. {$ifdef RANGE_WAS_ON}
  10912. {$R+}
  10913. {$endif}
  10914. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10915. { unmasked part shifted out? }
  10916. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10917. begin
  10918. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10919. RemoveCurrentP(p, hp1);
  10920. Result:=true;
  10921. exit;
  10922. end;
  10923. end;
  10924. A_SHR:
  10925. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10926. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10927. (taicpu(hp1).oper[0]^.val <= 63) then
  10928. begin
  10929. { Does SHR combined with the AND cover all the bits?
  10930. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10931. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10932. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10933. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10934. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10935. begin
  10936. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10937. RemoveCurrentP(p, hp1);
  10938. Result := True;
  10939. Exit;
  10940. end;
  10941. end;
  10942. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10943. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10944. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10945. begin
  10946. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10947. (
  10948. (
  10949. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10950. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10951. ) or (
  10952. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10953. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10954. {$ifdef x86_64}
  10955. ) or (
  10956. (taicpu(hp1).opsize = S_LQ) and
  10957. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10958. {$endif x86_64}
  10959. )
  10960. ) then
  10961. begin
  10962. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10963. begin
  10964. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10965. RemoveInstruction(hp1);
  10966. { See if there are other optimisations possible }
  10967. Continue;
  10968. end;
  10969. { The super-registers are the same though.
  10970. Note that this change by itself doesn't improve
  10971. code speed, but it opens up other optimisations. }
  10972. {$ifdef x86_64}
  10973. { Convert 64-bit register to 32-bit }
  10974. case taicpu(hp1).opsize of
  10975. S_BQ:
  10976. begin
  10977. taicpu(hp1).opsize := S_BL;
  10978. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10979. end;
  10980. S_WQ:
  10981. begin
  10982. taicpu(hp1).opsize := S_WL;
  10983. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10984. end
  10985. else
  10986. ;
  10987. end;
  10988. {$endif x86_64}
  10989. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10990. taicpu(hp1).opcode := A_MOVZX;
  10991. { See if there are other optimisations possible }
  10992. Continue;
  10993. end;
  10994. end;
  10995. else
  10996. ;
  10997. end;
  10998. end
  10999. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11000. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11001. begin
  11002. {$ifdef x86_64}
  11003. if (taicpu(p).opsize = S_Q) then
  11004. begin
  11005. { Never necessary }
  11006. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11007. RemoveCurrentP(p, hp1);
  11008. Result := True;
  11009. Exit;
  11010. end;
  11011. {$endif x86_64}
  11012. { Forward check to determine necessity of and %reg,%reg }
  11013. TransferUsedRegs(TmpUsedRegs);
  11014. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11015. { Saves on a bunch of dereferences }
  11016. ActiveReg := taicpu(p).oper[1]^.reg;
  11017. case taicpu(hp1).opcode of
  11018. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11019. if (
  11020. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11021. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11022. ) and
  11023. (
  11024. (taicpu(hp1).opcode <> A_MOV) or
  11025. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11026. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11027. ) and
  11028. not (
  11029. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11030. (taicpu(hp1).opcode = A_MOV) and
  11031. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11032. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11033. ) and
  11034. (
  11035. (
  11036. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11037. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11038. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11039. ) or
  11040. (
  11041. {$ifdef x86_64}
  11042. (
  11043. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11044. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11045. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11046. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11047. ) and
  11048. {$endif x86_64}
  11049. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11050. )
  11051. ) then
  11052. begin
  11053. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11054. RemoveCurrentP(p, hp1);
  11055. Result := True;
  11056. Exit;
  11057. end;
  11058. A_ADD,
  11059. A_AND,
  11060. A_BSF,
  11061. A_BSR,
  11062. A_BTC,
  11063. A_BTR,
  11064. A_BTS,
  11065. A_OR,
  11066. A_SUB,
  11067. A_XOR:
  11068. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11069. if (
  11070. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11071. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11072. ) and
  11073. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11074. begin
  11075. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11076. RemoveCurrentP(p, hp1);
  11077. Result := True;
  11078. Exit;
  11079. end;
  11080. A_CMP,
  11081. A_TEST:
  11082. if (
  11083. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11084. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11085. ) and
  11086. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11087. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11088. begin
  11089. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11090. RemoveCurrentP(p, hp1);
  11091. Result := True;
  11092. Exit;
  11093. end;
  11094. A_BSWAP,
  11095. A_NEG,
  11096. A_NOT:
  11097. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11098. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11099. begin
  11100. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11101. RemoveCurrentP(p, hp1);
  11102. Result := True;
  11103. Exit;
  11104. end;
  11105. else
  11106. ;
  11107. end;
  11108. end;
  11109. if (taicpu(hp1).is_jmp) and
  11110. (taicpu(hp1).opcode<>A_JMP) and
  11111. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11112. begin
  11113. { change
  11114. and x, reg
  11115. jxx
  11116. to
  11117. test x, reg
  11118. jxx
  11119. if reg is deallocated before the
  11120. jump, but only if it's a conditional jump (PFV)
  11121. }
  11122. taicpu(p).opcode := A_TEST;
  11123. Exit;
  11124. end;
  11125. Break;
  11126. end;
  11127. { Lone AND tests }
  11128. if (taicpu(p).oper[0]^.typ = top_const) then
  11129. begin
  11130. {
  11131. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11132. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11133. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11134. }
  11135. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11136. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11137. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11138. begin
  11139. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11140. if taicpu(p).opsize = S_L then
  11141. begin
  11142. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11143. Result := True;
  11144. end;
  11145. end;
  11146. end;
  11147. { Backward check to determine necessity of and %reg,%reg }
  11148. if (taicpu(p).oper[0]^.typ = top_reg) and
  11149. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11150. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11151. GetLastInstruction(p, hp2) and
  11152. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11153. { Check size of adjacent instruction to determine if the AND is
  11154. effectively a null operation }
  11155. (
  11156. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11157. { Note: Don't include S_Q }
  11158. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11159. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11160. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11161. ) then
  11162. begin
  11163. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11164. { If GetNextInstruction returned False, hp1 will be nil }
  11165. RemoveCurrentP(p, hp1);
  11166. Result := True;
  11167. Exit;
  11168. end;
  11169. end;
  11170. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11171. var
  11172. hp1: tai; NewRef: TReference;
  11173. { This entire nested function is used in an if-statement below, but we
  11174. want to avoid all the used reg transfers and GetNextInstruction calls
  11175. until we really have to check }
  11176. function MemRegisterNotUsedLater: Boolean; inline;
  11177. var
  11178. hp2: tai;
  11179. begin
  11180. TransferUsedRegs(TmpUsedRegs);
  11181. hp2 := p;
  11182. repeat
  11183. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11184. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11185. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11186. end;
  11187. begin
  11188. Result := False;
  11189. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11190. Exit;
  11191. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11192. begin
  11193. { Change:
  11194. add %reg2,%reg1
  11195. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11196. To:
  11197. mov/s/z #(%reg1,%reg2),%reg1
  11198. }
  11199. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11200. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11201. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11202. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11203. (
  11204. (
  11205. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11206. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11207. { r/esp cannot be an index }
  11208. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11209. ) or (
  11210. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11211. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11212. )
  11213. ) and (
  11214. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11215. (
  11216. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11217. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11218. MemRegisterNotUsedLater
  11219. )
  11220. ) then
  11221. begin
  11222. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11223. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11224. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11225. RemoveCurrentp(p, hp1);
  11226. Result := True;
  11227. Exit;
  11228. end;
  11229. { Change:
  11230. addl/q $x,%reg1
  11231. movl/q %reg1,%reg2
  11232. To:
  11233. leal/q $x(%reg1),%reg2
  11234. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11235. Breaks the dependency chain.
  11236. }
  11237. if MatchOpType(taicpu(p),top_const,top_reg) and
  11238. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11239. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11240. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11241. (
  11242. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11243. not (cs_opt_size in current_settings.optimizerswitches) or
  11244. (
  11245. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11246. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11247. )
  11248. ) then
  11249. begin
  11250. { Change the MOV instruction to a LEA instruction, and update the
  11251. first operand }
  11252. reference_reset(NewRef, 1, []);
  11253. NewRef.base := taicpu(p).oper[1]^.reg;
  11254. NewRef.scalefactor := 1;
  11255. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11256. taicpu(hp1).opcode := A_LEA;
  11257. taicpu(hp1).loadref(0, NewRef);
  11258. TransferUsedRegs(TmpUsedRegs);
  11259. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11260. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11261. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11262. begin
  11263. { Move what is now the LEA instruction to before the SUB instruction }
  11264. Asml.Remove(hp1);
  11265. Asml.InsertBefore(hp1, p);
  11266. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11267. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11268. p := hp1;
  11269. end
  11270. else
  11271. begin
  11272. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11273. RemoveCurrentP(p, hp1);
  11274. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11275. end;
  11276. Result := True;
  11277. end;
  11278. end;
  11279. end;
  11280. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11281. var
  11282. SubReg: TSubRegister;
  11283. begin
  11284. Result:=false;
  11285. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11286. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11287. with taicpu(p).oper[0]^.ref^ do
  11288. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11289. begin
  11290. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11291. begin
  11292. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11293. taicpu(p).opcode := A_ADD;
  11294. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11295. Result := True;
  11296. end
  11297. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11298. begin
  11299. if (base <> NR_NO) then
  11300. begin
  11301. if (scalefactor <= 1) then
  11302. begin
  11303. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11304. taicpu(p).opcode := A_ADD;
  11305. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11306. Result := True;
  11307. end;
  11308. end
  11309. else
  11310. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11311. if (scalefactor in [2, 4, 8]) then
  11312. begin
  11313. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11314. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11315. taicpu(p).opcode := A_SHL;
  11316. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11317. Result := True;
  11318. end;
  11319. end;
  11320. end;
  11321. end;
  11322. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11323. var
  11324. hp1: tai; NewRef: TReference;
  11325. begin
  11326. { Change:
  11327. subl/q $x,%reg1
  11328. movl/q %reg1,%reg2
  11329. To:
  11330. leal/q $-x(%reg1),%reg2
  11331. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11332. Breaks the dependency chain and potentially permits the removal of
  11333. a CMP instruction if one follows.
  11334. }
  11335. Result := False;
  11336. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11337. MatchOpType(taicpu(p),top_const,top_reg) and
  11338. GetNextInstruction(p, hp1) and
  11339. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11340. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11341. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11342. (
  11343. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11344. not (cs_opt_size in current_settings.optimizerswitches) or
  11345. (
  11346. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11347. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11348. )
  11349. ) then
  11350. begin
  11351. { Change the MOV instruction to a LEA instruction, and update the
  11352. first operand }
  11353. reference_reset(NewRef, 1, []);
  11354. NewRef.base := taicpu(p).oper[1]^.reg;
  11355. NewRef.scalefactor := 1;
  11356. NewRef.offset := -taicpu(p).oper[0]^.val;
  11357. taicpu(hp1).opcode := A_LEA;
  11358. taicpu(hp1).loadref(0, NewRef);
  11359. TransferUsedRegs(TmpUsedRegs);
  11360. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11361. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11362. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11363. begin
  11364. { Move what is now the LEA instruction to before the SUB instruction }
  11365. Asml.Remove(hp1);
  11366. Asml.InsertBefore(hp1, p);
  11367. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11368. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11369. p := hp1;
  11370. end
  11371. else
  11372. begin
  11373. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11374. RemoveCurrentP(p, hp1);
  11375. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11376. end;
  11377. Result := True;
  11378. end;
  11379. end;
  11380. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11381. begin
  11382. { we can skip all instructions not messing with the stack pointer }
  11383. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11384. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11385. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11386. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11387. ({(taicpu(hp1).ops=0) or }
  11388. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11389. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11390. ) and }
  11391. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11392. )
  11393. ) do
  11394. GetNextInstruction(hp1,hp1);
  11395. Result:=assigned(hp1);
  11396. end;
  11397. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11398. var
  11399. hp1, hp2, hp3, hp4, hp5: tai;
  11400. begin
  11401. Result:=false;
  11402. hp5:=nil;
  11403. { replace
  11404. leal(q) x(<stackpointer>),<stackpointer>
  11405. call procname
  11406. leal(q) -x(<stackpointer>),<stackpointer>
  11407. ret
  11408. by
  11409. jmp procname
  11410. but do it only on level 4 because it destroys stack back traces
  11411. }
  11412. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11413. MatchOpType(taicpu(p),top_ref,top_reg) and
  11414. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11415. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11416. { the -8 or -24 are not required, but bail out early if possible,
  11417. higher values are unlikely }
  11418. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11419. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11420. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11421. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11422. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11423. GetNextInstruction(p, hp1) and
  11424. { Take a copy of hp1 }
  11425. SetAndTest(hp1, hp4) and
  11426. { trick to skip label }
  11427. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11428. SkipSimpleInstructions(hp1) and
  11429. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11430. GetNextInstruction(hp1, hp2) and
  11431. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11432. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11433. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11434. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11435. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11436. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11437. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11438. { Segment register will be NR_NO }
  11439. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11440. GetNextInstruction(hp2, hp3) and
  11441. { trick to skip label }
  11442. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11443. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11444. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11445. SetAndTest(hp3,hp5) and
  11446. GetNextInstruction(hp3,hp3) and
  11447. MatchInstruction(hp3,A_RET,[S_NO])
  11448. )
  11449. ) and
  11450. (taicpu(hp3).ops=0) then
  11451. begin
  11452. taicpu(hp1).opcode := A_JMP;
  11453. taicpu(hp1).is_jmp := true;
  11454. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11455. RemoveCurrentP(p, hp4);
  11456. RemoveInstruction(hp2);
  11457. RemoveInstruction(hp3);
  11458. if Assigned(hp5) then
  11459. begin
  11460. AsmL.Remove(hp5);
  11461. ASmL.InsertBefore(hp5,hp1)
  11462. end;
  11463. Result:=true;
  11464. end;
  11465. end;
  11466. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11467. {$ifdef x86_64}
  11468. var
  11469. hp1, hp2, hp3, hp4, hp5: tai;
  11470. {$endif x86_64}
  11471. begin
  11472. Result:=false;
  11473. {$ifdef x86_64}
  11474. hp5:=nil;
  11475. { replace
  11476. push %rax
  11477. call procname
  11478. pop %rcx
  11479. ret
  11480. by
  11481. jmp procname
  11482. but do it only on level 4 because it destroys stack back traces
  11483. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11484. for all supported calling conventions
  11485. }
  11486. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11487. MatchOpType(taicpu(p),top_reg) and
  11488. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11489. GetNextInstruction(p, hp1) and
  11490. { Take a copy of hp1 }
  11491. SetAndTest(hp1, hp4) and
  11492. { trick to skip label }
  11493. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11494. SkipSimpleInstructions(hp1) and
  11495. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11496. GetNextInstruction(hp1, hp2) and
  11497. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11498. MatchOpType(taicpu(hp2),top_reg) and
  11499. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11500. GetNextInstruction(hp2, hp3) and
  11501. { trick to skip label }
  11502. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11503. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11504. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11505. SetAndTest(hp3,hp5) and
  11506. GetNextInstruction(hp3,hp3) and
  11507. MatchInstruction(hp3,A_RET,[S_NO])
  11508. )
  11509. ) and
  11510. (taicpu(hp3).ops=0) then
  11511. begin
  11512. taicpu(hp1).opcode := A_JMP;
  11513. taicpu(hp1).is_jmp := true;
  11514. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11515. RemoveCurrentP(p, hp4);
  11516. RemoveInstruction(hp2);
  11517. RemoveInstruction(hp3);
  11518. if Assigned(hp5) then
  11519. begin
  11520. AsmL.Remove(hp5);
  11521. ASmL.InsertBefore(hp5,hp1)
  11522. end;
  11523. Result:=true;
  11524. end;
  11525. {$endif x86_64}
  11526. end;
  11527. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11528. var
  11529. Value, RegName: string;
  11530. begin
  11531. Result:=false;
  11532. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11533. begin
  11534. case taicpu(p).oper[0]^.val of
  11535. 0:
  11536. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11537. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11538. begin
  11539. { change "mov $0,%reg" into "xor %reg,%reg" }
  11540. taicpu(p).opcode := A_XOR;
  11541. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11542. Result := True;
  11543. {$ifdef x86_64}
  11544. end
  11545. else if (taicpu(p).opsize = S_Q) then
  11546. begin
  11547. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11548. { The actual optimization }
  11549. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11550. taicpu(p).changeopsize(S_L);
  11551. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11552. Result := True;
  11553. end;
  11554. $1..$FFFFFFFF:
  11555. begin
  11556. { Code size reduction by J. Gareth "Kit" Moreton }
  11557. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11558. case taicpu(p).opsize of
  11559. S_Q:
  11560. begin
  11561. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11562. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11563. { The actual optimization }
  11564. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11565. taicpu(p).changeopsize(S_L);
  11566. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11567. Result := True;
  11568. end;
  11569. else
  11570. { Do nothing };
  11571. end;
  11572. {$endif x86_64}
  11573. end;
  11574. -1:
  11575. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11576. if (cs_opt_size in current_settings.optimizerswitches) and
  11577. (taicpu(p).opsize <> S_B) and
  11578. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11579. begin
  11580. { change "mov $-1,%reg" into "or $-1,%reg" }
  11581. { NOTES:
  11582. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11583. - This operation creates a false dependency on the register, so only do it when optimising for size
  11584. - 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
  11585. }
  11586. taicpu(p).opcode := A_OR;
  11587. Result := True;
  11588. end;
  11589. else
  11590. { Do nothing };
  11591. end;
  11592. end;
  11593. end;
  11594. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11595. var
  11596. hp1: tai;
  11597. begin
  11598. { Detect:
  11599. andw x, %ax (0 <= x < $8000)
  11600. ...
  11601. movzwl %ax,%eax
  11602. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11603. }
  11604. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11605. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11606. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11607. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11608. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11609. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11610. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11611. begin
  11612. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11613. taicpu(hp1).opcode := A_CWDE;
  11614. taicpu(hp1).clearop(0);
  11615. taicpu(hp1).clearop(1);
  11616. taicpu(hp1).ops := 0;
  11617. { A change was made, but not with p, so move forward 1 }
  11618. p := tai(p.Next);
  11619. Result := True;
  11620. end;
  11621. end;
  11622. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11623. begin
  11624. Result := False;
  11625. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11626. Exit;
  11627. { Convert:
  11628. movswl %ax,%eax -> cwtl
  11629. movslq %eax,%rax -> cdqe
  11630. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11631. refer to the same opcode and depends only on the assembler's
  11632. current operand-size attribute. [Kit]
  11633. }
  11634. with taicpu(p) do
  11635. case opsize of
  11636. S_WL:
  11637. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11638. begin
  11639. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11640. opcode := A_CWDE;
  11641. clearop(0);
  11642. clearop(1);
  11643. ops := 0;
  11644. Result := True;
  11645. end;
  11646. {$ifdef x86_64}
  11647. S_LQ:
  11648. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11649. begin
  11650. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11651. opcode := A_CDQE;
  11652. clearop(0);
  11653. clearop(1);
  11654. ops := 0;
  11655. Result := True;
  11656. end;
  11657. {$endif x86_64}
  11658. else
  11659. ;
  11660. end;
  11661. end;
  11662. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11663. var
  11664. hp1: tai;
  11665. begin
  11666. { Detect:
  11667. shr x, %ax (x > 0)
  11668. ...
  11669. movzwl %ax,%eax
  11670. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11671. }
  11672. Result := False;
  11673. if MatchOpType(taicpu(p), top_const, top_reg) and
  11674. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11675. (taicpu(p).oper[0]^.val > 0) and
  11676. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11677. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11678. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11679. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11680. begin
  11681. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11682. taicpu(hp1).opcode := A_CWDE;
  11683. taicpu(hp1).clearop(0);
  11684. taicpu(hp1).clearop(1);
  11685. taicpu(hp1).ops := 0;
  11686. { A change was made, but not with p, so move forward 1 }
  11687. p := tai(p.Next);
  11688. Result := True;
  11689. end;
  11690. end;
  11691. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11692. var
  11693. hp1, hp2: tai;
  11694. Opposite, SecondOpposite: TAsmOp;
  11695. NewCond: TAsmCond;
  11696. begin
  11697. Result := False;
  11698. { Change:
  11699. add/sub 128,(dest)
  11700. To:
  11701. sub/add -128,(dest)
  11702. This generaally takes fewer bytes to encode because -128 can be stored
  11703. in a signed byte, whereas +128 cannot.
  11704. }
  11705. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11706. begin
  11707. if taicpu(p).opcode = A_ADD then
  11708. Opposite := A_SUB
  11709. else
  11710. Opposite := A_ADD;
  11711. { Be careful if the flags are in use, because the CF flag inverts
  11712. when changing from ADD to SUB and vice versa }
  11713. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11714. GetNextInstruction(p, hp1) then
  11715. begin
  11716. TransferUsedRegs(TmpUsedRegs);
  11717. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11718. hp2 := hp1;
  11719. { Scan ahead to check if everything's safe }
  11720. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11721. begin
  11722. if (hp1.typ <> ait_instruction) then
  11723. { Probably unsafe since the flags are still in use }
  11724. Exit;
  11725. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11726. { Stop searching at an unconditional jump }
  11727. Break;
  11728. if not
  11729. (
  11730. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11731. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11732. ) and
  11733. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11734. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11735. Exit;
  11736. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11737. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11738. { Move to the next instruction }
  11739. GetNextInstruction(hp1, hp1);
  11740. end;
  11741. while Assigned(hp2) and (hp2 <> hp1) do
  11742. begin
  11743. NewCond := C_None;
  11744. case taicpu(hp2).condition of
  11745. C_A, C_NBE:
  11746. NewCond := C_BE;
  11747. C_B, C_C, C_NAE:
  11748. NewCond := C_AE;
  11749. C_AE, C_NB, C_NC:
  11750. NewCond := C_B;
  11751. C_BE, C_NA:
  11752. NewCond := C_A;
  11753. else
  11754. { No change needed };
  11755. end;
  11756. if NewCond <> C_None then
  11757. begin
  11758. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11759. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11760. taicpu(hp2).condition := NewCond;
  11761. end
  11762. else
  11763. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11764. begin
  11765. { Because of the flipping of the carry bit, to ensure
  11766. the operation remains equivalent, ADC becomes SBB
  11767. and vice versa, and the constant is not-inverted.
  11768. If multiple ADCs or SBBs appear in a row, each one
  11769. changed causes the carry bit to invert, so they all
  11770. need to be flipped }
  11771. if taicpu(hp2).opcode = A_ADC then
  11772. SecondOpposite := A_SBB
  11773. else
  11774. SecondOpposite := A_ADC;
  11775. if taicpu(hp2).oper[0]^.typ <> top_const then
  11776. { Should have broken out of this optimisation already }
  11777. InternalError(2021112901);
  11778. 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]^) + ' -> ' +
  11779. 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);
  11780. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11781. taicpu(hp2).opcode := SecondOpposite;
  11782. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11783. end;
  11784. { Move to the next instruction }
  11785. GetNextInstruction(hp2, hp2);
  11786. end;
  11787. if (hp2 <> hp1) then
  11788. InternalError(2021111501);
  11789. end;
  11790. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11791. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11792. taicpu(p).opcode := Opposite;
  11793. taicpu(p).oper[0]^.val := -128;
  11794. { No further optimisations can be made on this instruction, so move
  11795. onto the next one to save time }
  11796. p := tai(p.Next);
  11797. UpdateUsedRegs(p);
  11798. Result := True;
  11799. Exit;
  11800. end;
  11801. { Detect:
  11802. add/sub %reg2,(dest)
  11803. add/sub x, (dest)
  11804. (dest can be a register or a reference)
  11805. Swap the instructions to minimise a pipeline stall. This reverses the
  11806. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11807. optimisations could be made.
  11808. }
  11809. if (taicpu(p).oper[0]^.typ = top_reg) and
  11810. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11811. (
  11812. (
  11813. (taicpu(p).oper[1]^.typ = top_reg) and
  11814. { We can try searching further ahead if we're writing to a register }
  11815. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11816. ) or
  11817. (
  11818. (taicpu(p).oper[1]^.typ = top_ref) and
  11819. GetNextInstruction(p, hp1)
  11820. )
  11821. ) and
  11822. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11823. (taicpu(hp1).oper[0]^.typ = top_const) and
  11824. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11825. begin
  11826. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11827. TransferUsedRegs(TmpUsedRegs);
  11828. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11829. hp2 := p;
  11830. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11831. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11832. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11833. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11834. begin
  11835. asml.remove(hp1);
  11836. asml.InsertBefore(hp1, p);
  11837. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11838. Result := True;
  11839. end;
  11840. end;
  11841. end;
  11842. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11843. begin
  11844. Result:=false;
  11845. { change "cmp $0, %reg" to "test %reg, %reg" }
  11846. if MatchOpType(taicpu(p),top_const,top_reg) and
  11847. (taicpu(p).oper[0]^.val = 0) then
  11848. begin
  11849. taicpu(p).opcode := A_TEST;
  11850. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11851. Result:=true;
  11852. end;
  11853. end;
  11854. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11855. var
  11856. IsTestConstX : Boolean;
  11857. hp1,hp2 : tai;
  11858. begin
  11859. Result:=false;
  11860. { removes the line marked with (x) from the sequence
  11861. and/or/xor/add/sub/... $x, %y
  11862. test/or %y, %y | test $-1, %y (x)
  11863. j(n)z _Label
  11864. as the first instruction already adjusts the ZF
  11865. %y operand may also be a reference }
  11866. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11867. MatchOperand(taicpu(p).oper[0]^,-1);
  11868. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11869. GetLastInstruction(p, hp1) and
  11870. (tai(hp1).typ = ait_instruction) and
  11871. GetNextInstruction(p,hp2) and
  11872. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11873. case taicpu(hp1).opcode Of
  11874. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11875. { These two instructions set the zero flag if the result is zero }
  11876. A_POPCNT, A_LZCNT:
  11877. begin
  11878. if (
  11879. { With POPCNT, an input of zero will set the zero flag
  11880. because the population count of zero is zero }
  11881. (taicpu(hp1).opcode = A_POPCNT) and
  11882. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11883. (
  11884. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11885. { Faster than going through the second half of the 'or'
  11886. condition below }
  11887. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11888. )
  11889. ) or (
  11890. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11891. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11892. { and in case of carry for A(E)/B(E)/C/NC }
  11893. (
  11894. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11895. (
  11896. (taicpu(hp1).opcode <> A_ADD) and
  11897. (taicpu(hp1).opcode <> A_SUB) and
  11898. (taicpu(hp1).opcode <> A_LZCNT)
  11899. )
  11900. )
  11901. ) then
  11902. begin
  11903. RemoveCurrentP(p, hp2);
  11904. Result:=true;
  11905. Exit;
  11906. end;
  11907. end;
  11908. A_SHL, A_SAL, A_SHR, A_SAR:
  11909. begin
  11910. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11911. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11912. { therefore, it's only safe to do this optimization for }
  11913. { shifts by a (nonzero) constant }
  11914. (taicpu(hp1).oper[0]^.typ = top_const) and
  11915. (taicpu(hp1).oper[0]^.val <> 0) and
  11916. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11917. { and in case of carry for A(E)/B(E)/C/NC }
  11918. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11919. begin
  11920. RemoveCurrentP(p, hp2);
  11921. Result:=true;
  11922. Exit;
  11923. end;
  11924. end;
  11925. A_DEC, A_INC, A_NEG:
  11926. begin
  11927. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11928. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11929. { and in case of carry for A(E)/B(E)/C/NC }
  11930. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11931. begin
  11932. RemoveCurrentP(p, hp2);
  11933. Result:=true;
  11934. Exit;
  11935. end;
  11936. end
  11937. else
  11938. ;
  11939. end; { case }
  11940. { change "test $-1,%reg" into "test %reg,%reg" }
  11941. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11942. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11943. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11944. if MatchInstruction(p, A_OR, []) and
  11945. { Can only match if they're both registers }
  11946. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11947. begin
  11948. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11949. taicpu(p).opcode := A_TEST;
  11950. { No need to set Result to True, as we've done all the optimisations we can }
  11951. end;
  11952. end;
  11953. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11954. var
  11955. hp1,hp3 : tai;
  11956. {$ifndef x86_64}
  11957. hp2 : taicpu;
  11958. {$endif x86_64}
  11959. begin
  11960. Result:=false;
  11961. hp3:=nil;
  11962. {$ifndef x86_64}
  11963. { don't do this on modern CPUs, this really hurts them due to
  11964. broken call/ret pairing }
  11965. if (current_settings.optimizecputype < cpu_Pentium2) and
  11966. not(cs_create_pic in current_settings.moduleswitches) and
  11967. GetNextInstruction(p, hp1) and
  11968. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11969. MatchOpType(taicpu(hp1),top_ref) and
  11970. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11971. begin
  11972. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11973. InsertLLItem(p.previous, p, hp2);
  11974. taicpu(p).opcode := A_JMP;
  11975. taicpu(p).is_jmp := true;
  11976. RemoveInstruction(hp1);
  11977. Result:=true;
  11978. end
  11979. else
  11980. {$endif x86_64}
  11981. { replace
  11982. call procname
  11983. ret
  11984. by
  11985. jmp procname
  11986. but do it only on level 4 because it destroys stack back traces
  11987. else if the subroutine is marked as no return, remove the ret
  11988. }
  11989. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11990. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11991. GetNextInstruction(p, hp1) and
  11992. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11993. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11994. SetAndTest(hp1,hp3) and
  11995. GetNextInstruction(hp1,hp1) and
  11996. MatchInstruction(hp1,A_RET,[S_NO])
  11997. )
  11998. ) and
  11999. (taicpu(hp1).ops=0) then
  12000. begin
  12001. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12002. { we might destroy stack alignment here if we do not do a call }
  12003. (target_info.stackalign<=sizeof(SizeUInt)) then
  12004. begin
  12005. taicpu(p).opcode := A_JMP;
  12006. taicpu(p).is_jmp := true;
  12007. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12008. end
  12009. else
  12010. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12011. RemoveInstruction(hp1);
  12012. if Assigned(hp3) then
  12013. begin
  12014. AsmL.Remove(hp3);
  12015. AsmL.InsertBefore(hp3,p)
  12016. end;
  12017. Result:=true;
  12018. end;
  12019. end;
  12020. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12021. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12022. begin
  12023. case OpSize of
  12024. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12025. Result := (Val <= $FF) and (Val >= -128);
  12026. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12027. Result := (Val <= $FFFF) and (Val >= -32768);
  12028. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12029. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12030. else
  12031. Result := True;
  12032. end;
  12033. end;
  12034. var
  12035. hp1, hp2 : tai;
  12036. SizeChange: Boolean;
  12037. PreMessage: string;
  12038. begin
  12039. Result := False;
  12040. if (taicpu(p).oper[0]^.typ = top_reg) and
  12041. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12042. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12043. begin
  12044. { Change (using movzbl %al,%eax as an example):
  12045. movzbl %al, %eax movzbl %al, %eax
  12046. cmpl x, %eax testl %eax,%eax
  12047. To:
  12048. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12049. movzbl %al, %eax movzbl %al, %eax
  12050. Smaller instruction and minimises pipeline stall as the CPU
  12051. doesn't have to wait for the register to get zero-extended. [Kit]
  12052. Also allow if the smaller of the two registers is being checked,
  12053. as this still removes the false dependency.
  12054. }
  12055. if
  12056. (
  12057. (
  12058. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12059. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12060. ) or (
  12061. { If MatchOperand returns True, they must both be registers }
  12062. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12063. )
  12064. ) and
  12065. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12066. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12067. begin
  12068. 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);
  12069. asml.Remove(hp1);
  12070. asml.InsertBefore(hp1, p);
  12071. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12072. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12073. begin
  12074. taicpu(hp1).opcode := A_TEST;
  12075. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12076. end;
  12077. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12078. case taicpu(p).opsize of
  12079. S_BW, S_BL:
  12080. begin
  12081. SizeChange := taicpu(hp1).opsize <> S_B;
  12082. taicpu(hp1).changeopsize(S_B);
  12083. end;
  12084. S_WL:
  12085. begin
  12086. SizeChange := taicpu(hp1).opsize <> S_W;
  12087. taicpu(hp1).changeopsize(S_W);
  12088. end
  12089. else
  12090. InternalError(2020112701);
  12091. end;
  12092. UpdateUsedRegs(tai(p.Next));
  12093. { Check if the register is used aferwards - if not, we can
  12094. remove the movzx instruction completely }
  12095. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12096. begin
  12097. { Hp1 is a better position than p for debugging purposes }
  12098. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12099. RemoveCurrentp(p, hp1);
  12100. Result := True;
  12101. end;
  12102. if SizeChange then
  12103. DebugMsg(SPeepholeOptimization + PreMessage +
  12104. 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)
  12105. else
  12106. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12107. Exit;
  12108. end;
  12109. { Change (using movzwl %ax,%eax as an example):
  12110. movzwl %ax, %eax
  12111. movb %al, (dest) (Register is smaller than read register in movz)
  12112. To:
  12113. movb %al, (dest) (Move one back to avoid a false dependency)
  12114. movzwl %ax, %eax
  12115. }
  12116. if (taicpu(hp1).opcode = A_MOV) and
  12117. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12118. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12119. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12120. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12121. begin
  12122. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12123. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12124. asml.Remove(hp1);
  12125. asml.InsertBefore(hp1, p);
  12126. if taicpu(hp1).oper[1]^.typ = top_reg then
  12127. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12128. { Check if the register is used aferwards - if not, we can
  12129. remove the movzx instruction completely }
  12130. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12131. begin
  12132. { Hp1 is a better position than p for debugging purposes }
  12133. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12134. RemoveCurrentp(p, hp1);
  12135. Result := True;
  12136. end;
  12137. Exit;
  12138. end;
  12139. end;
  12140. end;
  12141. {$ifdef x86_64}
  12142. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12143. var
  12144. PreMessage, RegName: string;
  12145. begin
  12146. { Code size reduction by J. Gareth "Kit" Moreton }
  12147. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12148. as this removes the REX prefix }
  12149. Result := False;
  12150. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12151. Exit;
  12152. if taicpu(p).oper[0]^.typ <> top_reg then
  12153. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12154. InternalError(2018011500);
  12155. case taicpu(p).opsize of
  12156. S_Q:
  12157. begin
  12158. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12159. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12160. { The actual optimization }
  12161. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12162. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12163. taicpu(p).changeopsize(S_L);
  12164. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12165. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12166. end;
  12167. else
  12168. ;
  12169. end;
  12170. end;
  12171. {$endif}
  12172. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12173. var
  12174. XReg: TRegister;
  12175. begin
  12176. Result := False;
  12177. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12178. Smaller encoding and slightly faster on some platforms (also works for
  12179. ZMM-sized registers) }
  12180. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12181. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12182. begin
  12183. XReg := taicpu(p).oper[0]^.reg;
  12184. if (taicpu(p).oper[1]^.reg = XReg) then
  12185. begin
  12186. taicpu(p).changeopsize(S_XMM);
  12187. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12188. if (cs_opt_size in current_settings.optimizerswitches) then
  12189. begin
  12190. { Change input registers to %xmm0 to reduce size. Note that
  12191. there's a risk of a false dependency doing this, so only
  12192. optimise for size here }
  12193. XReg := NR_XMM0;
  12194. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12195. end
  12196. else
  12197. begin
  12198. setsubreg(XReg, R_SUBMMX);
  12199. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12200. end;
  12201. taicpu(p).oper[0]^.reg := XReg;
  12202. taicpu(p).oper[1]^.reg := XReg;
  12203. Result := True;
  12204. end;
  12205. end;
  12206. end;
  12207. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12208. var
  12209. OperIdx: Integer;
  12210. begin
  12211. for OperIdx := 0 to p.ops - 1 do
  12212. if p.oper[OperIdx]^.typ = top_ref then
  12213. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12214. end;
  12215. end.