aoptx86.pas 476 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function PrePeepholeOptSxx(var p : tai) : boolean;
  107. function PrePeepholeOptIMUL(var p : tai) : boolean;
  108. function PrePeepholeOptAND(var p : tai) : boolean;
  109. function OptPass1Test(var p: tai): boolean;
  110. function OptPass1Add(var p: tai): boolean;
  111. function OptPass1AND(var p : tai) : boolean;
  112. function OptPass1_V_MOVAP(var p : tai) : boolean;
  113. function OptPass1VOP(var p : tai) : boolean;
  114. function OptPass1MOV(var p : tai) : boolean;
  115. function OptPass1Movx(var p : tai) : boolean;
  116. function OptPass1MOVXX(var p : tai) : boolean;
  117. function OptPass1OP(var p : tai) : boolean;
  118. function OptPass1LEA(var p : tai) : boolean;
  119. function OptPass1Sub(var p : tai) : boolean;
  120. function OptPass1SHLSAL(var p : tai) : boolean;
  121. function OptPass1FSTP(var p : tai) : boolean;
  122. function OptPass1FLD(var p : tai) : boolean;
  123. function OptPass1Cmp(var p : tai) : boolean;
  124. function OptPass1PXor(var p : tai) : boolean;
  125. function OptPass1VPXor(var p: tai): boolean;
  126. function OptPass1Imul(var p : tai) : boolean;
  127. function OptPass1Jcc(var p : tai) : boolean;
  128. function OptPass1SHXX(var p: tai): boolean;
  129. function OptPass1VMOVDQ(var p: tai): Boolean;
  130. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  131. function OptPass2Movx(var p : tai): Boolean;
  132. function OptPass2MOV(var p : tai) : boolean;
  133. function OptPass2Imul(var p : tai) : boolean;
  134. function OptPass2Jmp(var p : tai) : boolean;
  135. function OptPass2Jcc(var p : tai) : boolean;
  136. function OptPass2Lea(var p: tai): Boolean;
  137. function OptPass2SUB(var p: tai): Boolean;
  138. function OptPass2ADD(var p : tai): Boolean;
  139. function OptPass2SETcc(var p : tai) : boolean;
  140. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  141. function PostPeepholeOptMov(var p : tai) : Boolean;
  142. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  143. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  144. function PostPeepholeOptXor(var p : tai) : Boolean;
  145. {$endif x86_64}
  146. function PostPeepholeOptAnd(var p : tai) : boolean;
  147. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  148. function PostPeepholeOptCmp(var p : tai) : Boolean;
  149. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  150. function PostPeepholeOptCall(var p : tai) : Boolean;
  151. function PostPeepholeOptLea(var p : tai) : Boolean;
  152. function PostPeepholeOptPush(var p: tai): Boolean;
  153. function PostPeepholeOptShr(var p : tai) : boolean;
  154. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  155. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  156. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  157. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  158. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  159. { Processor-dependent reference optimisation }
  160. class procedure OptimizeRefs(var p: taicpu); static;
  161. end;
  162. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  163. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  166. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  167. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  168. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  169. {$if max_operands>2}
  170. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  171. {$endif max_operands>2}
  172. function RefsEqual(const r1, r2: treference): boolean;
  173. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  174. { returns true, if ref is a reference using only the registers passed as base and index
  175. and having an offset }
  176. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  177. implementation
  178. uses
  179. cutils,verbose,
  180. systems,
  181. globals,
  182. cpuinfo,
  183. procinfo,
  184. paramgr,
  185. aasmbase,
  186. aoptbase,aoptutils,
  187. symconst,symsym,
  188. cgx86,
  189. itcpugas;
  190. {$ifdef DEBUG_AOPTCPU}
  191. const
  192. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  193. {$else DEBUG_AOPTCPU}
  194. { Empty strings help the optimizer to remove string concatenations that won't
  195. ever appear to the user on release builds. [Kit] }
  196. const
  197. SPeepholeOptimization = '';
  198. {$endif DEBUG_AOPTCPU}
  199. LIST_STEP_SIZE = 4;
  200. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. (taicpu(instr).opcode = op) and
  205. ((opsize = []) or (taicpu(instr).opsize in opsize));
  206. end;
  207. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  208. begin
  209. result :=
  210. (instr.typ = ait_instruction) and
  211. ((taicpu(instr).opcode = op1) or
  212. (taicpu(instr).opcode = op2)
  213. ) and
  214. ((opsize = []) or (taicpu(instr).opsize in opsize));
  215. end;
  216. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  217. begin
  218. result :=
  219. (instr.typ = ait_instruction) and
  220. ((taicpu(instr).opcode = op1) or
  221. (taicpu(instr).opcode = op2) or
  222. (taicpu(instr).opcode = op3)
  223. ) and
  224. ((opsize = []) or (taicpu(instr).opsize in opsize));
  225. end;
  226. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  227. const opsize : topsizes) : boolean;
  228. var
  229. op : TAsmOp;
  230. begin
  231. result:=false;
  232. if (instr.typ <> ait_instruction) or
  233. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  234. exit;
  235. for op in ops do
  236. begin
  237. if taicpu(instr).opcode = op then
  238. begin
  239. result:=true;
  240. exit;
  241. end;
  242. end;
  243. end;
  244. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  245. begin
  246. result := (oper.typ = top_reg) and (oper.reg = reg);
  247. end;
  248. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  249. begin
  250. result := (oper.typ = top_const) and (oper.val = a);
  251. end;
  252. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  253. begin
  254. result := oper1.typ = oper2.typ;
  255. if result then
  256. case oper1.typ of
  257. top_const:
  258. Result:=oper1.val = oper2.val;
  259. top_reg:
  260. Result:=oper1.reg = oper2.reg;
  261. top_ref:
  262. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  263. else
  264. internalerror(2013102801);
  265. end
  266. end;
  267. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  268. begin
  269. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  270. if result then
  271. case oper1.typ of
  272. top_const:
  273. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  274. top_reg:
  275. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  276. top_ref:
  277. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  278. else
  279. internalerror(2020052401);
  280. end
  281. end;
  282. function RefsEqual(const r1, r2: treference): boolean;
  283. begin
  284. RefsEqual :=
  285. (r1.offset = r2.offset) and
  286. (r1.segment = r2.segment) and (r1.base = r2.base) and
  287. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  288. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  289. (r1.relsymbol = r2.relsymbol) and
  290. (r1.volatility=[]) and
  291. (r2.volatility=[]);
  292. end;
  293. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  294. begin
  295. Result:=(ref.offset=0) and
  296. (ref.scalefactor in [0,1]) and
  297. (ref.segment=NR_NO) and
  298. (ref.symbol=nil) and
  299. (ref.relsymbol=nil) and
  300. ((base=NR_INVALID) or
  301. (ref.base=base)) and
  302. ((index=NR_INVALID) or
  303. (ref.index=index)) and
  304. (ref.volatility=[]);
  305. end;
  306. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  307. begin
  308. Result:=(ref.scalefactor in [0,1]) and
  309. (ref.segment=NR_NO) and
  310. (ref.symbol=nil) and
  311. (ref.relsymbol=nil) and
  312. ((base=NR_INVALID) or
  313. (ref.base=base)) and
  314. ((index=NR_INVALID) or
  315. (ref.index=index)) and
  316. (ref.volatility=[]);
  317. end;
  318. function InstrReadsFlags(p: tai): boolean;
  319. begin
  320. InstrReadsFlags := true;
  321. case p.typ of
  322. ait_instruction:
  323. if InsProp[taicpu(p).opcode].Ch*
  324. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  325. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  326. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  327. exit;
  328. ait_label:
  329. exit;
  330. else
  331. ;
  332. end;
  333. InstrReadsFlags := false;
  334. end;
  335. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  336. begin
  337. Next:=Current;
  338. repeat
  339. Result:=GetNextInstruction(Next,Next);
  340. until not (Result) or
  341. not(cs_opt_level3 in current_settings.optimizerswitches) or
  342. (Next.typ<>ait_instruction) or
  343. RegInInstruction(reg,Next) or
  344. is_calljmp(taicpu(Next).opcode);
  345. end;
  346. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  347. begin
  348. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  349. Next := Current;
  350. repeat
  351. Result := GetNextInstruction(Next,Next);
  352. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  353. if is_calljmpuncondret(taicpu(Next).opcode) then
  354. begin
  355. Result := False;
  356. Exit;
  357. end
  358. else
  359. CrossJump := True;
  360. until not Result or
  361. not (cs_opt_level3 in current_settings.optimizerswitches) or
  362. (Next.typ <> ait_instruction) or
  363. RegInInstruction(reg,Next);
  364. end;
  365. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  366. begin
  367. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  368. begin
  369. Result:=GetNextInstruction(Current,Next);
  370. exit;
  371. end;
  372. Next:=tai(Current.Next);
  373. Result:=false;
  374. while assigned(Next) do
  375. begin
  376. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  377. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  378. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  379. exit
  380. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  381. begin
  382. Result:=true;
  383. exit;
  384. end;
  385. Next:=tai(Next.Next);
  386. end;
  387. end;
  388. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  389. begin
  390. Result:=RegReadByInstruction(reg,hp);
  391. end;
  392. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  393. var
  394. p: taicpu;
  395. opcount: longint;
  396. begin
  397. RegReadByInstruction := false;
  398. if hp.typ <> ait_instruction then
  399. exit;
  400. p := taicpu(hp);
  401. case p.opcode of
  402. A_CALL:
  403. regreadbyinstruction := true;
  404. A_IMUL:
  405. case p.ops of
  406. 1:
  407. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  408. (
  409. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  410. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  411. );
  412. 2,3:
  413. regReadByInstruction :=
  414. reginop(reg,p.oper[0]^) or
  415. reginop(reg,p.oper[1]^);
  416. else
  417. InternalError(2019112801);
  418. end;
  419. A_MUL:
  420. begin
  421. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  422. (
  423. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  424. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  425. );
  426. end;
  427. A_IDIV,A_DIV:
  428. begin
  429. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  430. (
  431. (getregtype(reg)=R_INTREGISTER) and
  432. (
  433. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  434. )
  435. );
  436. end;
  437. else
  438. begin
  439. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  440. begin
  441. RegReadByInstruction := false;
  442. exit;
  443. end;
  444. for opcount := 0 to p.ops-1 do
  445. if (p.oper[opCount]^.typ = top_ref) and
  446. RegInRef(reg,p.oper[opcount]^.ref^) then
  447. begin
  448. RegReadByInstruction := true;
  449. exit
  450. end;
  451. { special handling for SSE MOVSD }
  452. if (p.opcode=A_MOVSD) and (p.ops>0) then
  453. begin
  454. if p.ops<>2 then
  455. internalerror(2017042702);
  456. regReadByInstruction := reginop(reg,p.oper[0]^) or
  457. (
  458. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  459. );
  460. exit;
  461. end;
  462. with insprop[p.opcode] do
  463. begin
  464. case getregtype(reg) of
  465. R_INTREGISTER:
  466. begin
  467. case getsupreg(reg) of
  468. RS_EAX:
  469. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  470. begin
  471. RegReadByInstruction := true;
  472. exit
  473. end;
  474. RS_ECX:
  475. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  476. begin
  477. RegReadByInstruction := true;
  478. exit
  479. end;
  480. RS_EDX:
  481. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  482. begin
  483. RegReadByInstruction := true;
  484. exit
  485. end;
  486. RS_EBX:
  487. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  488. begin
  489. RegReadByInstruction := true;
  490. exit
  491. end;
  492. RS_ESP:
  493. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  494. begin
  495. RegReadByInstruction := true;
  496. exit
  497. end;
  498. RS_EBP:
  499. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  500. begin
  501. RegReadByInstruction := true;
  502. exit
  503. end;
  504. RS_ESI:
  505. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  506. begin
  507. RegReadByInstruction := true;
  508. exit
  509. end;
  510. RS_EDI:
  511. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  512. begin
  513. RegReadByInstruction := true;
  514. exit
  515. end;
  516. end;
  517. end;
  518. R_MMREGISTER:
  519. begin
  520. case getsupreg(reg) of
  521. RS_XMM0:
  522. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  523. begin
  524. RegReadByInstruction := true;
  525. exit
  526. end;
  527. end;
  528. end;
  529. else
  530. ;
  531. end;
  532. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  533. begin
  534. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  535. begin
  536. case p.condition of
  537. C_A,C_NBE, { CF=0 and ZF=0 }
  538. C_BE,C_NA: { CF=1 or ZF=1 }
  539. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  540. C_AE,C_NB,C_NC, { CF=0 }
  541. C_B,C_NAE,C_C: { CF=1 }
  542. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  543. C_NE,C_NZ, { ZF=0 }
  544. C_E,C_Z: { ZF=1 }
  545. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  546. C_G,C_NLE, { ZF=0 and SF=OF }
  547. C_LE,C_NG: { ZF=1 or SF<>OF }
  548. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  549. C_GE,C_NL, { SF=OF }
  550. C_L,C_NGE: { SF<>OF }
  551. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  552. C_NO, { OF=0 }
  553. C_O: { OF=1 }
  554. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  555. C_NP,C_PO, { PF=0 }
  556. C_P,C_PE: { PF=1 }
  557. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  558. C_NS, { SF=0 }
  559. C_S: { SF=1 }
  560. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  561. else
  562. internalerror(2017042701);
  563. end;
  564. if RegReadByInstruction then
  565. exit;
  566. end;
  567. case getsubreg(reg) of
  568. R_SUBW,R_SUBD,R_SUBQ:
  569. RegReadByInstruction :=
  570. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  571. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  572. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  573. R_SUBFLAGCARRY:
  574. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  575. R_SUBFLAGPARITY:
  576. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  577. R_SUBFLAGAUXILIARY:
  578. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  579. R_SUBFLAGZERO:
  580. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  581. R_SUBFLAGSIGN:
  582. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  583. R_SUBFLAGOVERFLOW:
  584. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  585. R_SUBFLAGINTERRUPT:
  586. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  587. R_SUBFLAGDIRECTION:
  588. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  589. else
  590. internalerror(2017042601);
  591. end;
  592. exit;
  593. end;
  594. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  595. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  596. (p.oper[0]^.reg=p.oper[1]^.reg) then
  597. exit;
  598. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  599. begin
  600. RegReadByInstruction := true;
  601. exit
  602. end;
  603. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  604. begin
  605. RegReadByInstruction := true;
  606. exit
  607. end;
  608. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  609. begin
  610. RegReadByInstruction := true;
  611. exit
  612. end;
  613. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  614. begin
  615. RegReadByInstruction := true;
  616. exit
  617. end;
  618. end;
  619. end;
  620. end;
  621. end;
  622. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  623. begin
  624. result:=false;
  625. if p1.typ<>ait_instruction then
  626. exit;
  627. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  628. exit(true);
  629. if (getregtype(reg)=R_INTREGISTER) and
  630. { change information for xmm movsd are not correct }
  631. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  632. begin
  633. case getsupreg(reg) of
  634. { RS_EAX = RS_RAX on x86-64 }
  635. RS_EAX:
  636. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. RS_ECX:
  638. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. RS_EDX:
  640. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. RS_EBX:
  642. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. RS_ESP:
  644. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. RS_EBP:
  646. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. RS_ESI:
  648. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  649. RS_EDI:
  650. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  651. else
  652. ;
  653. end;
  654. if result then
  655. exit;
  656. end
  657. else if getregtype(reg)=R_MMREGISTER then
  658. begin
  659. case getsupreg(reg) of
  660. RS_XMM0:
  661. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  662. else
  663. ;
  664. end;
  665. if result then
  666. exit;
  667. end
  668. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  669. begin
  670. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  671. exit(true);
  672. case getsubreg(reg) of
  673. R_SUBFLAGCARRY:
  674. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  675. R_SUBFLAGPARITY:
  676. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  677. R_SUBFLAGAUXILIARY:
  678. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  679. R_SUBFLAGZERO:
  680. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  681. R_SUBFLAGSIGN:
  682. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. R_SUBFLAGOVERFLOW:
  684. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  685. R_SUBFLAGINTERRUPT:
  686. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  687. R_SUBFLAGDIRECTION:
  688. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  689. R_SUBW,R_SUBD,R_SUBQ:
  690. { Everything except the direction bits }
  691. Result:=
  692. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  693. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  694. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  695. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  696. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  697. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  698. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  699. else
  700. ;
  701. end;
  702. if result then
  703. exit;
  704. end
  705. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  706. exit(true);
  707. Result:=inherited RegInInstruction(Reg, p1);
  708. end;
  709. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  710. const
  711. WriteOps: array[0..3] of set of TInsChange =
  712. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  713. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  714. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  715. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  716. var
  717. OperIdx: Integer;
  718. begin
  719. Result := False;
  720. if p1.typ <> ait_instruction then
  721. exit;
  722. with insprop[taicpu(p1).opcode] do
  723. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  724. begin
  725. case getsubreg(reg) of
  726. R_SUBW,R_SUBD,R_SUBQ:
  727. Result :=
  728. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  729. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  730. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  731. R_SUBFLAGCARRY:
  732. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  733. R_SUBFLAGPARITY:
  734. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  735. R_SUBFLAGAUXILIARY:
  736. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  737. R_SUBFLAGZERO:
  738. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  739. R_SUBFLAGSIGN:
  740. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  741. R_SUBFLAGOVERFLOW:
  742. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  743. R_SUBFLAGINTERRUPT:
  744. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  745. R_SUBFLAGDIRECTION:
  746. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  747. else
  748. internalerror(2017042602);
  749. end;
  750. exit;
  751. end;
  752. case taicpu(p1).opcode of
  753. A_CALL:
  754. { We could potentially set Result to False if the register in
  755. question is non-volatile for the subroutine's calling convention,
  756. but this would require detecting the calling convention in use and
  757. also assuming that the routine doesn't contain malformed assembly
  758. language, for example... so it could only be done under -O4 as it
  759. would be considered a side-effect. [Kit] }
  760. Result := True;
  761. A_MOVSD:
  762. { special handling for SSE MOVSD }
  763. if (taicpu(p1).ops>0) then
  764. begin
  765. if taicpu(p1).ops<>2 then
  766. internalerror(2017042703);
  767. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  768. end;
  769. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  770. so fix it here (FK)
  771. }
  772. A_VMOVSS,
  773. A_VMOVSD:
  774. begin
  775. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  776. exit;
  777. end;
  778. A_IMUL:
  779. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  780. else
  781. ;
  782. end;
  783. if Result then
  784. exit;
  785. with insprop[taicpu(p1).opcode] do
  786. begin
  787. if getregtype(reg)=R_INTREGISTER then
  788. begin
  789. case getsupreg(reg) of
  790. RS_EAX:
  791. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  792. begin
  793. Result := True;
  794. exit
  795. end;
  796. RS_ECX:
  797. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  798. begin
  799. Result := True;
  800. exit
  801. end;
  802. RS_EDX:
  803. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  804. begin
  805. Result := True;
  806. exit
  807. end;
  808. RS_EBX:
  809. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  810. begin
  811. Result := True;
  812. exit
  813. end;
  814. RS_ESP:
  815. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  816. begin
  817. Result := True;
  818. exit
  819. end;
  820. RS_EBP:
  821. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  822. begin
  823. Result := True;
  824. exit
  825. end;
  826. RS_ESI:
  827. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  828. begin
  829. Result := True;
  830. exit
  831. end;
  832. RS_EDI:
  833. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  834. begin
  835. Result := True;
  836. exit
  837. end;
  838. end;
  839. end;
  840. for OperIdx := 0 to taicpu(p1).ops - 1 do
  841. if (WriteOps[OperIdx]*Ch<>[]) and
  842. { The register doesn't get modified inside a reference }
  843. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  844. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  845. begin
  846. Result := true;
  847. exit
  848. end;
  849. end;
  850. end;
  851. {$ifdef DEBUG_AOPTCPU}
  852. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  853. begin
  854. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  855. end;
  856. function debug_tostr(i: tcgint): string; inline;
  857. begin
  858. Result := tostr(i);
  859. end;
  860. function debug_regname(r: TRegister): string; inline;
  861. begin
  862. Result := '%' + std_regname(r);
  863. end;
  864. { Debug output function - creates a string representation of an operator }
  865. function debug_operstr(oper: TOper): string;
  866. begin
  867. case oper.typ of
  868. top_const:
  869. Result := '$' + debug_tostr(oper.val);
  870. top_reg:
  871. Result := debug_regname(oper.reg);
  872. top_ref:
  873. begin
  874. if oper.ref^.offset <> 0 then
  875. Result := debug_tostr(oper.ref^.offset) + '('
  876. else
  877. Result := '(';
  878. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  879. begin
  880. Result := Result + debug_regname(oper.ref^.base);
  881. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  882. Result := Result + ',' + debug_regname(oper.ref^.index);
  883. end
  884. else
  885. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  886. Result := Result + debug_regname(oper.ref^.index);
  887. if (oper.ref^.scalefactor > 1) then
  888. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  889. else
  890. Result := Result + ')';
  891. end;
  892. else
  893. Result := '[UNKNOWN]';
  894. end;
  895. end;
  896. function debug_op2str(opcode: tasmop): string; inline;
  897. begin
  898. Result := std_op2str[opcode];
  899. end;
  900. function debug_opsize2str(opsize: topsize): string; inline;
  901. begin
  902. Result := gas_opsize2str[opsize];
  903. end;
  904. {$else DEBUG_AOPTCPU}
  905. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  906. begin
  907. end;
  908. function debug_tostr(i: tcgint): string; inline;
  909. begin
  910. Result := '';
  911. end;
  912. function debug_regname(r: TRegister): string; inline;
  913. begin
  914. Result := '';
  915. end;
  916. function debug_operstr(oper: TOper): string; inline;
  917. begin
  918. Result := '';
  919. end;
  920. function debug_op2str(opcode: tasmop): string; inline;
  921. begin
  922. Result := '';
  923. end;
  924. function debug_opsize2str(opsize: topsize): string; inline;
  925. begin
  926. Result := '';
  927. end;
  928. {$endif DEBUG_AOPTCPU}
  929. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  930. begin
  931. {$ifdef x86_64}
  932. { Always fine on x86-64 }
  933. Result := True;
  934. {$else x86_64}
  935. Result :=
  936. {$ifdef i8086}
  937. (current_settings.cputype >= cpu_386) and
  938. {$endif i8086}
  939. (
  940. { Always accept if optimising for size }
  941. (cs_opt_size in current_settings.optimizerswitches) or
  942. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  943. (current_settings.optimizecputype >= cpu_Pentium2)
  944. );
  945. {$endif x86_64}
  946. end;
  947. { Attempts to allocate a volatile integer register for use between p and hp,
  948. using AUsedRegs for the current register usage information. Returns NR_NO
  949. if no free register could be found }
  950. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  951. var
  952. RegSet: TCPURegisterSet;
  953. CurrentSuperReg: Integer;
  954. CurrentReg: TRegister;
  955. Currentp: tai;
  956. Breakout: Boolean;
  957. begin
  958. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  959. Result := NR_NO;
  960. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  961. for CurrentSuperReg in RegSet do
  962. begin
  963. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  964. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg) then
  965. begin
  966. Currentp := p;
  967. Breakout := False;
  968. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  969. begin
  970. case Currentp.typ of
  971. ait_instruction:
  972. begin
  973. if RegInInstruction(CurrentReg, Currentp) then
  974. begin
  975. Breakout := True;
  976. Break;
  977. end;
  978. { Cannot allocate across an unconditional jump }
  979. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  980. Exit;
  981. end;
  982. ait_marker:
  983. { Don't try anything more if a marker is hit }
  984. Exit;
  985. ait_regalloc:
  986. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  987. begin
  988. Breakout := True;
  989. Break;
  990. end;
  991. else
  992. ;
  993. end;
  994. end;
  995. if Breakout then
  996. { Try the next register }
  997. Continue;
  998. { We have a free register available }
  999. Result := CurrentReg;
  1000. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1001. Exit;
  1002. end;
  1003. end;
  1004. end;
  1005. { Attempts to allocate a volatile MM register for use between p and hp,
  1006. using AUsedRegs for the current register usage information. Returns NR_NO
  1007. if no free register could be found }
  1008. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1009. var
  1010. RegSet: TCPURegisterSet;
  1011. CurrentSuperReg: Integer;
  1012. CurrentReg: TRegister;
  1013. Currentp: tai;
  1014. Breakout: Boolean;
  1015. begin
  1016. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1017. Result := NR_NO;
  1018. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1019. for CurrentSuperReg in RegSet do
  1020. begin
  1021. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1022. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1023. begin
  1024. Currentp := p;
  1025. Breakout := False;
  1026. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1027. begin
  1028. case Currentp.typ of
  1029. ait_instruction:
  1030. begin
  1031. if RegInInstruction(CurrentReg, Currentp) then
  1032. begin
  1033. Breakout := True;
  1034. Break;
  1035. end;
  1036. { Cannot allocate across an unconditional jump }
  1037. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1038. Exit;
  1039. end;
  1040. ait_marker:
  1041. { Don't try anything more if a marker is hit }
  1042. Exit;
  1043. ait_regalloc:
  1044. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1045. begin
  1046. Breakout := True;
  1047. Break;
  1048. end;
  1049. else
  1050. ;
  1051. end;
  1052. end;
  1053. if Breakout then
  1054. { Try the next register }
  1055. Continue;
  1056. { We have a free register available }
  1057. Result := CurrentReg;
  1058. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1059. Exit;
  1060. end;
  1061. end;
  1062. end;
  1063. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1064. begin
  1065. if not SuperRegistersEqual(reg1,reg2) then
  1066. exit(false);
  1067. if getregtype(reg1)<>R_INTREGISTER then
  1068. exit(true); {because SuperRegisterEqual is true}
  1069. case getsubreg(reg1) of
  1070. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1071. higher, it preserves the high bits, so the new value depends on
  1072. reg2's previous value. In other words, it is equivalent to doing:
  1073. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1074. R_SUBL:
  1075. exit(getsubreg(reg2)=R_SUBL);
  1076. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1077. higher, it actually does a:
  1078. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1079. R_SUBH:
  1080. exit(getsubreg(reg2)=R_SUBH);
  1081. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1082. bits of reg2:
  1083. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1084. R_SUBW:
  1085. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1086. { a write to R_SUBD always overwrites every other subregister,
  1087. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1088. R_SUBD,
  1089. R_SUBQ:
  1090. exit(true);
  1091. else
  1092. internalerror(2017042801);
  1093. end;
  1094. end;
  1095. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1096. begin
  1097. if not SuperRegistersEqual(reg1,reg2) then
  1098. exit(false);
  1099. if getregtype(reg1)<>R_INTREGISTER then
  1100. exit(true); {because SuperRegisterEqual is true}
  1101. case getsubreg(reg1) of
  1102. R_SUBL:
  1103. exit(getsubreg(reg2)<>R_SUBH);
  1104. R_SUBH:
  1105. exit(getsubreg(reg2)<>R_SUBL);
  1106. R_SUBW,
  1107. R_SUBD,
  1108. R_SUBQ:
  1109. exit(true);
  1110. else
  1111. internalerror(2017042802);
  1112. end;
  1113. end;
  1114. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1115. var
  1116. hp1 : tai;
  1117. l : TCGInt;
  1118. begin
  1119. result:=false;
  1120. { changes the code sequence
  1121. shr/sar const1, x
  1122. shl const2, x
  1123. to
  1124. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1125. if GetNextInstruction(p, hp1) and
  1126. MatchInstruction(hp1,A_SHL,[]) and
  1127. (taicpu(p).oper[0]^.typ = top_const) and
  1128. (taicpu(hp1).oper[0]^.typ = top_const) and
  1129. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1130. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1131. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1132. begin
  1133. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1134. not(cs_opt_size in current_settings.optimizerswitches) then
  1135. begin
  1136. { shr/sar const1, %reg
  1137. shl const2, %reg
  1138. with const1 > const2 }
  1139. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1140. taicpu(hp1).opcode := A_AND;
  1141. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1142. case taicpu(p).opsize Of
  1143. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1144. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1145. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1146. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1147. else
  1148. Internalerror(2017050703)
  1149. end;
  1150. end
  1151. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1152. not(cs_opt_size in current_settings.optimizerswitches) then
  1153. begin
  1154. { shr/sar const1, %reg
  1155. shl const2, %reg
  1156. with const1 < const2 }
  1157. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1158. taicpu(p).opcode := A_AND;
  1159. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1160. case taicpu(p).opsize Of
  1161. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1162. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1163. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1164. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1165. else
  1166. Internalerror(2017050702)
  1167. end;
  1168. end
  1169. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1170. begin
  1171. { shr/sar const1, %reg
  1172. shl const2, %reg
  1173. with const1 = const2 }
  1174. taicpu(p).opcode := A_AND;
  1175. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1176. case taicpu(p).opsize Of
  1177. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1178. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1179. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1180. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1181. else
  1182. Internalerror(2017050701)
  1183. end;
  1184. RemoveInstruction(hp1);
  1185. end;
  1186. end;
  1187. end;
  1188. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1189. var
  1190. opsize : topsize;
  1191. hp1 : tai;
  1192. tmpref : treference;
  1193. ShiftValue : Cardinal;
  1194. BaseValue : TCGInt;
  1195. begin
  1196. result:=false;
  1197. opsize:=taicpu(p).opsize;
  1198. { changes certain "imul const, %reg"'s to lea sequences }
  1199. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1200. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1201. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1202. if (taicpu(p).oper[0]^.val = 1) then
  1203. if (taicpu(p).ops = 2) then
  1204. { remove "imul $1, reg" }
  1205. begin
  1206. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1207. Result := RemoveCurrentP(p);
  1208. end
  1209. else
  1210. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1211. begin
  1212. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1213. InsertLLItem(p.previous, p.next, hp1);
  1214. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1215. p.free;
  1216. p := hp1;
  1217. end
  1218. else if ((taicpu(p).ops <= 2) or
  1219. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1220. not(cs_opt_size in current_settings.optimizerswitches) and
  1221. (not(GetNextInstruction(p, hp1)) or
  1222. not((tai(hp1).typ = ait_instruction) and
  1223. ((taicpu(hp1).opcode=A_Jcc) and
  1224. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1225. begin
  1226. {
  1227. imul X, reg1, reg2 to
  1228. lea (reg1,reg1,Y), reg2
  1229. shl ZZ,reg2
  1230. imul XX, reg1 to
  1231. lea (reg1,reg1,YY), reg1
  1232. shl ZZ,reg2
  1233. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1234. it does not exist as a separate optimization target in FPC though.
  1235. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1236. at most two zeros
  1237. }
  1238. reference_reset(tmpref,1,[]);
  1239. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1240. begin
  1241. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1242. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1243. TmpRef.base := taicpu(p).oper[1]^.reg;
  1244. TmpRef.index := taicpu(p).oper[1]^.reg;
  1245. if not(BaseValue in [3,5,9]) then
  1246. Internalerror(2018110101);
  1247. TmpRef.ScaleFactor := BaseValue-1;
  1248. if (taicpu(p).ops = 2) then
  1249. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1250. else
  1251. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1252. AsmL.InsertAfter(hp1,p);
  1253. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1254. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1255. RemoveCurrentP(p, hp1);
  1256. if ShiftValue>0 then
  1257. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1258. end;
  1259. end;
  1260. end;
  1261. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1262. begin
  1263. Result := False;
  1264. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1265. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1266. begin
  1267. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1268. taicpu(p).opcode := A_MOV;
  1269. Result := True;
  1270. end;
  1271. end;
  1272. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1273. var
  1274. p: taicpu absolute hp;
  1275. i: Integer;
  1276. begin
  1277. Result := False;
  1278. if not assigned(hp) or
  1279. (hp.typ <> ait_instruction) then
  1280. Exit;
  1281. // p := taicpu(hp);
  1282. Prefetch(insprop[p.opcode]);
  1283. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1284. with insprop[p.opcode] do
  1285. begin
  1286. case getsubreg(reg) of
  1287. R_SUBW,R_SUBD,R_SUBQ:
  1288. Result:=
  1289. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1290. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1291. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1292. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1293. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1294. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1295. R_SUBFLAGCARRY:
  1296. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1297. R_SUBFLAGPARITY:
  1298. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1299. R_SUBFLAGAUXILIARY:
  1300. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1301. R_SUBFLAGZERO:
  1302. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1303. R_SUBFLAGSIGN:
  1304. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1305. R_SUBFLAGOVERFLOW:
  1306. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1307. R_SUBFLAGINTERRUPT:
  1308. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1309. R_SUBFLAGDIRECTION:
  1310. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1311. else
  1312. begin
  1313. writeln(getsubreg(reg));
  1314. internalerror(2017050501);
  1315. end;
  1316. end;
  1317. exit;
  1318. end;
  1319. { Handle special cases first }
  1320. case p.opcode of
  1321. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1322. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1323. begin
  1324. Result :=
  1325. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1326. (p.oper[1]^.typ = top_reg) and
  1327. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1328. (
  1329. (p.oper[0]^.typ = top_const) or
  1330. (
  1331. (p.oper[0]^.typ = top_reg) and
  1332. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1333. ) or (
  1334. (p.oper[0]^.typ = top_ref) and
  1335. not RegInRef(reg,p.oper[0]^.ref^)
  1336. )
  1337. );
  1338. end;
  1339. A_MUL, A_IMUL:
  1340. Result :=
  1341. (
  1342. (p.ops=3) and { IMUL only }
  1343. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1344. (
  1345. (
  1346. (p.oper[1]^.typ=top_reg) and
  1347. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1348. ) or (
  1349. (p.oper[1]^.typ=top_ref) and
  1350. not RegInRef(reg,p.oper[1]^.ref^)
  1351. )
  1352. )
  1353. ) or (
  1354. (
  1355. (p.ops=1) and
  1356. (
  1357. (
  1358. (
  1359. (p.oper[0]^.typ=top_reg) and
  1360. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1361. )
  1362. ) or (
  1363. (p.oper[0]^.typ=top_ref) and
  1364. not RegInRef(reg,p.oper[0]^.ref^)
  1365. )
  1366. ) and (
  1367. (
  1368. (p.opsize=S_B) and
  1369. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1370. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1371. ) or (
  1372. (p.opsize=S_W) and
  1373. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1374. ) or (
  1375. (p.opsize=S_L) and
  1376. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1377. {$ifdef x86_64}
  1378. ) or (
  1379. (p.opsize=S_Q) and
  1380. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1381. {$endif x86_64}
  1382. )
  1383. )
  1384. )
  1385. );
  1386. A_CBW:
  1387. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1388. {$ifndef x86_64}
  1389. A_LDS:
  1390. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1391. A_LES:
  1392. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1393. {$endif not x86_64}
  1394. A_LFS:
  1395. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1396. A_LGS:
  1397. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1398. A_LSS:
  1399. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1401. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1402. A_LODSB:
  1403. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1404. A_LODSW:
  1405. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1406. {$ifdef x86_64}
  1407. A_LODSQ:
  1408. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1409. {$endif x86_64}
  1410. A_LODSD:
  1411. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1412. A_FSTSW, A_FNSTSW:
  1413. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1414. else
  1415. begin
  1416. with insprop[p.opcode] do
  1417. begin
  1418. if (
  1419. { xor %reg,%reg etc. is classed as a new value }
  1420. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1421. MatchOpType(p, top_reg, top_reg) and
  1422. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1423. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1424. ) then
  1425. begin
  1426. Result := True;
  1427. Exit;
  1428. end;
  1429. { Make sure the entire register is overwritten }
  1430. if (getregtype(reg) = R_INTREGISTER) then
  1431. begin
  1432. if (p.ops > 0) then
  1433. begin
  1434. if RegInOp(reg, p.oper[0]^) then
  1435. begin
  1436. if (p.oper[0]^.typ = top_ref) then
  1437. begin
  1438. if RegInRef(reg, p.oper[0]^.ref^) then
  1439. begin
  1440. Result := False;
  1441. Exit;
  1442. end;
  1443. end
  1444. else if (p.oper[0]^.typ = top_reg) then
  1445. begin
  1446. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1447. begin
  1448. Result := False;
  1449. Exit;
  1450. end
  1451. else if ([Ch_WOp1]*Ch<>[]) then
  1452. begin
  1453. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1454. Result := True
  1455. else
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end;
  1460. end;
  1461. end;
  1462. end;
  1463. if (p.ops > 1) then
  1464. begin
  1465. if RegInOp(reg, p.oper[1]^) then
  1466. begin
  1467. if (p.oper[1]^.typ = top_ref) then
  1468. begin
  1469. if RegInRef(reg, p.oper[1]^.ref^) then
  1470. begin
  1471. Result := False;
  1472. Exit;
  1473. end;
  1474. end
  1475. else if (p.oper[1]^.typ = top_reg) then
  1476. begin
  1477. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1478. begin
  1479. Result := False;
  1480. Exit;
  1481. end
  1482. else if ([Ch_WOp2]*Ch<>[]) then
  1483. begin
  1484. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1485. Result := True
  1486. else
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end;
  1491. end;
  1492. end;
  1493. end;
  1494. if (p.ops > 2) then
  1495. begin
  1496. if RegInOp(reg, p.oper[2]^) then
  1497. begin
  1498. if (p.oper[2]^.typ = top_ref) then
  1499. begin
  1500. if RegInRef(reg, p.oper[2]^.ref^) then
  1501. begin
  1502. Result := False;
  1503. Exit;
  1504. end;
  1505. end
  1506. else if (p.oper[2]^.typ = top_reg) then
  1507. begin
  1508. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1509. begin
  1510. Result := False;
  1511. Exit;
  1512. end
  1513. else if ([Ch_WOp3]*Ch<>[]) then
  1514. begin
  1515. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1516. Result := True
  1517. else
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end;
  1522. end;
  1523. end;
  1524. end;
  1525. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1526. begin
  1527. if (p.oper[3]^.typ = top_ref) then
  1528. begin
  1529. if RegInRef(reg, p.oper[3]^.ref^) then
  1530. begin
  1531. Result := False;
  1532. Exit;
  1533. end;
  1534. end
  1535. else if (p.oper[3]^.typ = top_reg) then
  1536. begin
  1537. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1538. begin
  1539. Result := False;
  1540. Exit;
  1541. end
  1542. else if ([Ch_WOp4]*Ch<>[]) then
  1543. begin
  1544. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1545. Result := True
  1546. else
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end;
  1551. end;
  1552. end;
  1553. end;
  1554. end;
  1555. end;
  1556. end;
  1557. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1558. case getsupreg(reg) of
  1559. RS_EAX:
  1560. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1561. begin
  1562. Result := True;
  1563. Exit;
  1564. end;
  1565. RS_ECX:
  1566. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1567. begin
  1568. Result := True;
  1569. Exit;
  1570. end;
  1571. RS_EDX:
  1572. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1573. begin
  1574. Result := True;
  1575. Exit;
  1576. end;
  1577. RS_EBX:
  1578. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1579. begin
  1580. Result := True;
  1581. Exit;
  1582. end;
  1583. RS_ESP:
  1584. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1585. begin
  1586. Result := True;
  1587. Exit;
  1588. end;
  1589. RS_EBP:
  1590. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1591. begin
  1592. Result := True;
  1593. Exit;
  1594. end;
  1595. RS_ESI:
  1596. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1597. begin
  1598. Result := True;
  1599. Exit;
  1600. end;
  1601. RS_EDI:
  1602. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1603. begin
  1604. Result := True;
  1605. Exit;
  1606. end;
  1607. else
  1608. ;
  1609. end;
  1610. end;
  1611. end;
  1612. end;
  1613. end;
  1614. end;
  1615. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1616. var
  1617. hp2,hp3 : tai;
  1618. begin
  1619. { some x86-64 issue a NOP before the real exit code }
  1620. if MatchInstruction(p,A_NOP,[]) then
  1621. GetNextInstruction(p,p);
  1622. result:=assigned(p) and (p.typ=ait_instruction) and
  1623. ((taicpu(p).opcode = A_RET) or
  1624. ((taicpu(p).opcode=A_LEAVE) and
  1625. GetNextInstruction(p,hp2) and
  1626. MatchInstruction(hp2,A_RET,[S_NO])
  1627. ) or
  1628. (((taicpu(p).opcode=A_LEA) and
  1629. MatchOpType(taicpu(p),top_ref,top_reg) and
  1630. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1631. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1632. ) and
  1633. GetNextInstruction(p,hp2) and
  1634. MatchInstruction(hp2,A_RET,[S_NO])
  1635. ) or
  1636. ((((taicpu(p).opcode=A_MOV) and
  1637. MatchOpType(taicpu(p),top_reg,top_reg) and
  1638. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1639. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1640. ((taicpu(p).opcode=A_LEA) and
  1641. MatchOpType(taicpu(p),top_ref,top_reg) and
  1642. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1643. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1644. )
  1645. ) and
  1646. GetNextInstruction(p,hp2) and
  1647. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1648. MatchOpType(taicpu(hp2),top_reg) and
  1649. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1650. GetNextInstruction(hp2,hp3) and
  1651. MatchInstruction(hp3,A_RET,[S_NO])
  1652. )
  1653. );
  1654. end;
  1655. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1656. begin
  1657. isFoldableArithOp := False;
  1658. case hp1.opcode of
  1659. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1660. isFoldableArithOp :=
  1661. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1662. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1663. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1664. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1665. (taicpu(hp1).oper[1]^.reg = reg);
  1666. A_INC,A_DEC,A_NEG,A_NOT:
  1667. isFoldableArithOp :=
  1668. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1669. (taicpu(hp1).oper[0]^.reg = reg);
  1670. else
  1671. ;
  1672. end;
  1673. end;
  1674. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1675. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1676. var
  1677. hp2: tai;
  1678. begin
  1679. hp2 := p;
  1680. repeat
  1681. hp2 := tai(hp2.previous);
  1682. if assigned(hp2) and
  1683. (hp2.typ = ait_regalloc) and
  1684. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1685. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1686. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1687. begin
  1688. RemoveInstruction(hp2);
  1689. break;
  1690. end;
  1691. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1692. end;
  1693. begin
  1694. case current_procinfo.procdef.returndef.typ of
  1695. arraydef,recorddef,pointerdef,
  1696. stringdef,enumdef,procdef,objectdef,errordef,
  1697. filedef,setdef,procvardef,
  1698. classrefdef,forwarddef:
  1699. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1700. orddef:
  1701. if current_procinfo.procdef.returndef.size <> 0 then
  1702. begin
  1703. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1704. { for int64/qword }
  1705. if current_procinfo.procdef.returndef.size = 8 then
  1706. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1707. end;
  1708. else
  1709. ;
  1710. end;
  1711. end;
  1712. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1713. var
  1714. hp1,hp2 : tai;
  1715. begin
  1716. result:=false;
  1717. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1718. begin
  1719. { vmova* reg1,reg1
  1720. =>
  1721. <nop> }
  1722. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1723. begin
  1724. RemoveCurrentP(p);
  1725. result:=true;
  1726. exit;
  1727. end
  1728. else if GetNextInstruction(p,hp1) then
  1729. begin
  1730. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1731. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1732. begin
  1733. { vmova* reg1,reg2
  1734. vmova* reg2,reg3
  1735. dealloc reg2
  1736. =>
  1737. vmova* reg1,reg3 }
  1738. TransferUsedRegs(TmpUsedRegs);
  1739. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1740. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1741. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1742. begin
  1743. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1744. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1745. RemoveInstruction(hp1);
  1746. result:=true;
  1747. exit;
  1748. end
  1749. { special case:
  1750. vmova* reg1,<op>
  1751. vmova* <op>,reg1
  1752. =>
  1753. vmova* reg1,<op> }
  1754. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1755. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1756. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1757. ) then
  1758. begin
  1759. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1760. RemoveInstruction(hp1);
  1761. result:=true;
  1762. exit;
  1763. end
  1764. end
  1765. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1766. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1767. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1768. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1769. ) and
  1770. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1771. begin
  1772. { vmova* reg1,reg2
  1773. vmovs* reg2,<op>
  1774. dealloc reg2
  1775. =>
  1776. vmovs* reg1,reg3 }
  1777. TransferUsedRegs(TmpUsedRegs);
  1778. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1779. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1780. begin
  1781. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1782. taicpu(p).opcode:=taicpu(hp1).opcode;
  1783. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1784. RemoveInstruction(hp1);
  1785. result:=true;
  1786. exit;
  1787. end
  1788. end;
  1789. end;
  1790. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1791. begin
  1792. if MatchInstruction(hp1,[A_VFMADDPD,
  1793. A_VFMADD132PD,
  1794. A_VFMADD132PS,
  1795. A_VFMADD132SD,
  1796. A_VFMADD132SS,
  1797. A_VFMADD213PD,
  1798. A_VFMADD213PS,
  1799. A_VFMADD213SD,
  1800. A_VFMADD213SS,
  1801. A_VFMADD231PD,
  1802. A_VFMADD231PS,
  1803. A_VFMADD231SD,
  1804. A_VFMADD231SS,
  1805. A_VFMADDSUB132PD,
  1806. A_VFMADDSUB132PS,
  1807. A_VFMADDSUB213PD,
  1808. A_VFMADDSUB213PS,
  1809. A_VFMADDSUB231PD,
  1810. A_VFMADDSUB231PS,
  1811. A_VFMSUB132PD,
  1812. A_VFMSUB132PS,
  1813. A_VFMSUB132SD,
  1814. A_VFMSUB132SS,
  1815. A_VFMSUB213PD,
  1816. A_VFMSUB213PS,
  1817. A_VFMSUB213SD,
  1818. A_VFMSUB213SS,
  1819. A_VFMSUB231PD,
  1820. A_VFMSUB231PS,
  1821. A_VFMSUB231SD,
  1822. A_VFMSUB231SS,
  1823. A_VFMSUBADD132PD,
  1824. A_VFMSUBADD132PS,
  1825. A_VFMSUBADD213PD,
  1826. A_VFMSUBADD213PS,
  1827. A_VFMSUBADD231PD,
  1828. A_VFMSUBADD231PS,
  1829. A_VFNMADD132PD,
  1830. A_VFNMADD132PS,
  1831. A_VFNMADD132SD,
  1832. A_VFNMADD132SS,
  1833. A_VFNMADD213PD,
  1834. A_VFNMADD213PS,
  1835. A_VFNMADD213SD,
  1836. A_VFNMADD213SS,
  1837. A_VFNMADD231PD,
  1838. A_VFNMADD231PS,
  1839. A_VFNMADD231SD,
  1840. A_VFNMADD231SS,
  1841. A_VFNMSUB132PD,
  1842. A_VFNMSUB132PS,
  1843. A_VFNMSUB132SD,
  1844. A_VFNMSUB132SS,
  1845. A_VFNMSUB213PD,
  1846. A_VFNMSUB213PS,
  1847. A_VFNMSUB213SD,
  1848. A_VFNMSUB213SS,
  1849. A_VFNMSUB231PD,
  1850. A_VFNMSUB231PS,
  1851. A_VFNMSUB231SD,
  1852. A_VFNMSUB231SS],[S_NO]) and
  1853. { we mix single and double opperations here because we assume that the compiler
  1854. generates vmovapd only after double operations and vmovaps only after single operations }
  1855. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1856. GetNextInstruction(hp1,hp2) and
  1857. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1858. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1859. begin
  1860. TransferUsedRegs(TmpUsedRegs);
  1861. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1862. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1863. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1864. begin
  1865. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1866. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1867. RemoveInstruction(hp2);
  1868. end;
  1869. end
  1870. else if (hp1.typ = ait_instruction) and
  1871. GetNextInstruction(hp1, hp2) and
  1872. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1873. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1874. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1875. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1876. (((taicpu(p).opcode=A_MOVAPS) and
  1877. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1878. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1879. ((taicpu(p).opcode=A_MOVAPD) and
  1880. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1881. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1882. ) then
  1883. { change
  1884. movapX reg,reg2
  1885. addsX/subsX/... reg3, reg2
  1886. movapX reg2,reg
  1887. to
  1888. addsX/subsX/... reg3,reg
  1889. }
  1890. begin
  1891. TransferUsedRegs(TmpUsedRegs);
  1892. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1893. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1894. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1895. begin
  1896. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1897. debug_op2str(taicpu(p).opcode)+' '+
  1898. debug_op2str(taicpu(hp1).opcode)+' '+
  1899. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1900. { we cannot eliminate the first move if
  1901. the operations uses the same register for source and dest }
  1902. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1903. RemoveCurrentP(p, nil);
  1904. p:=hp1;
  1905. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1906. RemoveInstruction(hp2);
  1907. result:=true;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. end;
  1913. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1914. var
  1915. hp1 : tai;
  1916. begin
  1917. result:=false;
  1918. { replace
  1919. V<Op>X %mreg1,%mreg2,%mreg3
  1920. VMovX %mreg3,%mreg4
  1921. dealloc %mreg3
  1922. by
  1923. V<Op>X %mreg1,%mreg2,%mreg4
  1924. ?
  1925. }
  1926. if GetNextInstruction(p,hp1) and
  1927. { we mix single and double operations here because we assume that the compiler
  1928. generates vmovapd only after double operations and vmovaps only after single operations }
  1929. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1930. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1931. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1932. begin
  1933. TransferUsedRegs(TmpUsedRegs);
  1934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1935. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1936. begin
  1937. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1938. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1939. RemoveInstruction(hp1);
  1940. result:=true;
  1941. end;
  1942. end;
  1943. end;
  1944. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1945. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1946. begin
  1947. Result := False;
  1948. { For safety reasons, only check for exact register matches }
  1949. { Check base register }
  1950. if (ref.base = AOldReg) then
  1951. begin
  1952. ref.base := ANewReg;
  1953. Result := True;
  1954. end;
  1955. { Check index register }
  1956. if (ref.index = AOldReg) then
  1957. begin
  1958. ref.index := ANewReg;
  1959. Result := True;
  1960. end;
  1961. end;
  1962. { Replaces all references to AOldReg in an operand to ANewReg }
  1963. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1964. var
  1965. OldSupReg, NewSupReg: TSuperRegister;
  1966. OldSubReg, NewSubReg: TSubRegister;
  1967. OldRegType: TRegisterType;
  1968. ThisOper: POper;
  1969. begin
  1970. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1971. Result := False;
  1972. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1973. InternalError(2020011801);
  1974. OldSupReg := getsupreg(AOldReg);
  1975. OldSubReg := getsubreg(AOldReg);
  1976. OldRegType := getregtype(AOldReg);
  1977. NewSupReg := getsupreg(ANewReg);
  1978. NewSubReg := getsubreg(ANewReg);
  1979. if OldRegType <> getregtype(ANewReg) then
  1980. InternalError(2020011802);
  1981. if OldSubReg <> NewSubReg then
  1982. InternalError(2020011803);
  1983. case ThisOper^.typ of
  1984. top_reg:
  1985. if (
  1986. (ThisOper^.reg = AOldReg) or
  1987. (
  1988. (OldRegType = R_INTREGISTER) and
  1989. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1990. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1991. (
  1992. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1993. {$ifndef x86_64}
  1994. and (
  1995. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1996. don't have an 8-bit representation }
  1997. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1998. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1999. )
  2000. {$endif x86_64}
  2001. )
  2002. )
  2003. ) then
  2004. begin
  2005. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2006. Result := True;
  2007. end;
  2008. top_ref:
  2009. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2010. Result := True;
  2011. else
  2012. ;
  2013. end;
  2014. end;
  2015. { Replaces all references to AOldReg in an instruction to ANewReg }
  2016. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2017. const
  2018. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2019. var
  2020. OperIdx: Integer;
  2021. begin
  2022. Result := False;
  2023. for OperIdx := 0 to p.ops - 1 do
  2024. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2025. begin
  2026. { The shift and rotate instructions can only use CL }
  2027. if not (
  2028. (OperIdx = 0) and
  2029. { This second condition just helps to avoid unnecessarily
  2030. calling MatchInstruction for 10 different opcodes }
  2031. (p.oper[0]^.reg = NR_CL) and
  2032. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2033. ) then
  2034. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2035. end
  2036. else if p.oper[OperIdx]^.typ = top_ref then
  2037. { It's okay to replace registers in references that get written to }
  2038. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2039. end;
  2040. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2041. begin
  2042. with ref^ do
  2043. Result :=
  2044. (index = NR_NO) and
  2045. (
  2046. {$ifdef x86_64}
  2047. (
  2048. (base = NR_RIP) and
  2049. (refaddr in [addr_pic, addr_pic_no_got])
  2050. ) or
  2051. {$endif x86_64}
  2052. (base = NR_STACK_POINTER_REG) or
  2053. (base = current_procinfo.framepointer)
  2054. );
  2055. end;
  2056. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2057. var
  2058. l: asizeint;
  2059. begin
  2060. Result := False;
  2061. { Should have been checked previously }
  2062. if p.opcode <> A_LEA then
  2063. InternalError(2020072501);
  2064. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2065. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2066. not(cs_opt_size in current_settings.optimizerswitches) then
  2067. exit;
  2068. with p.oper[0]^.ref^ do
  2069. begin
  2070. if (base <> p.oper[1]^.reg) or
  2071. (index <> NR_NO) or
  2072. assigned(symbol) then
  2073. exit;
  2074. l:=offset;
  2075. if (l=1) and UseIncDec then
  2076. begin
  2077. p.opcode:=A_INC;
  2078. p.loadreg(0,p.oper[1]^.reg);
  2079. p.ops:=1;
  2080. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2081. end
  2082. else if (l=-1) and UseIncDec then
  2083. begin
  2084. p.opcode:=A_DEC;
  2085. p.loadreg(0,p.oper[1]^.reg);
  2086. p.ops:=1;
  2087. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2088. end
  2089. else
  2090. begin
  2091. if (l<0) and (l<>-2147483648) then
  2092. begin
  2093. p.opcode:=A_SUB;
  2094. p.loadConst(0,-l);
  2095. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2096. end
  2097. else
  2098. begin
  2099. p.opcode:=A_ADD;
  2100. p.loadConst(0,l);
  2101. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2102. end;
  2103. end;
  2104. end;
  2105. Result := True;
  2106. end;
  2107. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2108. var
  2109. CurrentReg, ReplaceReg: TRegister;
  2110. begin
  2111. Result := False;
  2112. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2113. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2114. case hp.opcode of
  2115. A_FSTSW, A_FNSTSW,
  2116. A_IN, A_INS, A_OUT, A_OUTS,
  2117. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2118. { These routines have explicit operands, but they are restricted in
  2119. what they can be (e.g. IN and OUT can only read from AL, AX or
  2120. EAX. }
  2121. Exit;
  2122. A_IMUL:
  2123. begin
  2124. { The 1-operand version writes to implicit registers
  2125. The 2-operand version reads from the first operator, and reads
  2126. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2127. the 3-operand version reads from a register that it doesn't write to
  2128. }
  2129. case hp.ops of
  2130. 1:
  2131. if (
  2132. (
  2133. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2134. ) or
  2135. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2136. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2137. begin
  2138. Result := True;
  2139. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2140. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2141. end;
  2142. 2:
  2143. { Only modify the first parameter }
  2144. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2145. begin
  2146. Result := True;
  2147. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2148. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2149. end;
  2150. 3:
  2151. { Only modify the second parameter }
  2152. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2153. begin
  2154. Result := True;
  2155. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2156. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2157. end;
  2158. else
  2159. InternalError(2020012901);
  2160. end;
  2161. end;
  2162. else
  2163. if (hp.ops > 0) and
  2164. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2165. begin
  2166. Result := True;
  2167. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2168. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2169. end;
  2170. end;
  2171. end;
  2172. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2173. var
  2174. hp1, hp2, hp3: tai;
  2175. DoOptimisation, TempBool: Boolean;
  2176. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2177. begin
  2178. if taicpu(hp1).opcode = signed_movop then
  2179. begin
  2180. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2181. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2182. end
  2183. else
  2184. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2185. end;
  2186. var
  2187. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2188. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2189. NewSize: topsize;
  2190. CurrentReg, ActiveReg: TRegister;
  2191. SourceRef, TargetRef: TReference;
  2192. MovAligned, MovUnaligned: TAsmOp;
  2193. begin
  2194. Result:=false;
  2195. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2196. { remove mov reg1,reg1? }
  2197. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2198. then
  2199. begin
  2200. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2201. { take care of the register (de)allocs following p }
  2202. RemoveCurrentP(p, hp1);
  2203. Result:=true;
  2204. exit;
  2205. end;
  2206. { All the next optimisations require a next instruction }
  2207. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2208. Exit;
  2209. { Look for:
  2210. mov %reg1,%reg2
  2211. ??? %reg2,r/m
  2212. Change to:
  2213. mov %reg1,%reg2
  2214. ??? %reg1,r/m
  2215. }
  2216. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2217. begin
  2218. CurrentReg := taicpu(p).oper[1]^.reg;
  2219. if RegReadByInstruction(CurrentReg, hp1) and
  2220. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2221. begin
  2222. { A change has occurred, just not in p }
  2223. Result := True;
  2224. TransferUsedRegs(TmpUsedRegs);
  2225. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2226. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2227. { Just in case something didn't get modified (e.g. an
  2228. implicit register) }
  2229. not RegReadByInstruction(CurrentReg, hp1) then
  2230. begin
  2231. { We can remove the original MOV }
  2232. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2233. RemoveCurrentp(p, hp1);
  2234. { UsedRegs got updated by RemoveCurrentp }
  2235. Result := True;
  2236. Exit;
  2237. end;
  2238. { If we know a MOV instruction has become a null operation, we might as well
  2239. get rid of it now to save time. }
  2240. if (taicpu(hp1).opcode = A_MOV) and
  2241. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2242. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2243. { Just being a register is enough to confirm it's a null operation }
  2244. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2245. begin
  2246. Result := True;
  2247. { Speed-up to reduce a pipeline stall... if we had something like...
  2248. movl %eax,%edx
  2249. movw %dx,%ax
  2250. ... the second instruction would change to movw %ax,%ax, but
  2251. given that it is now %ax that's active rather than %eax,
  2252. penalties might occur due to a partial register write, so instead,
  2253. change it to a MOVZX instruction when optimising for speed.
  2254. }
  2255. if not (cs_opt_size in current_settings.optimizerswitches) and
  2256. IsMOVZXAcceptable and
  2257. (taicpu(hp1).opsize < taicpu(p).opsize)
  2258. {$ifdef x86_64}
  2259. { operations already implicitly set the upper 64 bits to zero }
  2260. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2261. {$endif x86_64}
  2262. then
  2263. begin
  2264. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2265. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2266. case taicpu(p).opsize of
  2267. S_W:
  2268. if taicpu(hp1).opsize = S_B then
  2269. taicpu(hp1).opsize := S_BL
  2270. else
  2271. InternalError(2020012911);
  2272. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2273. case taicpu(hp1).opsize of
  2274. S_B:
  2275. taicpu(hp1).opsize := S_BL;
  2276. S_W:
  2277. taicpu(hp1).opsize := S_WL;
  2278. else
  2279. InternalError(2020012912);
  2280. end;
  2281. else
  2282. InternalError(2020012910);
  2283. end;
  2284. taicpu(hp1).opcode := A_MOVZX;
  2285. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2286. end
  2287. else
  2288. begin
  2289. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2290. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2291. RemoveInstruction(hp1);
  2292. { The instruction after what was hp1 is now the immediate next instruction,
  2293. so we can continue to make optimisations if it's present }
  2294. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2295. Exit;
  2296. hp1 := hp2;
  2297. end;
  2298. end;
  2299. end;
  2300. end;
  2301. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2302. overwrites the original destination register. e.g.
  2303. movl ###,%reg2d
  2304. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2305. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2306. }
  2307. if (taicpu(p).oper[1]^.typ = top_reg) and
  2308. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2309. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2310. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2311. begin
  2312. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2313. begin
  2314. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2315. case taicpu(p).oper[0]^.typ of
  2316. top_const:
  2317. { We have something like:
  2318. movb $x, %regb
  2319. movzbl %regb,%regd
  2320. Change to:
  2321. movl $x, %regd
  2322. }
  2323. begin
  2324. case taicpu(hp1).opsize of
  2325. S_BW:
  2326. begin
  2327. convert_mov_value(A_MOVSX, $FF);
  2328. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2329. taicpu(p).opsize := S_W;
  2330. end;
  2331. S_BL:
  2332. begin
  2333. convert_mov_value(A_MOVSX, $FF);
  2334. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2335. taicpu(p).opsize := S_L;
  2336. end;
  2337. S_WL:
  2338. begin
  2339. convert_mov_value(A_MOVSX, $FFFF);
  2340. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2341. taicpu(p).opsize := S_L;
  2342. end;
  2343. {$ifdef x86_64}
  2344. S_BQ:
  2345. begin
  2346. convert_mov_value(A_MOVSX, $FF);
  2347. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2348. taicpu(p).opsize := S_Q;
  2349. end;
  2350. S_WQ:
  2351. begin
  2352. convert_mov_value(A_MOVSX, $FFFF);
  2353. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2354. taicpu(p).opsize := S_Q;
  2355. end;
  2356. S_LQ:
  2357. begin
  2358. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2359. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2360. taicpu(p).opsize := S_Q;
  2361. end;
  2362. {$endif x86_64}
  2363. else
  2364. { If hp1 was a MOV instruction, it should have been
  2365. optimised already }
  2366. InternalError(2020021001);
  2367. end;
  2368. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2369. RemoveInstruction(hp1);
  2370. Result := True;
  2371. Exit;
  2372. end;
  2373. top_ref:
  2374. { We have something like:
  2375. movb mem, %regb
  2376. movzbl %regb,%regd
  2377. Change to:
  2378. movzbl mem, %regd
  2379. }
  2380. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2381. begin
  2382. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2383. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2384. RemoveCurrentP(p, hp1);
  2385. Result:=True;
  2386. Exit;
  2387. end;
  2388. else
  2389. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2390. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2391. Exit;
  2392. end;
  2393. end
  2394. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2395. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2396. optimised }
  2397. else
  2398. begin
  2399. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2400. RemoveCurrentP(p, hp1);
  2401. Result := True;
  2402. Exit;
  2403. end;
  2404. end;
  2405. if (taicpu(hp1).opcode = A_AND) and
  2406. (taicpu(p).oper[1]^.typ = top_reg) and
  2407. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2408. begin
  2409. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2410. begin
  2411. case taicpu(p).opsize of
  2412. S_L:
  2413. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2414. begin
  2415. { Optimize out:
  2416. mov x, %reg
  2417. and ffffffffh, %reg
  2418. }
  2419. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2420. RemoveInstruction(hp1);
  2421. Result:=true;
  2422. exit;
  2423. end;
  2424. S_Q: { TODO: Confirm if this is even possible }
  2425. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2426. begin
  2427. { Optimize out:
  2428. mov x, %reg
  2429. and ffffffffffffffffh, %reg
  2430. }
  2431. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2432. RemoveInstruction(hp1);
  2433. Result:=true;
  2434. exit;
  2435. end;
  2436. else
  2437. ;
  2438. end;
  2439. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2440. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2441. GetNextInstruction(hp1,hp2) and
  2442. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2443. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2444. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2445. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2446. GetNextInstruction(hp2,hp3) and
  2447. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2448. (taicpu(hp3).condition in [C_E,C_NE]) then
  2449. begin
  2450. TransferUsedRegs(TmpUsedRegs);
  2451. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2452. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2453. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2454. begin
  2455. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2456. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2457. taicpu(hp1).opcode:=A_TEST;
  2458. RemoveInstruction(hp2);
  2459. RemoveCurrentP(p, hp1);
  2460. Result:=true;
  2461. exit;
  2462. end;
  2463. end;
  2464. end
  2465. else if IsMOVZXAcceptable and
  2466. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2467. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2468. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2469. then
  2470. begin
  2471. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2472. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2473. case taicpu(p).opsize of
  2474. S_B:
  2475. if (taicpu(hp1).oper[0]^.val = $ff) then
  2476. begin
  2477. { Convert:
  2478. movb x, %regl movb x, %regl
  2479. andw ffh, %regw andl ffh, %regd
  2480. To:
  2481. movzbw x, %regd movzbl x, %regd
  2482. (Identical registers, just different sizes)
  2483. }
  2484. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2485. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2486. case taicpu(hp1).opsize of
  2487. S_W: NewSize := S_BW;
  2488. S_L: NewSize := S_BL;
  2489. {$ifdef x86_64}
  2490. S_Q: NewSize := S_BQ;
  2491. {$endif x86_64}
  2492. else
  2493. InternalError(2018011510);
  2494. end;
  2495. end
  2496. else
  2497. NewSize := S_NO;
  2498. S_W:
  2499. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2500. begin
  2501. { Convert:
  2502. movw x, %regw
  2503. andl ffffh, %regd
  2504. To:
  2505. movzwl x, %regd
  2506. (Identical registers, just different sizes)
  2507. }
  2508. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2509. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2510. case taicpu(hp1).opsize of
  2511. S_L: NewSize := S_WL;
  2512. {$ifdef x86_64}
  2513. S_Q: NewSize := S_WQ;
  2514. {$endif x86_64}
  2515. else
  2516. InternalError(2018011511);
  2517. end;
  2518. end
  2519. else
  2520. NewSize := S_NO;
  2521. else
  2522. NewSize := S_NO;
  2523. end;
  2524. if NewSize <> S_NO then
  2525. begin
  2526. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2527. { The actual optimization }
  2528. taicpu(p).opcode := A_MOVZX;
  2529. taicpu(p).changeopsize(NewSize);
  2530. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2531. { Safeguard if "and" is followed by a conditional command }
  2532. TransferUsedRegs(TmpUsedRegs);
  2533. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2534. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2535. begin
  2536. { At this point, the "and" command is effectively equivalent to
  2537. "test %reg,%reg". This will be handled separately by the
  2538. Peephole Optimizer. [Kit] }
  2539. DebugMsg(SPeepholeOptimization + PreMessage +
  2540. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2541. end
  2542. else
  2543. begin
  2544. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2545. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2546. RemoveInstruction(hp1);
  2547. end;
  2548. Result := True;
  2549. Exit;
  2550. end;
  2551. end;
  2552. end;
  2553. if (taicpu(hp1).opcode = A_OR) and
  2554. (taicpu(p).oper[1]^.typ = top_reg) and
  2555. MatchOperand(taicpu(p).oper[0]^, 0) and
  2556. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2557. begin
  2558. { mov 0, %reg
  2559. or ###,%reg
  2560. Change to (only if the flags are not used):
  2561. mov ###,%reg
  2562. }
  2563. TransferUsedRegs(TmpUsedRegs);
  2564. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2565. DoOptimisation := True;
  2566. { Even if the flags are used, we might be able to do the optimisation
  2567. if the conditions are predictable }
  2568. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2569. begin
  2570. { Only perform if ### = %reg (the same register) or equal to 0,
  2571. so %reg is guaranteed to still have a value of zero }
  2572. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2573. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2574. begin
  2575. hp2 := hp1;
  2576. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2577. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2578. GetNextInstruction(hp2, hp3) do
  2579. begin
  2580. { Don't continue modifying if the flags state is getting changed }
  2581. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2582. Break;
  2583. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2584. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2585. begin
  2586. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2587. begin
  2588. { Condition is always true }
  2589. case taicpu(hp3).opcode of
  2590. A_Jcc:
  2591. begin
  2592. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2593. { Check for jump shortcuts before we destroy the condition }
  2594. DoJumpOptimizations(hp3, TempBool);
  2595. MakeUnconditional(taicpu(hp3));
  2596. Result := True;
  2597. end;
  2598. A_CMOVcc:
  2599. begin
  2600. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2601. taicpu(hp3).opcode := A_MOV;
  2602. taicpu(hp3).condition := C_None;
  2603. Result := True;
  2604. end;
  2605. A_SETcc:
  2606. begin
  2607. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2608. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2609. taicpu(hp3).opcode := A_MOV;
  2610. taicpu(hp3).ops := 2;
  2611. taicpu(hp3).condition := C_None;
  2612. taicpu(hp3).opsize := S_B;
  2613. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2614. taicpu(hp3).loadconst(0, 1);
  2615. Result := True;
  2616. end;
  2617. else
  2618. InternalError(2021090701);
  2619. end;
  2620. end
  2621. 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
  2622. begin
  2623. { Condition is always false }
  2624. case taicpu(hp3).opcode of
  2625. A_Jcc:
  2626. begin
  2627. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2628. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2629. RemoveInstruction(hp3);
  2630. Result := True;
  2631. { Since hp3 was deleted, hp2 must not be updated }
  2632. Continue;
  2633. end;
  2634. A_CMOVcc:
  2635. begin
  2636. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2637. RemoveInstruction(hp3);
  2638. Result := True;
  2639. { Since hp3 was deleted, hp2 must not be updated }
  2640. Continue;
  2641. end;
  2642. A_SETcc:
  2643. begin
  2644. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2645. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2646. taicpu(hp3).opcode := A_MOV;
  2647. taicpu(hp3).ops := 2;
  2648. taicpu(hp3).condition := C_None;
  2649. taicpu(hp3).opsize := S_B;
  2650. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2651. taicpu(hp3).loadconst(0, 0);
  2652. Result := True;
  2653. end;
  2654. else
  2655. InternalError(2021090702);
  2656. end;
  2657. end
  2658. else
  2659. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2660. DoOptimisation := False;
  2661. end;
  2662. hp2 := hp3;
  2663. end;
  2664. { Flags are still in use - don't optimise }
  2665. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2666. DoOptimisation := False;
  2667. end
  2668. else
  2669. DoOptimisation := False;
  2670. end;
  2671. if DoOptimisation then
  2672. begin
  2673. {$ifdef x86_64}
  2674. { OR only supports 32-bit sign-extended constants for 64-bit
  2675. instructions, so compensate for this if the constant is
  2676. encoded as a value greater than or equal to 2^31 }
  2677. if (taicpu(hp1).opsize = S_Q) and
  2678. (taicpu(hp1).oper[0]^.typ = top_const) and
  2679. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2680. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2681. {$endif x86_64}
  2682. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2683. taicpu(hp1).opcode := A_MOV;
  2684. RemoveCurrentP(p, hp1);
  2685. Result := True;
  2686. Exit;
  2687. end;
  2688. end;
  2689. { Next instruction is also a MOV ? }
  2690. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2691. begin
  2692. if (taicpu(p).oper[1]^.typ = top_reg) and
  2693. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2694. begin
  2695. CurrentReg := taicpu(p).oper[1]^.reg;
  2696. TransferUsedRegs(TmpUsedRegs);
  2697. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2698. { we have
  2699. mov x, %treg
  2700. mov %treg, y
  2701. }
  2702. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2703. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2704. { we've got
  2705. mov x, %treg
  2706. mov %treg, y
  2707. with %treg is not used after }
  2708. case taicpu(p).oper[0]^.typ Of
  2709. { top_reg is covered by DeepMOVOpt }
  2710. top_const:
  2711. begin
  2712. { change
  2713. mov const, %treg
  2714. mov %treg, y
  2715. to
  2716. mov const, y
  2717. }
  2718. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2719. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2720. begin
  2721. if taicpu(hp1).oper[1]^.typ=top_reg then
  2722. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2723. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2724. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2725. RemoveInstruction(hp1);
  2726. Result:=true;
  2727. Exit;
  2728. end;
  2729. end;
  2730. top_ref:
  2731. case taicpu(hp1).oper[1]^.typ of
  2732. top_reg:
  2733. begin
  2734. { change
  2735. mov mem, %treg
  2736. mov %treg, %reg
  2737. to
  2738. mov mem, %reg"
  2739. }
  2740. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2741. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2742. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2743. RemoveInstruction(hp1);
  2744. Result:=true;
  2745. Exit;
  2746. end;
  2747. top_ref:
  2748. begin
  2749. {$ifdef x86_64}
  2750. { Look for the following to simplify:
  2751. mov x(mem1), %reg
  2752. mov %reg, y(mem2)
  2753. mov x+8(mem1), %reg
  2754. mov %reg, y+8(mem2)
  2755. Change to:
  2756. movdqu x(mem1), %xmmreg
  2757. movdqu %xmmreg, y(mem2)
  2758. }
  2759. SourceRef := taicpu(p).oper[0]^.ref^;
  2760. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2761. if (taicpu(p).opsize = S_Q) and
  2762. GetNextInstruction(hp1, hp2) and
  2763. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2764. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2765. begin
  2766. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2767. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2768. Inc(SourceRef.offset, 8);
  2769. if UseAVX then
  2770. begin
  2771. MovAligned := A_VMOVDQA;
  2772. MovUnaligned := A_VMOVDQU;
  2773. end
  2774. else
  2775. begin
  2776. MovAligned := A_MOVDQA;
  2777. MovUnaligned := A_MOVDQU;
  2778. end;
  2779. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2780. begin
  2781. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2782. Inc(TargetRef.offset, 8);
  2783. if GetNextInstruction(hp2, hp3) and
  2784. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2785. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2786. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2787. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2788. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2789. begin
  2790. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2791. if CurrentReg <> NR_NO then
  2792. begin
  2793. { Remember that the offsets are 8 ahead }
  2794. if ((SourceRef.offset mod 16) = 8) and
  2795. (
  2796. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2797. (SourceRef.base = current_procinfo.framepointer) or
  2798. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2799. ) then
  2800. taicpu(p).opcode := MovAligned
  2801. else
  2802. taicpu(p).opcode := MovUnaligned;
  2803. taicpu(p).opsize := S_XMM;
  2804. taicpu(p).oper[1]^.reg := CurrentReg;
  2805. if ((TargetRef.offset mod 16) = 8) and
  2806. (
  2807. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2808. (TargetRef.base = current_procinfo.framepointer) or
  2809. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2810. ) then
  2811. taicpu(hp1).opcode := MovAligned
  2812. else
  2813. taicpu(hp1).opcode := MovUnaligned;
  2814. taicpu(hp1).opsize := S_XMM;
  2815. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2816. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2817. RemoveInstruction(hp2);
  2818. RemoveInstruction(hp3);
  2819. Result := True;
  2820. Exit;
  2821. end;
  2822. end;
  2823. end
  2824. else
  2825. begin
  2826. { See if the next references are 8 less rather than 8 greater }
  2827. Dec(SourceRef.offset, 16); { -8 the other way }
  2828. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2829. begin
  2830. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2831. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2832. if GetNextInstruction(hp2, hp3) and
  2833. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2834. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2835. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2836. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2837. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2838. begin
  2839. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2840. if CurrentReg <> NR_NO then
  2841. begin
  2842. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2843. if ((SourceRef.offset mod 16) = 0) and
  2844. (
  2845. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2846. (SourceRef.base = current_procinfo.framepointer) or
  2847. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2848. ) then
  2849. taicpu(hp2).opcode := MovAligned
  2850. else
  2851. taicpu(hp2).opcode := MovUnaligned;
  2852. taicpu(hp2).opsize := S_XMM;
  2853. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2854. if ((TargetRef.offset mod 16) = 0) and
  2855. (
  2856. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2857. (TargetRef.base = current_procinfo.framepointer) or
  2858. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2859. ) then
  2860. taicpu(hp3).opcode := MovAligned
  2861. else
  2862. taicpu(hp3).opcode := MovUnaligned;
  2863. taicpu(hp3).opsize := S_XMM;
  2864. taicpu(hp3).oper[0]^.reg := CurrentReg;
  2865. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  2866. RemoveInstruction(hp1);
  2867. RemoveCurrentP(p, hp2);
  2868. Result := True;
  2869. Exit;
  2870. end;
  2871. end;
  2872. end;
  2873. end;
  2874. end;
  2875. {$endif x86_64}
  2876. end;
  2877. else
  2878. { The write target should be a reg or a ref }
  2879. InternalError(2021091601);
  2880. end;
  2881. else
  2882. ;
  2883. end
  2884. else
  2885. { %treg is used afterwards, but all eventualities
  2886. other than the first MOV instruction being a constant
  2887. are covered by DeepMOVOpt, so only check for that }
  2888. if (taicpu(p).oper[0]^.typ = top_const) and
  2889. (
  2890. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2891. not (cs_opt_size in current_settings.optimizerswitches) or
  2892. (taicpu(hp1).opsize = S_B)
  2893. ) and
  2894. (
  2895. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2896. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2897. ) then
  2898. begin
  2899. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2900. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2901. end;
  2902. end;
  2903. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2904. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2905. { mov reg1, mem1 or mov mem1, reg1
  2906. mov mem2, reg2 mov reg2, mem2}
  2907. begin
  2908. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2909. { mov reg1, mem1 or mov mem1, reg1
  2910. mov mem2, reg1 mov reg2, mem1}
  2911. begin
  2912. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2913. { Removes the second statement from
  2914. mov reg1, mem1/reg2
  2915. mov mem1/reg2, reg1 }
  2916. begin
  2917. if taicpu(p).oper[0]^.typ=top_reg then
  2918. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2919. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2920. RemoveInstruction(hp1);
  2921. Result:=true;
  2922. exit;
  2923. end
  2924. else
  2925. begin
  2926. TransferUsedRegs(TmpUsedRegs);
  2927. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2928. if (taicpu(p).oper[1]^.typ = top_ref) and
  2929. { mov reg1, mem1
  2930. mov mem2, reg1 }
  2931. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2932. GetNextInstruction(hp1, hp2) and
  2933. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2934. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2935. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2936. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2937. { change to
  2938. mov reg1, mem1 mov reg1, mem1
  2939. mov mem2, reg1 cmp reg1, mem2
  2940. cmp mem1, reg1
  2941. }
  2942. begin
  2943. RemoveInstruction(hp2);
  2944. taicpu(hp1).opcode := A_CMP;
  2945. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2946. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2947. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2948. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2949. end;
  2950. end;
  2951. end
  2952. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2953. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2954. begin
  2955. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2956. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2957. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2958. end
  2959. else
  2960. begin
  2961. TransferUsedRegs(TmpUsedRegs);
  2962. if GetNextInstruction(hp1, hp2) and
  2963. MatchOpType(taicpu(p),top_ref,top_reg) and
  2964. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2965. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2966. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2967. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2968. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2969. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2970. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2971. { mov mem1, %reg1
  2972. mov %reg1, mem2
  2973. mov mem2, reg2
  2974. to:
  2975. mov mem1, reg2
  2976. mov reg2, mem2}
  2977. begin
  2978. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2979. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2980. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2981. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2982. RemoveInstruction(hp2);
  2983. Result := True;
  2984. end
  2985. {$ifdef i386}
  2986. { this is enabled for i386 only, as the rules to create the reg sets below
  2987. are too complicated for x86-64, so this makes this code too error prone
  2988. on x86-64
  2989. }
  2990. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2991. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2992. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2993. { mov mem1, reg1 mov mem1, reg1
  2994. mov reg1, mem2 mov reg1, mem2
  2995. mov mem2, reg2 mov mem2, reg1
  2996. to: to:
  2997. mov mem1, reg1 mov mem1, reg1
  2998. mov mem1, reg2 mov reg1, mem2
  2999. mov reg1, mem2
  3000. or (if mem1 depends on reg1
  3001. and/or if mem2 depends on reg2)
  3002. to:
  3003. mov mem1, reg1
  3004. mov reg1, mem2
  3005. mov reg1, reg2
  3006. }
  3007. begin
  3008. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3009. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3010. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3011. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3012. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3013. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3014. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3015. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3016. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3017. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3018. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3019. end
  3020. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3021. begin
  3022. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3023. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3024. end
  3025. else
  3026. begin
  3027. RemoveInstruction(hp2);
  3028. end
  3029. {$endif i386}
  3030. ;
  3031. end;
  3032. end
  3033. { movl [mem1],reg1
  3034. movl [mem1],reg2
  3035. to
  3036. movl [mem1],reg1
  3037. movl reg1,reg2
  3038. }
  3039. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3040. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3041. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3042. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3043. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3044. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3045. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3046. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3047. begin
  3048. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3049. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3050. end;
  3051. { movl const1,[mem1]
  3052. movl [mem1],reg1
  3053. to
  3054. movl const1,reg1
  3055. movl reg1,[mem1]
  3056. }
  3057. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3058. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3059. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3060. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3061. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3062. begin
  3063. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3064. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3065. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3066. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3067. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3068. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3069. Result:=true;
  3070. exit;
  3071. end;
  3072. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3073. end;
  3074. { search further than the next instruction for a mov (as long as it's not a jump) }
  3075. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3076. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3077. (taicpu(p).oper[1]^.typ = top_reg) and
  3078. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3079. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3080. begin
  3081. { we work with hp2 here, so hp1 can be still used later on when
  3082. checking for GetNextInstruction_p }
  3083. hp3 := hp1;
  3084. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3085. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3086. { Saves on a large number of dereferences }
  3087. ActiveReg := taicpu(p).oper[1]^.reg;
  3088. TransferUsedRegs(TmpUsedRegs);
  3089. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3090. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3091. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3092. (hp2.typ=ait_instruction) do
  3093. begin
  3094. case taicpu(hp2).opcode of
  3095. A_POP:
  3096. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3097. begin
  3098. if not CrossJump and
  3099. not RegUsedBetween(ActiveReg, p, hp2) then
  3100. begin
  3101. { We can remove the original MOV since the register
  3102. wasn't used between it and its popping from the stack }
  3103. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3104. RemoveCurrentp(p, hp1);
  3105. Result := True;
  3106. Exit;
  3107. end;
  3108. { Can't go any further }
  3109. Break;
  3110. end;
  3111. A_MOV:
  3112. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3113. ((taicpu(p).oper[0]^.typ=top_const) or
  3114. ((taicpu(p).oper[0]^.typ=top_reg) and
  3115. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3116. )
  3117. ) then
  3118. begin
  3119. { we have
  3120. mov x, %treg
  3121. mov %treg, y
  3122. }
  3123. { We don't need to call UpdateUsedRegs for every instruction between
  3124. p and hp2 because the register we're concerned about will not
  3125. become deallocated (otherwise GetNextInstructionUsingReg would
  3126. have stopped at an earlier instruction). [Kit] }
  3127. TempRegUsed :=
  3128. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3129. RegReadByInstruction(ActiveReg, hp3) or
  3130. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3131. case taicpu(p).oper[0]^.typ Of
  3132. top_reg:
  3133. begin
  3134. { change
  3135. mov %reg, %treg
  3136. mov %treg, y
  3137. to
  3138. mov %reg, y
  3139. }
  3140. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3141. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3142. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3143. begin
  3144. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3145. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3146. if TempRegUsed then
  3147. begin
  3148. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3149. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3150. { Set the start of the next GetNextInstructionUsingRegCond search
  3151. to start at the entry right before hp2 (which is about to be removed) }
  3152. hp3 := tai(hp2.Previous);
  3153. RemoveInstruction(hp2);
  3154. { See if there's more we can optimise }
  3155. Continue;
  3156. end
  3157. else
  3158. begin
  3159. RemoveInstruction(hp2);
  3160. { We can remove the original MOV too }
  3161. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3162. RemoveCurrentP(p, hp1);
  3163. Result:=true;
  3164. Exit;
  3165. end;
  3166. end
  3167. else
  3168. begin
  3169. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3170. taicpu(hp2).loadReg(0, CurrentReg);
  3171. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3172. { Check to see if the register also appears in the reference }
  3173. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3174. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3175. { Don't remove the first instruction if the temporary register is in use }
  3176. if not TempRegUsed and
  3177. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3178. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3179. begin
  3180. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3181. RemoveCurrentP(p, hp1);
  3182. Result:=true;
  3183. Exit;
  3184. end;
  3185. { No need to set Result to True here. If there's another instruction later
  3186. on that can be optimised, it will be detected when the main Pass 1 loop
  3187. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3188. end;
  3189. end;
  3190. top_const:
  3191. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3192. begin
  3193. { change
  3194. mov const, %treg
  3195. mov %treg, y
  3196. to
  3197. mov const, y
  3198. }
  3199. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3200. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3201. begin
  3202. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3203. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3204. if TempRegUsed then
  3205. begin
  3206. { Don't remove the first instruction if the temporary register is in use }
  3207. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3208. { No need to set Result to True. If there's another instruction later on
  3209. that can be optimised, it will be detected when the main Pass 1 loop
  3210. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3211. end
  3212. else
  3213. begin
  3214. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3215. RemoveCurrentP(p, hp1);
  3216. Result:=true;
  3217. Exit;
  3218. end;
  3219. end;
  3220. end;
  3221. else
  3222. Internalerror(2019103001);
  3223. end;
  3224. end
  3225. else
  3226. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3227. begin
  3228. if not CrossJump and
  3229. not RegUsedBetween(ActiveReg, p, hp2) and
  3230. not RegReadByInstruction(ActiveReg, hp2) then
  3231. begin
  3232. { Register is not used before it is overwritten }
  3233. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3234. RemoveCurrentp(p, hp1);
  3235. Result := True;
  3236. Exit;
  3237. end;
  3238. if (taicpu(p).oper[0]^.typ = top_const) and
  3239. (taicpu(hp2).oper[0]^.typ = top_const) then
  3240. begin
  3241. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3242. begin
  3243. { Same value - register hasn't changed }
  3244. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3245. RemoveInstruction(hp2);
  3246. Result := True;
  3247. { See if there's more we can optimise }
  3248. Continue;
  3249. end;
  3250. end;
  3251. end;
  3252. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3253. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3254. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3255. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3256. begin
  3257. {
  3258. Change from:
  3259. mov ###, %reg
  3260. ...
  3261. movs/z %reg,%reg (Same register, just different sizes)
  3262. To:
  3263. movs/z ###, %reg (Longer version)
  3264. ...
  3265. (remove)
  3266. }
  3267. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3268. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3269. { Keep the first instruction as mov if ### is a constant }
  3270. if taicpu(p).oper[0]^.typ = top_const then
  3271. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3272. else
  3273. begin
  3274. taicpu(p).opcode := taicpu(hp2).opcode;
  3275. taicpu(p).opsize := taicpu(hp2).opsize;
  3276. end;
  3277. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3278. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3279. RemoveInstruction(hp2);
  3280. Result := True;
  3281. Exit;
  3282. end;
  3283. else
  3284. { Move down to the MatchOpType if-block below };
  3285. end;
  3286. { Also catches MOV/S/Z instructions that aren't modified }
  3287. if taicpu(p).oper[0]^.typ = top_reg then
  3288. begin
  3289. CurrentReg := taicpu(p).oper[0]^.reg;
  3290. if
  3291. not RegModifiedByInstruction(CurrentReg, hp3) and
  3292. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3293. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3294. begin
  3295. Result := True;
  3296. { Just in case something didn't get modified (e.g. an
  3297. implicit register). Also, if it does read from this
  3298. register, then there's no longer an advantage to
  3299. changing the register on subsequent instructions.}
  3300. if not RegReadByInstruction(ActiveReg, hp2) then
  3301. begin
  3302. { If a conditional jump was crossed, do not delete
  3303. the original MOV no matter what }
  3304. if not CrossJump and
  3305. { RegEndOfLife returns True if the register is
  3306. deallocated before the next instruction or has
  3307. been loaded with a new value }
  3308. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3309. begin
  3310. { We can remove the original MOV }
  3311. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3312. RemoveCurrentp(p, hp1);
  3313. Exit;
  3314. end;
  3315. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3316. begin
  3317. { See if there's more we can optimise }
  3318. hp3 := hp2;
  3319. Continue;
  3320. end;
  3321. end;
  3322. end;
  3323. end;
  3324. { Break out of the while loop under normal circumstances }
  3325. Break;
  3326. end;
  3327. end;
  3328. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3329. (taicpu(p).oper[1]^.typ = top_reg) and
  3330. (taicpu(p).opsize = S_L) and
  3331. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3332. (taicpu(hp2).opcode = A_AND) and
  3333. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3334. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3335. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3336. ) then
  3337. begin
  3338. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3339. begin
  3340. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3341. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3342. begin
  3343. { Optimize out:
  3344. mov x, %reg
  3345. and ffffffffh, %reg
  3346. }
  3347. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3348. RemoveInstruction(hp2);
  3349. Result:=true;
  3350. exit;
  3351. end;
  3352. end;
  3353. end;
  3354. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3355. x >= RetOffset) as it doesn't do anything (it writes either to a
  3356. parameter or to the temporary storage room for the function
  3357. result)
  3358. }
  3359. if IsExitCode(hp1) and
  3360. (taicpu(p).oper[1]^.typ = top_ref) and
  3361. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3362. (
  3363. (
  3364. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3365. not (
  3366. assigned(current_procinfo.procdef.funcretsym) and
  3367. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3368. )
  3369. ) or
  3370. { Also discard writes to the stack that are below the base pointer,
  3371. as this is temporary storage rather than a function result on the
  3372. stack, say. }
  3373. (
  3374. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3375. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3376. )
  3377. ) then
  3378. begin
  3379. RemoveCurrentp(p, hp1);
  3380. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3381. RemoveLastDeallocForFuncRes(p);
  3382. Result:=true;
  3383. exit;
  3384. end;
  3385. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3386. begin
  3387. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3388. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3389. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3390. begin
  3391. { change
  3392. mov reg1, mem1
  3393. test/cmp x, mem1
  3394. to
  3395. mov reg1, mem1
  3396. test/cmp x, reg1
  3397. }
  3398. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3399. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3400. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3401. Result := True;
  3402. Exit;
  3403. end;
  3404. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3405. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3406. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3407. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3408. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3409. (
  3410. (
  3411. (taicpu(hp1).opcode = A_TEST)
  3412. ) or (
  3413. (taicpu(hp1).opcode = A_CMP) and
  3414. { A sanity check more than anything }
  3415. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3416. )
  3417. ) then
  3418. begin
  3419. { change
  3420. mov mem, %reg
  3421. cmp/test x, %reg / test %reg,%reg
  3422. (reg deallocated)
  3423. to
  3424. cmp/test x, mem / cmp 0, mem
  3425. }
  3426. TransferUsedRegs(TmpUsedRegs);
  3427. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3428. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3429. begin
  3430. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3431. if (taicpu(hp1).opcode = A_TEST) and
  3432. (
  3433. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3434. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3435. ) then
  3436. begin
  3437. taicpu(hp1).opcode := A_CMP;
  3438. taicpu(hp1).loadconst(0, 0);
  3439. end;
  3440. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3441. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3442. RemoveCurrentP(p, hp1);
  3443. Result := True;
  3444. Exit;
  3445. end;
  3446. end;
  3447. end;
  3448. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3449. { If the flags register is in use, don't change the instruction to an
  3450. ADD otherwise this will scramble the flags. [Kit] }
  3451. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3452. begin
  3453. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3454. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3455. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3456. ) or
  3457. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3458. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3459. )
  3460. ) then
  3461. { mov reg1,ref
  3462. lea reg2,[reg1,reg2]
  3463. to
  3464. add reg2,ref}
  3465. begin
  3466. TransferUsedRegs(TmpUsedRegs);
  3467. { reg1 may not be used afterwards }
  3468. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3469. begin
  3470. Taicpu(hp1).opcode:=A_ADD;
  3471. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3472. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3473. RemoveCurrentp(p, hp1);
  3474. result:=true;
  3475. exit;
  3476. end;
  3477. end;
  3478. { If the LEA instruction can be converted into an arithmetic instruction,
  3479. it may be possible to then fold it in the next optimisation, otherwise
  3480. there's nothing more that can be optimised here. }
  3481. if not ConvertLEA(taicpu(hp1)) then
  3482. Exit;
  3483. end;
  3484. if (taicpu(p).oper[1]^.typ = top_reg) and
  3485. (hp1.typ = ait_instruction) and
  3486. GetNextInstruction(hp1, hp2) and
  3487. MatchInstruction(hp2,A_MOV,[]) and
  3488. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3489. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3490. (
  3491. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3492. {$ifdef x86_64}
  3493. or
  3494. (
  3495. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3496. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3497. )
  3498. {$endif x86_64}
  3499. ) then
  3500. begin
  3501. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3502. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3503. { change movsX/movzX reg/ref, reg2
  3504. add/sub/or/... reg3/$const, reg2
  3505. mov reg2 reg/ref
  3506. dealloc reg2
  3507. to
  3508. add/sub/or/... reg3/$const, reg/ref }
  3509. begin
  3510. TransferUsedRegs(TmpUsedRegs);
  3511. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3512. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3513. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3514. begin
  3515. { by example:
  3516. movswl %si,%eax movswl %si,%eax p
  3517. decl %eax addl %edx,%eax hp1
  3518. movw %ax,%si movw %ax,%si hp2
  3519. ->
  3520. movswl %si,%eax movswl %si,%eax p
  3521. decw %eax addw %edx,%eax hp1
  3522. movw %ax,%si movw %ax,%si hp2
  3523. }
  3524. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3525. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3526. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3527. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3528. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3529. {
  3530. ->
  3531. movswl %si,%eax movswl %si,%eax p
  3532. decw %si addw %dx,%si hp1
  3533. movw %ax,%si movw %ax,%si hp2
  3534. }
  3535. case taicpu(hp1).ops of
  3536. 1:
  3537. begin
  3538. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3539. if taicpu(hp1).oper[0]^.typ=top_reg then
  3540. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3541. end;
  3542. 2:
  3543. begin
  3544. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3545. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3546. (taicpu(hp1).opcode<>A_SHL) and
  3547. (taicpu(hp1).opcode<>A_SHR) and
  3548. (taicpu(hp1).opcode<>A_SAR) then
  3549. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3550. end;
  3551. else
  3552. internalerror(2008042701);
  3553. end;
  3554. {
  3555. ->
  3556. decw %si addw %dx,%si p
  3557. }
  3558. RemoveInstruction(hp2);
  3559. RemoveCurrentP(p, hp1);
  3560. Result:=True;
  3561. Exit;
  3562. end;
  3563. end;
  3564. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3565. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3566. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3567. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3568. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3569. )
  3570. {$ifdef i386}
  3571. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3572. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3573. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3574. {$endif i386}
  3575. then
  3576. { change movsX/movzX reg/ref, reg2
  3577. add/sub/or/... regX/$const, reg2
  3578. mov reg2, reg3
  3579. dealloc reg2
  3580. to
  3581. movsX/movzX reg/ref, reg3
  3582. add/sub/or/... reg3/$const, reg3
  3583. }
  3584. begin
  3585. TransferUsedRegs(TmpUsedRegs);
  3586. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3587. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3588. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3589. begin
  3590. { by example:
  3591. movswl %si,%eax movswl %si,%eax p
  3592. decl %eax addl %edx,%eax hp1
  3593. movw %ax,%si movw %ax,%si hp2
  3594. ->
  3595. movswl %si,%eax movswl %si,%eax p
  3596. decw %eax addw %edx,%eax hp1
  3597. movw %ax,%si movw %ax,%si hp2
  3598. }
  3599. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3600. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3601. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3602. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3603. { limit size of constants as well to avoid assembler errors, but
  3604. check opsize to avoid overflow when left shifting the 1 }
  3605. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3606. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3607. {$ifdef x86_64}
  3608. { Be careful of, for example:
  3609. movl %reg1,%reg2
  3610. addl %reg3,%reg2
  3611. movq %reg2,%reg4
  3612. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3613. }
  3614. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3615. begin
  3616. taicpu(hp2).changeopsize(S_L);
  3617. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3618. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3619. end;
  3620. {$endif x86_64}
  3621. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3622. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3623. if taicpu(p).oper[0]^.typ=top_reg then
  3624. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3625. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3626. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3627. {
  3628. ->
  3629. movswl %si,%eax movswl %si,%eax p
  3630. decw %si addw %dx,%si hp1
  3631. movw %ax,%si movw %ax,%si hp2
  3632. }
  3633. case taicpu(hp1).ops of
  3634. 1:
  3635. begin
  3636. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3637. if taicpu(hp1).oper[0]^.typ=top_reg then
  3638. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3639. end;
  3640. 2:
  3641. begin
  3642. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3643. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3644. (taicpu(hp1).opcode<>A_SHL) and
  3645. (taicpu(hp1).opcode<>A_SHR) and
  3646. (taicpu(hp1).opcode<>A_SAR) then
  3647. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3648. end;
  3649. else
  3650. internalerror(2018111801);
  3651. end;
  3652. {
  3653. ->
  3654. decw %si addw %dx,%si p
  3655. }
  3656. RemoveInstruction(hp2);
  3657. end;
  3658. end;
  3659. end;
  3660. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3661. GetNextInstruction(hp1, hp2) and
  3662. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3663. MatchOperand(Taicpu(p).oper[0]^,0) and
  3664. (Taicpu(p).oper[1]^.typ = top_reg) and
  3665. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3666. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3667. { mov reg1,0
  3668. bts reg1,operand1 --> mov reg1,operand2
  3669. or reg1,operand2 bts reg1,operand1}
  3670. begin
  3671. Taicpu(hp2).opcode:=A_MOV;
  3672. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3673. asml.remove(hp1);
  3674. insertllitem(hp2,hp2.next,hp1);
  3675. RemoveCurrentp(p, hp1);
  3676. Result:=true;
  3677. exit;
  3678. end;
  3679. {
  3680. mov ref,reg0
  3681. <op> reg0,reg1
  3682. dealloc reg0
  3683. to
  3684. <op> ref,reg1
  3685. }
  3686. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3687. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3688. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3689. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3690. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3691. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3692. begin
  3693. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3694. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3695. RemoveCurrentp(p, hp1);
  3696. Result:=true;
  3697. exit;
  3698. end;
  3699. {$ifdef x86_64}
  3700. { Convert:
  3701. movq x(ref),%reg64
  3702. shrq y,%reg64
  3703. To:
  3704. movq x+4(ref),%reg32
  3705. shrq y-32,%reg32 (Remove if y = 32)
  3706. }
  3707. if (taicpu(p).opsize = S_Q) and
  3708. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3709. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3710. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3711. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3712. (taicpu(hp1).oper[0]^.val >= 32) and
  3713. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3714. begin
  3715. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3716. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3717. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3718. { Convert to 32-bit }
  3719. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3720. taicpu(p).opsize := S_L;
  3721. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3722. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3723. if (taicpu(hp1).oper[0]^.val = 32) then
  3724. begin
  3725. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3726. RemoveInstruction(hp1);
  3727. end
  3728. else
  3729. begin
  3730. { This will potentially open up more arithmetic operations since
  3731. the peephole optimizer now has a big hint that only the lower
  3732. 32 bits are currently in use (and opcodes are smaller in size) }
  3733. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3734. taicpu(hp1).opsize := S_L;
  3735. Dec(taicpu(hp1).oper[0]^.val, 32);
  3736. DebugMsg(SPeepholeOptimization + PreMessage +
  3737. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3738. end;
  3739. Result := True;
  3740. Exit;
  3741. end;
  3742. {$endif x86_64}
  3743. end;
  3744. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3745. var
  3746. hp1 : tai;
  3747. begin
  3748. Result:=false;
  3749. if taicpu(p).ops <> 2 then
  3750. exit;
  3751. if ((taicpu(p).oper[1]^.typ=top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3752. GetNextInstruction(p,hp1) then
  3753. begin
  3754. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3755. (taicpu(hp1).ops = 2) then
  3756. begin
  3757. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3758. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3759. { movXX reg1, mem1 or movXX mem1, reg1
  3760. movXX mem2, reg2 movXX reg2, mem2}
  3761. begin
  3762. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3763. { movXX reg1, mem1 or movXX mem1, reg1
  3764. movXX mem2, reg1 movXX reg2, mem1}
  3765. begin
  3766. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3767. begin
  3768. { Removes the second statement from
  3769. movXX reg1, mem1/reg2
  3770. movXX mem1/reg2, reg1
  3771. }
  3772. if taicpu(p).oper[0]^.typ=top_reg then
  3773. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3774. { Removes the second statement from
  3775. movXX mem1/reg1, reg2
  3776. movXX reg2, mem1/reg1
  3777. }
  3778. if (taicpu(p).oper[1]^.typ=top_reg) and
  3779. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3780. begin
  3781. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3782. RemoveInstruction(hp1);
  3783. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3784. Result:=true;
  3785. exit;
  3786. end
  3787. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  3788. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  3789. begin
  3790. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3791. RemoveInstruction(hp1);
  3792. Result:=true;
  3793. exit;
  3794. end;
  3795. end
  3796. end;
  3797. end;
  3798. end;
  3799. end;
  3800. end;
  3801. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3802. var
  3803. hp1 : tai;
  3804. begin
  3805. result:=false;
  3806. { replace
  3807. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3808. MovX %mreg2,%mreg1
  3809. dealloc %mreg2
  3810. by
  3811. <Op>X %mreg2,%mreg1
  3812. ?
  3813. }
  3814. if GetNextInstruction(p,hp1) and
  3815. { we mix single and double opperations here because we assume that the compiler
  3816. generates vmovapd only after double operations and vmovaps only after single operations }
  3817. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3818. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3819. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3820. (taicpu(p).oper[0]^.typ=top_reg) then
  3821. begin
  3822. TransferUsedRegs(TmpUsedRegs);
  3823. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3824. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3825. begin
  3826. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3827. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3828. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3829. RemoveInstruction(hp1);
  3830. result:=true;
  3831. end;
  3832. end;
  3833. end;
  3834. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3835. var
  3836. hp1, p_label, p_dist, hp1_dist: tai;
  3837. JumpLabel, JumpLabel_dist: TAsmLabel;
  3838. begin
  3839. Result := False;
  3840. if GetNextInstruction(p, hp1) and
  3841. TrySwapMovCmp(p, hp1) then
  3842. begin
  3843. Result := True;
  3844. Exit;
  3845. end;
  3846. { Search for:
  3847. test %reg,%reg
  3848. j(c1) @lbl1
  3849. ...
  3850. @lbl:
  3851. test %reg,%reg (same register)
  3852. j(c2) @lbl2
  3853. If c2 is a subset of c1, change to:
  3854. test %reg,%reg
  3855. j(c1) @lbl2
  3856. (@lbl1 may become a dead label as a result)
  3857. }
  3858. if (taicpu(p).oper[1]^.typ = top_reg) and
  3859. (taicpu(p).oper[0]^.typ = top_reg) and
  3860. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3861. MatchInstruction(hp1, A_JCC, []) and
  3862. IsJumpToLabel(taicpu(hp1)) then
  3863. begin
  3864. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3865. p_label := nil;
  3866. if Assigned(JumpLabel) then
  3867. p_label := getlabelwithsym(JumpLabel);
  3868. if Assigned(p_label) and
  3869. GetNextInstruction(p_label, p_dist) and
  3870. MatchInstruction(p_dist, A_TEST, []) and
  3871. { It's fine if the second test uses smaller sub-registers }
  3872. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3873. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3874. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3875. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3876. GetNextInstruction(p_dist, hp1_dist) and
  3877. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3878. begin
  3879. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3880. if JumpLabel = JumpLabel_dist then
  3881. { This is an infinite loop }
  3882. Exit;
  3883. { Best optimisation when the first condition is a subset (or equal) of the second }
  3884. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3885. begin
  3886. { Any registers used here will already be allocated }
  3887. if Assigned(JumpLabel_dist) then
  3888. JumpLabel_dist.IncRefs;
  3889. if Assigned(JumpLabel) then
  3890. JumpLabel.DecRefs;
  3891. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3892. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3893. Result := True;
  3894. Exit;
  3895. end;
  3896. end;
  3897. end;
  3898. end;
  3899. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3900. var
  3901. hp1, hp2: tai;
  3902. ActiveReg: TRegister;
  3903. OldOffset: asizeint;
  3904. ThisConst: TCGInt;
  3905. function RegDeallocated: Boolean;
  3906. begin
  3907. TransferUsedRegs(TmpUsedRegs);
  3908. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3909. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  3910. end;
  3911. begin
  3912. result:=false;
  3913. hp1 := nil;
  3914. { replace
  3915. addX const,%reg1
  3916. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3917. dealloc %reg1
  3918. by
  3919. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3920. }
  3921. if MatchOpType(taicpu(p),top_const,top_reg) then
  3922. begin
  3923. ActiveReg := taicpu(p).oper[1]^.reg;
  3924. { Ensures the entire register was updated }
  3925. if (taicpu(p).opsize >= S_L) and
  3926. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  3927. MatchInstruction(hp1,A_LEA,[]) and
  3928. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  3929. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  3930. (
  3931. { Cover the case where the register in the reference is also the destination register }
  3932. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  3933. (
  3934. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  3935. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  3936. RegDeallocated
  3937. )
  3938. ) then
  3939. begin
  3940. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  3941. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  3942. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3943. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  3944. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3945. {$ifdef x86_64}
  3946. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  3947. begin
  3948. { Overflow; abort }
  3949. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  3950. end
  3951. else
  3952. {$endif x86_64}
  3953. begin
  3954. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3955. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  3956. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  3957. RemoveCurrentP(p, hp1)
  3958. else
  3959. RemoveCurrentP(p);
  3960. result:=true;
  3961. Exit;
  3962. end;
  3963. end;
  3964. if (
  3965. { Save calling GetNextInstructionUsingReg again }
  3966. Assigned(hp1) or
  3967. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  3968. ) and
  3969. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  3970. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  3971. begin
  3972. if taicpu(hp1).oper[0]^.typ = top_const then
  3973. begin
  3974. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  3975. if taicpu(hp1).opcode = A_ADD then
  3976. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  3977. else
  3978. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  3979. Result := True;
  3980. { Handle any overflows }
  3981. case taicpu(p).opsize of
  3982. S_B:
  3983. taicpu(p).oper[0]^.val := ThisConst and $FF;
  3984. S_W:
  3985. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  3986. S_L:
  3987. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  3988. {$ifdef x86_64}
  3989. S_Q:
  3990. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  3991. { Overflow; abort }
  3992. Result := False
  3993. else
  3994. taicpu(p).oper[0]^.val := ThisConst;
  3995. {$endif x86_64}
  3996. else
  3997. InternalError(2021102610);
  3998. end;
  3999. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4000. if Result then
  4001. begin
  4002. if (taicpu(p).oper[0]^.val < 0) and
  4003. (
  4004. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4005. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4006. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4007. ) then
  4008. begin
  4009. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4010. taicpu(p).opcode := A_SUB;
  4011. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4012. end
  4013. else
  4014. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4015. RemoveInstruction(hp1);
  4016. end;
  4017. end
  4018. else
  4019. begin
  4020. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4021. TransferUsedRegs(TmpUsedRegs);
  4022. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4023. hp2 := p;
  4024. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4025. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4026. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4027. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4028. begin
  4029. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4030. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4031. Asml.Remove(p);
  4032. Asml.InsertAfter(p, hp1);
  4033. p := hp1;
  4034. Result := True;
  4035. end;
  4036. end;
  4037. end;
  4038. end;
  4039. end;
  4040. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4041. var
  4042. hp1: tai;
  4043. ref: Integer;
  4044. saveref: treference;
  4045. TempReg: TRegister;
  4046. Multiple: TCGInt;
  4047. begin
  4048. Result:=false;
  4049. { removes seg register prefixes from LEA operations, as they
  4050. don't do anything}
  4051. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4052. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4053. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4054. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4055. (
  4056. { do not mess with leas accessing the stack pointer
  4057. unless it's a null operation }
  4058. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4059. (
  4060. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4061. (taicpu(p).oper[0]^.ref^.offset = 0)
  4062. )
  4063. ) and
  4064. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4065. begin
  4066. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4067. begin
  4068. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4069. begin
  4070. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4071. taicpu(p).oper[1]^.reg);
  4072. InsertLLItem(p.previous,p.next, hp1);
  4073. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4074. p.free;
  4075. p:=hp1;
  4076. end
  4077. else
  4078. begin
  4079. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4080. RemoveCurrentP(p);
  4081. end;
  4082. Result:=true;
  4083. exit;
  4084. end
  4085. else if (
  4086. { continue to use lea to adjust the stack pointer,
  4087. it is the recommended way, but only if not optimizing for size }
  4088. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4089. (cs_opt_size in current_settings.optimizerswitches)
  4090. ) and
  4091. { If the flags register is in use, don't change the instruction
  4092. to an ADD otherwise this will scramble the flags. [Kit] }
  4093. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4094. ConvertLEA(taicpu(p)) then
  4095. begin
  4096. Result:=true;
  4097. exit;
  4098. end;
  4099. end;
  4100. if GetNextInstruction(p,hp1) and
  4101. (hp1.typ=ait_instruction) then
  4102. begin
  4103. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4104. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4105. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4106. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4107. begin
  4108. TransferUsedRegs(TmpUsedRegs);
  4109. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4110. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4111. begin
  4112. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4113. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4114. RemoveInstruction(hp1);
  4115. result:=true;
  4116. exit;
  4117. end;
  4118. end;
  4119. { changes
  4120. lea <ref1>, reg1
  4121. <op> ...,<ref. with reg1>,...
  4122. to
  4123. <op> ...,<ref1>,... }
  4124. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4125. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4126. not(MatchInstruction(hp1,A_LEA,[])) then
  4127. begin
  4128. { find a reference which uses reg1 }
  4129. 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
  4130. ref:=0
  4131. 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
  4132. ref:=1
  4133. else
  4134. ref:=-1;
  4135. if (ref<>-1) and
  4136. { reg1 must be either the base or the index }
  4137. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4138. begin
  4139. { reg1 can be removed from the reference }
  4140. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4141. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4142. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4143. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4144. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4145. else
  4146. Internalerror(2019111201);
  4147. { check if the can insert all data of the lea into the second instruction }
  4148. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4149. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4150. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4151. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4152. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4153. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4154. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4155. {$ifdef x86_64}
  4156. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4157. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4158. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4159. )
  4160. {$endif x86_64}
  4161. then
  4162. begin
  4163. { reg1 might not used by the second instruction after it is remove from the reference }
  4164. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4165. begin
  4166. TransferUsedRegs(TmpUsedRegs);
  4167. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4168. { reg1 is not updated so it might not be used afterwards }
  4169. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4170. begin
  4171. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4172. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4173. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4174. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4175. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4176. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4177. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4178. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4179. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4180. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4181. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4182. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4183. RemoveCurrentP(p, hp1);
  4184. result:=true;
  4185. exit;
  4186. end
  4187. end;
  4188. end;
  4189. { recover }
  4190. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4191. end;
  4192. end;
  4193. end;
  4194. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4195. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4196. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4197. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4198. begin
  4199. { Check common LEA/LEA conditions }
  4200. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4201. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4202. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4203. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4204. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4205. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4206. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4207. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4208. (
  4209. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4210. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4211. ) and (
  4212. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4213. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4214. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4215. ) then
  4216. begin
  4217. { changes
  4218. lea (regX,scale), reg1
  4219. lea offset(reg1,reg1), reg1
  4220. to
  4221. lea offset(regX,scale*2), reg1
  4222. and
  4223. lea (regX,scale1), reg1
  4224. lea offset(reg1,scale2), reg1
  4225. to
  4226. lea offset(regX,scale1*scale2), reg1
  4227. ... so long as the final scale does not exceed 8
  4228. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4229. }
  4230. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4231. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4232. (
  4233. (
  4234. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4235. ) or (
  4236. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4237. (
  4238. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4239. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4240. )
  4241. )
  4242. ) and (
  4243. (
  4244. { lea (reg1,scale2), reg1 variant }
  4245. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4246. (
  4247. (
  4248. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4249. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4250. ) or (
  4251. { lea (regX,regX), reg1 variant }
  4252. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4253. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4254. )
  4255. )
  4256. ) or (
  4257. { lea (reg1,reg1), reg1 variant }
  4258. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4259. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4260. )
  4261. ) then
  4262. begin
  4263. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4264. { Make everything homogeneous to make calculations easier }
  4265. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4266. begin
  4267. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4268. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4269. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4270. else
  4271. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4272. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4273. end;
  4274. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4275. begin
  4276. { Just to prevent miscalculations }
  4277. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4278. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4279. else
  4280. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4281. end
  4282. else
  4283. begin
  4284. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4285. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4286. end;
  4287. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4288. RemoveCurrentP(p);
  4289. result:=true;
  4290. exit;
  4291. end
  4292. { changes
  4293. lea offset1(regX), reg1
  4294. lea offset2(reg1), reg1
  4295. to
  4296. lea offset1+offset2(regX), reg1 }
  4297. else if
  4298. (
  4299. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4300. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4301. ) or (
  4302. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4303. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4304. (
  4305. (
  4306. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4307. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4308. ) or (
  4309. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4310. (
  4311. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4312. (
  4313. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4314. (
  4315. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4316. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4317. )
  4318. )
  4319. )
  4320. )
  4321. )
  4322. ) then
  4323. begin
  4324. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4325. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4326. begin
  4327. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4328. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4329. { if the register is used as index and base, we have to increase for base as well
  4330. and adapt base }
  4331. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4332. begin
  4333. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4334. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4335. end;
  4336. end
  4337. else
  4338. begin
  4339. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4340. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4341. end;
  4342. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4343. begin
  4344. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4345. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4346. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4347. end;
  4348. RemoveCurrentP(p);
  4349. result:=true;
  4350. exit;
  4351. end;
  4352. end;
  4353. { Change:
  4354. leal/q $x(%reg1),%reg2
  4355. ...
  4356. shll/q $y,%reg2
  4357. To:
  4358. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4359. }
  4360. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4361. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4362. (taicpu(hp1).oper[0]^.val <= 3) then
  4363. begin
  4364. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4365. TransferUsedRegs(TmpUsedRegs);
  4366. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4367. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4368. if
  4369. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4370. (this works even if scalefactor is zero) }
  4371. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4372. { Ensure offset doesn't go out of bounds }
  4373. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4374. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4375. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4376. (
  4377. (
  4378. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4379. (
  4380. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4381. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4382. (
  4383. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4384. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4385. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4386. )
  4387. )
  4388. ) or (
  4389. (
  4390. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4391. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4392. ) and
  4393. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4394. )
  4395. ) then
  4396. begin
  4397. repeat
  4398. with taicpu(p).oper[0]^.ref^ do
  4399. begin
  4400. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4401. if index = base then
  4402. begin
  4403. if Multiple > 4 then
  4404. { Optimisation will no longer work because resultant
  4405. scale factor will exceed 8 }
  4406. Break;
  4407. base := NR_NO;
  4408. scalefactor := 2;
  4409. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4410. end
  4411. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4412. begin
  4413. { Scale factor only works on the index register }
  4414. index := base;
  4415. base := NR_NO;
  4416. end;
  4417. { For safety }
  4418. if scalefactor <= 1 then
  4419. begin
  4420. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4421. scalefactor := Multiple;
  4422. end
  4423. else
  4424. begin
  4425. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4426. scalefactor := scalefactor * Multiple;
  4427. end;
  4428. offset := offset * Multiple;
  4429. end;
  4430. RemoveInstruction(hp1);
  4431. Result := True;
  4432. Exit;
  4433. { This repeat..until loop exists for the benefit of Break }
  4434. until True;
  4435. end;
  4436. end;
  4437. end;
  4438. end;
  4439. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4440. var
  4441. hp1 : tai;
  4442. begin
  4443. DoSubAddOpt := False;
  4444. if taicpu(p).oper[0]^.typ <> top_const then
  4445. { Should have been confirmed before calling }
  4446. InternalError(2021102601);
  4447. if GetLastInstruction(p, hp1) and
  4448. (hp1.typ = ait_instruction) and
  4449. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4450. case taicpu(hp1).opcode Of
  4451. A_DEC:
  4452. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4453. begin
  4454. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4455. RemoveInstruction(hp1);
  4456. end;
  4457. A_SUB:
  4458. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4459. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4460. begin
  4461. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4462. RemoveInstruction(hp1);
  4463. end;
  4464. A_ADD:
  4465. begin
  4466. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4467. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4468. begin
  4469. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4470. RemoveInstruction(hp1);
  4471. if (taicpu(p).oper[0]^.val = 0) then
  4472. begin
  4473. hp1 := tai(p.next);
  4474. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4475. if not GetLastInstruction(hp1, p) then
  4476. p := hp1;
  4477. DoSubAddOpt := True;
  4478. end
  4479. end;
  4480. end;
  4481. else
  4482. ;
  4483. end;
  4484. end;
  4485. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4486. var
  4487. hp1, hp2: tai;
  4488. ActiveReg: TRegister;
  4489. OldOffset: asizeint;
  4490. ThisConst: TCGInt;
  4491. function RegDeallocated: Boolean;
  4492. begin
  4493. TransferUsedRegs(TmpUsedRegs);
  4494. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4495. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4496. end;
  4497. begin
  4498. Result:=false;
  4499. hp1 := nil;
  4500. { replace
  4501. subX const,%reg1
  4502. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4503. dealloc %reg1
  4504. by
  4505. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4506. }
  4507. if MatchOpType(taicpu(p),top_const,top_reg) then
  4508. begin
  4509. ActiveReg := taicpu(p).oper[1]^.reg;
  4510. { Ensures the entire register was updated }
  4511. if (taicpu(p).opsize >= S_L) and
  4512. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4513. MatchInstruction(hp1,A_LEA,[]) and
  4514. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4515. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4516. (
  4517. { Cover the case where the register in the reference is also the destination register }
  4518. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4519. (
  4520. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4521. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4522. RegDeallocated
  4523. )
  4524. ) then
  4525. begin
  4526. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4527. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4528. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4529. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4530. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4531. {$ifdef x86_64}
  4532. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4533. begin
  4534. { Overflow; abort }
  4535. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4536. end
  4537. else
  4538. {$endif x86_64}
  4539. begin
  4540. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4541. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4542. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4543. RemoveCurrentP(p, hp1)
  4544. else
  4545. RemoveCurrentP(p);
  4546. result:=true;
  4547. Exit;
  4548. end;
  4549. end;
  4550. if (
  4551. { Save calling GetNextInstructionUsingReg again }
  4552. Assigned(hp1) or
  4553. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4554. ) and
  4555. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4556. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4557. begin
  4558. if taicpu(hp1).oper[0]^.typ = top_const then
  4559. begin
  4560. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  4561. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  4562. Result := True;
  4563. { Handle any overflows }
  4564. case taicpu(p).opsize of
  4565. S_B:
  4566. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4567. S_W:
  4568. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4569. S_L:
  4570. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4571. {$ifdef x86_64}
  4572. S_Q:
  4573. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4574. { Overflow; abort }
  4575. Result := False
  4576. else
  4577. taicpu(p).oper[0]^.val := ThisConst;
  4578. {$endif x86_64}
  4579. else
  4580. InternalError(2021102610);
  4581. end;
  4582. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4583. if Result then
  4584. begin
  4585. if (taicpu(p).oper[0]^.val < 0) and
  4586. (
  4587. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4588. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4589. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4590. ) then
  4591. begin
  4592. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  4593. taicpu(p).opcode := A_SUB;
  4594. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4595. end
  4596. else
  4597. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  4598. RemoveInstruction(hp1);
  4599. end;
  4600. end
  4601. else
  4602. begin
  4603. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  4604. TransferUsedRegs(TmpUsedRegs);
  4605. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4606. hp2 := p;
  4607. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4608. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4609. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4610. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4611. begin
  4612. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  4613. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  4614. Asml.Remove(p);
  4615. Asml.InsertAfter(p, hp1);
  4616. p := hp1;
  4617. Result := True;
  4618. Exit;
  4619. end;
  4620. end;
  4621. end;
  4622. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4623. { * change "sub/add const1, reg" or "dec reg" followed by
  4624. "sub const2, reg" to one "sub ..., reg" }
  4625. {$ifdef i386}
  4626. if (taicpu(p).oper[0]^.val = 2) and
  4627. (ActiveReg = NR_ESP) and
  4628. { Don't do the sub/push optimization if the sub }
  4629. { comes from setting up the stack frame (JM) }
  4630. (not(GetLastInstruction(p,hp1)) or
  4631. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4632. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4633. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4634. begin
  4635. hp1 := tai(p.next);
  4636. while Assigned(hp1) and
  4637. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4638. not RegReadByInstruction(NR_ESP,hp1) and
  4639. not RegModifiedByInstruction(NR_ESP,hp1) do
  4640. hp1 := tai(hp1.next);
  4641. if Assigned(hp1) and
  4642. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4643. begin
  4644. taicpu(hp1).changeopsize(S_L);
  4645. if taicpu(hp1).oper[0]^.typ=top_reg then
  4646. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4647. hp1 := tai(p.next);
  4648. RemoveCurrentp(p, hp1);
  4649. Result:=true;
  4650. exit;
  4651. end;
  4652. end;
  4653. {$endif i386}
  4654. if DoSubAddOpt(p) then
  4655. Result:=true;
  4656. end;
  4657. end;
  4658. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4659. var
  4660. TmpBool1,TmpBool2 : Boolean;
  4661. tmpref : treference;
  4662. hp1,hp2: tai;
  4663. mask: tcgint;
  4664. begin
  4665. Result:=false;
  4666. { All these optimisations work on "shl/sal const,%reg" }
  4667. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4668. Exit;
  4669. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4670. (taicpu(p).oper[0]^.val <= 3) then
  4671. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4672. begin
  4673. { should we check the next instruction? }
  4674. TmpBool1 := True;
  4675. { have we found an add/sub which could be
  4676. integrated in the lea? }
  4677. TmpBool2 := False;
  4678. reference_reset(tmpref,2,[]);
  4679. TmpRef.index := taicpu(p).oper[1]^.reg;
  4680. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4681. while TmpBool1 and
  4682. GetNextInstruction(p, hp1) and
  4683. (tai(hp1).typ = ait_instruction) and
  4684. ((((taicpu(hp1).opcode = A_ADD) or
  4685. (taicpu(hp1).opcode = A_SUB)) and
  4686. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4687. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4688. (((taicpu(hp1).opcode = A_INC) or
  4689. (taicpu(hp1).opcode = A_DEC)) and
  4690. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4691. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4692. ((taicpu(hp1).opcode = A_LEA) and
  4693. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4694. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4695. (not GetNextInstruction(hp1,hp2) or
  4696. not instrReadsFlags(hp2)) Do
  4697. begin
  4698. TmpBool1 := False;
  4699. if taicpu(hp1).opcode=A_LEA then
  4700. begin
  4701. if (TmpRef.base = NR_NO) and
  4702. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4703. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4704. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4705. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4706. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4707. begin
  4708. TmpBool1 := True;
  4709. TmpBool2 := True;
  4710. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4711. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4712. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4713. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4714. RemoveInstruction(hp1);
  4715. end
  4716. end
  4717. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4718. begin
  4719. TmpBool1 := True;
  4720. TmpBool2 := True;
  4721. case taicpu(hp1).opcode of
  4722. A_ADD:
  4723. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4724. A_SUB:
  4725. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4726. else
  4727. internalerror(2019050536);
  4728. end;
  4729. RemoveInstruction(hp1);
  4730. end
  4731. else
  4732. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4733. (((taicpu(hp1).opcode = A_ADD) and
  4734. (TmpRef.base = NR_NO)) or
  4735. (taicpu(hp1).opcode = A_INC) or
  4736. (taicpu(hp1).opcode = A_DEC)) then
  4737. begin
  4738. TmpBool1 := True;
  4739. TmpBool2 := True;
  4740. case taicpu(hp1).opcode of
  4741. A_ADD:
  4742. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4743. A_INC:
  4744. inc(TmpRef.offset);
  4745. A_DEC:
  4746. dec(TmpRef.offset);
  4747. else
  4748. internalerror(2019050535);
  4749. end;
  4750. RemoveInstruction(hp1);
  4751. end;
  4752. end;
  4753. if TmpBool2
  4754. {$ifndef x86_64}
  4755. or
  4756. ((current_settings.optimizecputype < cpu_Pentium2) and
  4757. (taicpu(p).oper[0]^.val <= 3) and
  4758. not(cs_opt_size in current_settings.optimizerswitches))
  4759. {$endif x86_64}
  4760. then
  4761. begin
  4762. if not(TmpBool2) and
  4763. (taicpu(p).oper[0]^.val=1) then
  4764. begin
  4765. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4766. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4767. end
  4768. else
  4769. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4770. taicpu(p).oper[1]^.reg);
  4771. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4772. InsertLLItem(p.previous, p.next, hp1);
  4773. p.free;
  4774. p := hp1;
  4775. end;
  4776. end
  4777. {$ifndef x86_64}
  4778. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4779. begin
  4780. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4781. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4782. (unlike shl, which is only Tairable in the U pipe) }
  4783. if taicpu(p).oper[0]^.val=1 then
  4784. begin
  4785. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4786. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4787. InsertLLItem(p.previous, p.next, hp1);
  4788. p.free;
  4789. p := hp1;
  4790. end
  4791. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4792. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4793. else if (taicpu(p).opsize = S_L) and
  4794. (taicpu(p).oper[0]^.val<= 3) then
  4795. begin
  4796. reference_reset(tmpref,2,[]);
  4797. TmpRef.index := taicpu(p).oper[1]^.reg;
  4798. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4799. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4800. InsertLLItem(p.previous, p.next, hp1);
  4801. p.free;
  4802. p := hp1;
  4803. end;
  4804. end
  4805. {$endif x86_64}
  4806. else if
  4807. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4808. (
  4809. (
  4810. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4811. SetAndTest(hp1, hp2)
  4812. {$ifdef x86_64}
  4813. ) or
  4814. (
  4815. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4816. GetNextInstruction(hp1, hp2) and
  4817. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4818. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4819. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4820. {$endif x86_64}
  4821. )
  4822. ) and
  4823. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4824. begin
  4825. { Change:
  4826. shl x, %reg1
  4827. mov -(1<<x), %reg2
  4828. and %reg2, %reg1
  4829. Or:
  4830. shl x, %reg1
  4831. and -(1<<x), %reg1
  4832. To just:
  4833. shl x, %reg1
  4834. Since the and operation only zeroes bits that are already zero from the shl operation
  4835. }
  4836. case taicpu(p).oper[0]^.val of
  4837. 8:
  4838. mask:=$FFFFFFFFFFFFFF00;
  4839. 16:
  4840. mask:=$FFFFFFFFFFFF0000;
  4841. 32:
  4842. mask:=$FFFFFFFF00000000;
  4843. 63:
  4844. { Constant pre-calculated to prevent overflow errors with Int64 }
  4845. mask:=$8000000000000000;
  4846. else
  4847. begin
  4848. if taicpu(p).oper[0]^.val >= 64 then
  4849. { Shouldn't happen realistically, since the register
  4850. is guaranteed to be set to zero at this point }
  4851. mask := 0
  4852. else
  4853. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4854. end;
  4855. end;
  4856. if taicpu(hp1).oper[0]^.val = mask then
  4857. begin
  4858. { Everything checks out, perform the optimisation, as long as
  4859. the FLAGS register isn't being used}
  4860. TransferUsedRegs(TmpUsedRegs);
  4861. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4862. {$ifdef x86_64}
  4863. if (hp1 <> hp2) then
  4864. begin
  4865. { "shl/mov/and" version }
  4866. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4867. { Don't do the optimisation if the FLAGS register is in use }
  4868. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4869. begin
  4870. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4871. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4872. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4873. begin
  4874. RemoveInstruction(hp1);
  4875. Result := True;
  4876. end;
  4877. { Only set Result to True if the 'mov' instruction was removed }
  4878. RemoveInstruction(hp2);
  4879. end;
  4880. end
  4881. else
  4882. {$endif x86_64}
  4883. begin
  4884. { "shl/and" version }
  4885. { Don't do the optimisation if the FLAGS register is in use }
  4886. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4887. begin
  4888. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4889. RemoveInstruction(hp1);
  4890. Result := True;
  4891. end;
  4892. end;
  4893. Exit;
  4894. end
  4895. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4896. begin
  4897. { Even if the mask doesn't allow for its removal, we might be
  4898. able to optimise the mask for the "shl/and" version, which
  4899. may permit other peephole optimisations }
  4900. {$ifdef DEBUG_AOPTCPU}
  4901. mask := taicpu(hp1).oper[0]^.val and mask;
  4902. if taicpu(hp1).oper[0]^.val <> mask then
  4903. begin
  4904. DebugMsg(
  4905. SPeepholeOptimization +
  4906. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4907. ' to $' + debug_tostr(mask) +
  4908. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4909. taicpu(hp1).oper[0]^.val := mask;
  4910. end;
  4911. {$else DEBUG_AOPTCPU}
  4912. { If debugging is off, just set the operand even if it's the same }
  4913. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4914. {$endif DEBUG_AOPTCPU}
  4915. end;
  4916. end;
  4917. {
  4918. change
  4919. shl/sal const,reg
  4920. <op> ...(...,reg,1),...
  4921. into
  4922. <op> ...(...,reg,1 shl const),...
  4923. if const in 1..3
  4924. }
  4925. if MatchOpType(taicpu(p), top_const, top_reg) and
  4926. (taicpu(p).oper[0]^.val in [1..3]) and
  4927. GetNextInstruction(p, hp1) and
  4928. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4929. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4930. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4931. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4932. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4933. begin
  4934. TransferUsedRegs(TmpUsedRegs);
  4935. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4936. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4937. begin
  4938. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4939. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4940. RemoveCurrentP(p);
  4941. Result:=true;
  4942. end;
  4943. end;
  4944. end;
  4945. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4946. var
  4947. CurrentRef: TReference;
  4948. FullReg: TRegister;
  4949. hp1, hp2: tai;
  4950. begin
  4951. Result := False;
  4952. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4953. Exit;
  4954. { We assume you've checked if the operand is actually a reference by
  4955. this point. If it isn't, you'll most likely get an access violation }
  4956. CurrentRef := first_mov.oper[1]^.ref^;
  4957. { Memory must be aligned }
  4958. if (CurrentRef.offset mod 4) <> 0 then
  4959. Exit;
  4960. Inc(CurrentRef.offset);
  4961. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4962. if MatchOperand(second_mov.oper[0]^, 0) and
  4963. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4964. GetNextInstruction(second_mov, hp1) and
  4965. (hp1.typ = ait_instruction) and
  4966. (taicpu(hp1).opcode = A_MOV) and
  4967. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4968. (taicpu(hp1).oper[0]^.val = 0) then
  4969. begin
  4970. Inc(CurrentRef.offset);
  4971. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4972. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4973. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4974. begin
  4975. case taicpu(hp1).opsize of
  4976. S_B:
  4977. if GetNextInstruction(hp1, hp2) and
  4978. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4979. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4980. (taicpu(hp2).oper[0]^.val = 0) then
  4981. begin
  4982. Inc(CurrentRef.offset);
  4983. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4984. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4985. (taicpu(hp2).opsize = S_B) then
  4986. begin
  4987. RemoveInstruction(hp1);
  4988. RemoveInstruction(hp2);
  4989. first_mov.opsize := S_L;
  4990. if first_mov.oper[0]^.typ = top_reg then
  4991. begin
  4992. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4993. { Reuse second_mov as a MOVZX instruction }
  4994. second_mov.opcode := A_MOVZX;
  4995. second_mov.opsize := S_BL;
  4996. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4997. second_mov.loadreg(1, FullReg);
  4998. first_mov.oper[0]^.reg := FullReg;
  4999. asml.Remove(second_mov);
  5000. asml.InsertBefore(second_mov, first_mov);
  5001. end
  5002. else
  5003. { It's a value }
  5004. begin
  5005. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5006. RemoveInstruction(second_mov);
  5007. end;
  5008. Result := True;
  5009. Exit;
  5010. end;
  5011. end;
  5012. S_W:
  5013. begin
  5014. RemoveInstruction(hp1);
  5015. first_mov.opsize := S_L;
  5016. if first_mov.oper[0]^.typ = top_reg then
  5017. begin
  5018. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5019. { Reuse second_mov as a MOVZX instruction }
  5020. second_mov.opcode := A_MOVZX;
  5021. second_mov.opsize := S_BL;
  5022. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5023. second_mov.loadreg(1, FullReg);
  5024. first_mov.oper[0]^.reg := FullReg;
  5025. asml.Remove(second_mov);
  5026. asml.InsertBefore(second_mov, first_mov);
  5027. end
  5028. else
  5029. { It's a value }
  5030. begin
  5031. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5032. RemoveInstruction(second_mov);
  5033. end;
  5034. Result := True;
  5035. Exit;
  5036. end;
  5037. else
  5038. ;
  5039. end;
  5040. end;
  5041. end;
  5042. end;
  5043. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5044. { returns true if a "continue" should be done after this optimization }
  5045. var
  5046. hp1, hp2: tai;
  5047. begin
  5048. Result := false;
  5049. if MatchOpType(taicpu(p),top_ref) and
  5050. GetNextInstruction(p, hp1) and
  5051. (hp1.typ = ait_instruction) and
  5052. (((taicpu(hp1).opcode = A_FLD) and
  5053. (taicpu(p).opcode = A_FSTP)) or
  5054. ((taicpu(p).opcode = A_FISTP) and
  5055. (taicpu(hp1).opcode = A_FILD))) and
  5056. MatchOpType(taicpu(hp1),top_ref) and
  5057. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5058. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5059. begin
  5060. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5061. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5062. GetNextInstruction(hp1, hp2) and
  5063. (hp2.typ = ait_instruction) and
  5064. IsExitCode(hp2) and
  5065. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5066. not(assigned(current_procinfo.procdef.funcretsym) and
  5067. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5068. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5069. begin
  5070. RemoveInstruction(hp1);
  5071. RemoveCurrentP(p, hp2);
  5072. RemoveLastDeallocForFuncRes(p);
  5073. Result := true;
  5074. end
  5075. else
  5076. { we can do this only in fast math mode as fstp is rounding ...
  5077. ... still disabled as it breaks the compiler and/or rtl }
  5078. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5079. { ... or if another fstp equal to the first one follows }
  5080. (GetNextInstruction(hp1,hp2) and
  5081. (hp2.typ = ait_instruction) and
  5082. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5083. (taicpu(p).opsize=taicpu(hp2).opsize))
  5084. ) and
  5085. { fst can't store an extended/comp value }
  5086. (taicpu(p).opsize <> S_FX) and
  5087. (taicpu(p).opsize <> S_IQ) then
  5088. begin
  5089. if (taicpu(p).opcode = A_FSTP) then
  5090. taicpu(p).opcode := A_FST
  5091. else
  5092. taicpu(p).opcode := A_FIST;
  5093. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5094. RemoveInstruction(hp1);
  5095. end;
  5096. end;
  5097. end;
  5098. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5099. var
  5100. hp1, hp2: tai;
  5101. begin
  5102. result:=false;
  5103. if MatchOpType(taicpu(p),top_reg) and
  5104. GetNextInstruction(p, hp1) and
  5105. (hp1.typ = Ait_Instruction) and
  5106. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5107. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5108. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5109. { change to
  5110. fld reg fxxx reg,st
  5111. fxxxp st, st1 (hp1)
  5112. Remark: non commutative operations must be reversed!
  5113. }
  5114. begin
  5115. case taicpu(hp1).opcode Of
  5116. A_FMULP,A_FADDP,
  5117. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5118. begin
  5119. case taicpu(hp1).opcode Of
  5120. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5121. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5122. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5123. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5124. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5125. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5126. else
  5127. internalerror(2019050534);
  5128. end;
  5129. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5130. taicpu(hp1).oper[1]^.reg := NR_ST;
  5131. RemoveCurrentP(p, hp1);
  5132. Result:=true;
  5133. exit;
  5134. end;
  5135. else
  5136. ;
  5137. end;
  5138. end
  5139. else
  5140. if MatchOpType(taicpu(p),top_ref) and
  5141. GetNextInstruction(p, hp2) and
  5142. (hp2.typ = Ait_Instruction) and
  5143. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5144. (taicpu(p).opsize in [S_FS, S_FL]) and
  5145. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5146. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5147. if GetLastInstruction(p, hp1) and
  5148. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5149. MatchOpType(taicpu(hp1),top_ref) and
  5150. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5151. if ((taicpu(hp2).opcode = A_FMULP) or
  5152. (taicpu(hp2).opcode = A_FADDP)) then
  5153. { change to
  5154. fld/fst mem1 (hp1) fld/fst mem1
  5155. fld mem1 (p) fadd/
  5156. faddp/ fmul st, st
  5157. fmulp st, st1 (hp2) }
  5158. begin
  5159. RemoveCurrentP(p, hp1);
  5160. if (taicpu(hp2).opcode = A_FADDP) then
  5161. taicpu(hp2).opcode := A_FADD
  5162. else
  5163. taicpu(hp2).opcode := A_FMUL;
  5164. taicpu(hp2).oper[1]^.reg := NR_ST;
  5165. end
  5166. else
  5167. { change to
  5168. fld/fst mem1 (hp1) fld/fst mem1
  5169. fld mem1 (p) fld st}
  5170. begin
  5171. taicpu(p).changeopsize(S_FL);
  5172. taicpu(p).loadreg(0,NR_ST);
  5173. end
  5174. else
  5175. begin
  5176. case taicpu(hp2).opcode Of
  5177. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5178. { change to
  5179. fld/fst mem1 (hp1) fld/fst mem1
  5180. fld mem2 (p) fxxx mem2
  5181. fxxxp st, st1 (hp2) }
  5182. begin
  5183. case taicpu(hp2).opcode Of
  5184. A_FADDP: taicpu(p).opcode := A_FADD;
  5185. A_FMULP: taicpu(p).opcode := A_FMUL;
  5186. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5187. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5188. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5189. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5190. else
  5191. internalerror(2019050533);
  5192. end;
  5193. RemoveInstruction(hp2);
  5194. end
  5195. else
  5196. ;
  5197. end
  5198. end
  5199. end;
  5200. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5201. begin
  5202. Result := condition_in(cond1, cond2) or
  5203. { Not strictly subsets due to the actual flags checked, but because we're
  5204. comparing integers, E is a subset of AE and GE and their aliases }
  5205. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5206. end;
  5207. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5208. var
  5209. v: TCGInt;
  5210. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5211. FirstMatch: Boolean;
  5212. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5213. begin
  5214. Result:=false;
  5215. { All these optimisations need a next instruction }
  5216. if not GetNextInstruction(p, hp1) then
  5217. Exit;
  5218. { Search for:
  5219. cmp ###,###
  5220. j(c1) @lbl1
  5221. ...
  5222. @lbl:
  5223. cmp ###.### (same comparison as above)
  5224. j(c2) @lbl2
  5225. If c1 is a subset of c2, change to:
  5226. cmp ###,###
  5227. j(c2) @lbl2
  5228. (@lbl1 may become a dead label as a result)
  5229. }
  5230. { Also handle cases where there are multiple jumps in a row }
  5231. p_jump := hp1;
  5232. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5233. begin
  5234. if IsJumpToLabel(taicpu(p_jump)) then
  5235. begin
  5236. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5237. p_label := nil;
  5238. if Assigned(JumpLabel) then
  5239. p_label := getlabelwithsym(JumpLabel);
  5240. if Assigned(p_label) and
  5241. GetNextInstruction(p_label, p_dist) and
  5242. MatchInstruction(p_dist, A_CMP, []) and
  5243. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5244. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5245. GetNextInstruction(p_dist, hp1_dist) and
  5246. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5247. begin
  5248. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5249. if JumpLabel = JumpLabel_dist then
  5250. { This is an infinite loop }
  5251. Exit;
  5252. { Best optimisation when the first condition is a subset (or equal) of the second }
  5253. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5254. begin
  5255. { Any registers used here will already be allocated }
  5256. if Assigned(JumpLabel_dist) then
  5257. JumpLabel_dist.IncRefs;
  5258. if Assigned(JumpLabel) then
  5259. JumpLabel.DecRefs;
  5260. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5261. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5262. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5263. Result := True;
  5264. { Don't exit yet. Since p and p_jump haven't actually been
  5265. removed, we can check for more on this iteration }
  5266. end
  5267. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5268. GetNextInstruction(hp1_dist, hp1_label) and
  5269. SkipAligns(hp1_label, hp1_label) and
  5270. (hp1_label.typ = ait_label) then
  5271. begin
  5272. JumpLabel_far := tai_label(hp1_label).labsym;
  5273. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5274. { This is an infinite loop }
  5275. Exit;
  5276. if Assigned(JumpLabel_far) then
  5277. begin
  5278. { In this situation, if the first jump branches, the second one will never,
  5279. branch so change the destination label to after the second jump }
  5280. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5281. if Assigned(JumpLabel) then
  5282. JumpLabel.DecRefs;
  5283. JumpLabel_far.IncRefs;
  5284. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5285. Result := True;
  5286. { Don't exit yet. Since p and p_jump haven't actually been
  5287. removed, we can check for more on this iteration }
  5288. Continue;
  5289. end;
  5290. end;
  5291. end;
  5292. end;
  5293. { Search for:
  5294. cmp ###,###
  5295. j(c1) @lbl1
  5296. cmp ###,### (same as first)
  5297. Remove second cmp
  5298. }
  5299. if GetNextInstruction(p_jump, hp2) and
  5300. (
  5301. (
  5302. MatchInstruction(hp2, A_CMP, []) and
  5303. (
  5304. (
  5305. MatchOpType(taicpu(p), top_const, top_reg) and
  5306. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5307. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5308. ) or (
  5309. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5310. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5311. )
  5312. )
  5313. ) or (
  5314. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5315. MatchOperand(taicpu(p).oper[0]^, 0) and
  5316. (taicpu(p).oper[1]^.typ = top_reg) and
  5317. MatchInstruction(hp2, A_TEST, []) and
  5318. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5319. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5320. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5321. )
  5322. ) then
  5323. begin
  5324. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5325. RemoveInstruction(hp2);
  5326. Result := True;
  5327. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5328. end;
  5329. GetNextInstruction(p_jump, p_jump);
  5330. end;
  5331. if taicpu(p).oper[0]^.typ = top_const then
  5332. begin
  5333. if (taicpu(p).oper[0]^.val = 0) and
  5334. (taicpu(p).oper[1]^.typ = top_reg) and
  5335. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5336. begin
  5337. hp2 := p;
  5338. FirstMatch := True;
  5339. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5340. anything meaningful once it's converted to "test %reg,%reg";
  5341. additionally, some jumps will always (or never) branch, so
  5342. evaluate every jump immediately following the
  5343. comparison, optimising the conditions if possible.
  5344. Similarly with SETcc... those that are always set to 0 or 1
  5345. are changed to MOV instructions }
  5346. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5347. (
  5348. GetNextInstruction(hp2, hp1) and
  5349. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5350. ) do
  5351. begin
  5352. FirstMatch := False;
  5353. case taicpu(hp1).condition of
  5354. C_B, C_C, C_NAE, C_O:
  5355. { For B/NAE:
  5356. Will never branch since an unsigned integer can never be below zero
  5357. For C/O:
  5358. Result cannot overflow because 0 is being subtracted
  5359. }
  5360. begin
  5361. if taicpu(hp1).opcode = A_Jcc then
  5362. begin
  5363. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5364. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5365. RemoveInstruction(hp1);
  5366. { Since hp1 was deleted, hp2 must not be updated }
  5367. Continue;
  5368. end
  5369. else
  5370. begin
  5371. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5372. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5373. taicpu(hp1).opcode := A_MOV;
  5374. taicpu(hp1).ops := 2;
  5375. taicpu(hp1).condition := C_None;
  5376. taicpu(hp1).opsize := S_B;
  5377. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5378. taicpu(hp1).loadconst(0, 0);
  5379. end;
  5380. end;
  5381. C_BE, C_NA:
  5382. begin
  5383. { Will only branch if equal to zero }
  5384. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5385. taicpu(hp1).condition := C_E;
  5386. end;
  5387. C_A, C_NBE:
  5388. begin
  5389. { Will only branch if not equal to zero }
  5390. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5391. taicpu(hp1).condition := C_NE;
  5392. end;
  5393. C_AE, C_NB, C_NC, C_NO:
  5394. begin
  5395. { Will always branch }
  5396. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5397. if taicpu(hp1).opcode = A_Jcc then
  5398. begin
  5399. MakeUnconditional(taicpu(hp1));
  5400. { Any jumps/set that follow will now be dead code }
  5401. RemoveDeadCodeAfterJump(taicpu(hp1));
  5402. Break;
  5403. end
  5404. else
  5405. begin
  5406. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5407. taicpu(hp1).opcode := A_MOV;
  5408. taicpu(hp1).ops := 2;
  5409. taicpu(hp1).condition := C_None;
  5410. taicpu(hp1).opsize := S_B;
  5411. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5412. taicpu(hp1).loadconst(0, 1);
  5413. end;
  5414. end;
  5415. C_None:
  5416. InternalError(2020012201);
  5417. C_P, C_PE, C_NP, C_PO:
  5418. { We can't handle parity checks and they should never be generated
  5419. after a general-purpose CMP (it's used in some floating-point
  5420. comparisons that don't use CMP) }
  5421. InternalError(2020012202);
  5422. else
  5423. { Zero/Equality, Sign, their complements and all of the
  5424. signed comparisons do not need to be converted };
  5425. end;
  5426. hp2 := hp1;
  5427. end;
  5428. { Convert the instruction to a TEST }
  5429. taicpu(p).opcode := A_TEST;
  5430. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5431. Result := True;
  5432. Exit;
  5433. end
  5434. else if (taicpu(p).oper[0]^.val = 1) and
  5435. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5436. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5437. begin
  5438. { Convert; To:
  5439. cmp $1,r/m cmp $0,r/m
  5440. jl @lbl jle @lbl
  5441. }
  5442. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5443. taicpu(p).oper[0]^.val := 0;
  5444. taicpu(hp1).condition := C_LE;
  5445. { If the instruction is now "cmp $0,%reg", convert it to a
  5446. TEST (and effectively do the work of the "cmp $0,%reg" in
  5447. the block above)
  5448. If it's a reference, we can get away with not setting
  5449. Result to True because he haven't evaluated the jump
  5450. in this pass yet.
  5451. }
  5452. if (taicpu(p).oper[1]^.typ = top_reg) then
  5453. begin
  5454. taicpu(p).opcode := A_TEST;
  5455. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5456. Result := True;
  5457. end;
  5458. Exit;
  5459. end
  5460. else if (taicpu(p).oper[1]^.typ = top_reg)
  5461. {$ifdef x86_64}
  5462. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5463. {$endif x86_64}
  5464. then
  5465. begin
  5466. { cmp register,$8000 neg register
  5467. je target --> jo target
  5468. .... only if register is deallocated before jump.}
  5469. case Taicpu(p).opsize of
  5470. S_B: v:=$80;
  5471. S_W: v:=$8000;
  5472. S_L: v:=qword($80000000);
  5473. else
  5474. internalerror(2013112905);
  5475. end;
  5476. if (taicpu(p).oper[0]^.val=v) and
  5477. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5478. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5479. begin
  5480. TransferUsedRegs(TmpUsedRegs);
  5481. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5482. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5483. begin
  5484. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5485. Taicpu(p).opcode:=A_NEG;
  5486. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5487. Taicpu(p).clearop(1);
  5488. Taicpu(p).ops:=1;
  5489. if Taicpu(hp1).condition=C_E then
  5490. Taicpu(hp1).condition:=C_O
  5491. else
  5492. Taicpu(hp1).condition:=C_NO;
  5493. Result:=true;
  5494. exit;
  5495. end;
  5496. end;
  5497. end;
  5498. end;
  5499. if TrySwapMovCmp(p, hp1) then
  5500. begin
  5501. Result := True;
  5502. Exit;
  5503. end;
  5504. end;
  5505. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5506. var
  5507. hp1: tai;
  5508. begin
  5509. {
  5510. remove the second (v)pxor from
  5511. pxor reg,reg
  5512. ...
  5513. pxor reg,reg
  5514. }
  5515. Result:=false;
  5516. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5517. MatchOpType(taicpu(p),top_reg,top_reg) and
  5518. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5519. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5520. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5521. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5522. begin
  5523. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5524. RemoveInstruction(hp1);
  5525. Result:=true;
  5526. Exit;
  5527. end
  5528. {
  5529. replace
  5530. pxor reg1,reg1
  5531. movapd/s reg1,reg2
  5532. dealloc reg1
  5533. by
  5534. pxor reg2,reg2
  5535. }
  5536. else if GetNextInstruction(p,hp1) and
  5537. { we mix single and double opperations here because we assume that the compiler
  5538. generates vmovapd only after double operations and vmovaps only after single operations }
  5539. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5540. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5541. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5542. (taicpu(p).oper[0]^.typ=top_reg) then
  5543. begin
  5544. TransferUsedRegs(TmpUsedRegs);
  5545. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5546. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5547. begin
  5548. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5549. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5550. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5551. RemoveInstruction(hp1);
  5552. result:=true;
  5553. end;
  5554. end;
  5555. end;
  5556. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5557. var
  5558. hp1: tai;
  5559. begin
  5560. {
  5561. remove the second (v)pxor from
  5562. (v)pxor reg,reg
  5563. ...
  5564. (v)pxor reg,reg
  5565. }
  5566. Result:=false;
  5567. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5568. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5569. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5570. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5571. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5572. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5573. begin
  5574. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5575. RemoveInstruction(hp1);
  5576. Result:=true;
  5577. Exit;
  5578. end
  5579. else
  5580. Result:=OptPass1VOP(p);
  5581. end;
  5582. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5583. var
  5584. hp1 : tai;
  5585. begin
  5586. result:=false;
  5587. { replace
  5588. IMul const,%mreg1,%mreg2
  5589. Mov %reg2,%mreg3
  5590. dealloc %mreg3
  5591. by
  5592. Imul const,%mreg1,%mreg23
  5593. }
  5594. if (taicpu(p).ops=3) and
  5595. GetNextInstruction(p,hp1) and
  5596. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5597. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5598. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5599. begin
  5600. TransferUsedRegs(TmpUsedRegs);
  5601. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5602. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5603. begin
  5604. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5605. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5606. RemoveInstruction(hp1);
  5607. result:=true;
  5608. end;
  5609. end;
  5610. end;
  5611. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5612. var
  5613. hp1 : tai;
  5614. begin
  5615. result:=false;
  5616. { replace
  5617. IMul %reg0,%reg1,%reg2
  5618. Mov %reg2,%reg3
  5619. dealloc %reg2
  5620. by
  5621. Imul %reg0,%reg1,%reg3
  5622. }
  5623. if GetNextInstruction(p,hp1) and
  5624. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5625. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5626. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5627. begin
  5628. TransferUsedRegs(TmpUsedRegs);
  5629. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5630. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5631. begin
  5632. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5633. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5634. RemoveInstruction(hp1);
  5635. result:=true;
  5636. end;
  5637. end;
  5638. end;
  5639. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  5640. var
  5641. hp1: tai;
  5642. begin
  5643. Result:=false;
  5644. { get rid of
  5645. (v)cvtss2sd reg0,<reg1,>reg2
  5646. (v)cvtss2sd reg2,<reg2,>reg0
  5647. }
  5648. if GetNextInstruction(p,hp1) and
  5649. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  5650. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  5651. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  5652. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5653. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  5654. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5655. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5656. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  5657. )
  5658. ) then
  5659. begin
  5660. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  5661. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  5662. begin
  5663. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  5664. RemoveCurrentP(p);
  5665. RemoveInstruction(hp1);
  5666. end
  5667. else
  5668. begin
  5669. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  5670. if taicpu(hp1).opcode=A_CVTSD2SS then
  5671. begin
  5672. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  5673. taicpu(p).opcode:=A_MOVAPS;
  5674. end
  5675. else
  5676. begin
  5677. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  5678. taicpu(p).opcode:=A_VMOVAPS;
  5679. end;
  5680. taicpu(p).ops:=2;
  5681. RemoveInstruction(hp1);
  5682. end;
  5683. Result:=true;
  5684. Exit;
  5685. end;
  5686. end;
  5687. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5688. var
  5689. hp1, hp2, hp3, hp4, hp5: tai;
  5690. ThisReg: TRegister;
  5691. begin
  5692. Result := False;
  5693. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5694. Exit;
  5695. {
  5696. convert
  5697. j<c> .L1
  5698. mov 1,reg
  5699. jmp .L2
  5700. .L1
  5701. mov 0,reg
  5702. .L2
  5703. into
  5704. mov 0,reg
  5705. set<not(c)> reg
  5706. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5707. would destroy the flag contents
  5708. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5709. executed at the same time as a previous comparison.
  5710. set<not(c)> reg
  5711. movzx reg, reg
  5712. }
  5713. if MatchInstruction(hp1,A_MOV,[]) and
  5714. (taicpu(hp1).oper[0]^.typ = top_const) and
  5715. (
  5716. (
  5717. (taicpu(hp1).oper[1]^.typ = top_reg)
  5718. {$ifdef i386}
  5719. { Under i386, ESI, EDI, EBP and ESP
  5720. don't have an 8-bit representation }
  5721. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5722. {$endif i386}
  5723. ) or (
  5724. {$ifdef i386}
  5725. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5726. {$endif i386}
  5727. (taicpu(hp1).opsize = S_B)
  5728. )
  5729. ) and
  5730. GetNextInstruction(hp1,hp2) and
  5731. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5732. GetNextInstruction(hp2,hp3) and
  5733. SkipAligns(hp3, hp3) and
  5734. (hp3.typ=ait_label) and
  5735. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5736. GetNextInstruction(hp3,hp4) and
  5737. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5738. (taicpu(hp4).oper[0]^.typ = top_const) and
  5739. (
  5740. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5741. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5742. ) and
  5743. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5744. GetNextInstruction(hp4,hp5) and
  5745. SkipAligns(hp5, hp5) and
  5746. (hp5.typ=ait_label) and
  5747. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5748. begin
  5749. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5750. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5751. tai_label(hp3).labsym.DecRefs;
  5752. { If this isn't the only reference to the middle label, we can
  5753. still make a saving - only that the first jump and everything
  5754. that follows will remain. }
  5755. if (tai_label(hp3).labsym.getrefs = 0) then
  5756. begin
  5757. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5758. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5759. else
  5760. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5761. { remove jump, first label and second MOV (also catching any aligns) }
  5762. repeat
  5763. if not GetNextInstruction(hp2, hp3) then
  5764. InternalError(2021040810);
  5765. RemoveInstruction(hp2);
  5766. hp2 := hp3;
  5767. until hp2 = hp5;
  5768. { Don't decrement reference count before the removal loop
  5769. above, otherwise GetNextInstruction won't stop on the
  5770. the label }
  5771. tai_label(hp5).labsym.DecRefs;
  5772. end
  5773. else
  5774. begin
  5775. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5776. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5777. else
  5778. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5779. end;
  5780. taicpu(p).opcode:=A_SETcc;
  5781. taicpu(p).opsize:=S_B;
  5782. taicpu(p).is_jmp:=False;
  5783. if taicpu(hp1).opsize=S_B then
  5784. begin
  5785. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5786. if taicpu(hp1).oper[1]^.typ = top_reg then
  5787. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  5788. RemoveInstruction(hp1);
  5789. end
  5790. else
  5791. begin
  5792. { Will be a register because the size can't be S_B otherwise }
  5793. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5794. taicpu(p).loadreg(0, ThisReg);
  5795. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  5796. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5797. begin
  5798. case taicpu(hp1).opsize of
  5799. S_W:
  5800. taicpu(hp1).opsize := S_BW;
  5801. S_L:
  5802. taicpu(hp1).opsize := S_BL;
  5803. {$ifdef x86_64}
  5804. S_Q:
  5805. begin
  5806. taicpu(hp1).opsize := S_BL;
  5807. { Change the destination register to 32-bit }
  5808. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5809. end;
  5810. {$endif x86_64}
  5811. else
  5812. InternalError(2021040820);
  5813. end;
  5814. taicpu(hp1).opcode := A_MOVZX;
  5815. taicpu(hp1).loadreg(0, ThisReg);
  5816. end
  5817. else
  5818. begin
  5819. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5820. { hp1 is already a MOV instruction with the correct register }
  5821. taicpu(hp1).loadconst(0, 0);
  5822. { Inserting it right before p will guarantee that the flags are also tracked }
  5823. asml.Remove(hp1);
  5824. asml.InsertBefore(hp1, p);
  5825. end;
  5826. end;
  5827. Result:=true;
  5828. exit;
  5829. end
  5830. end;
  5831. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  5832. var
  5833. hp1, hp2, hp3: tai;
  5834. SourceRef, TargetRef: TReference;
  5835. CurrentReg: TRegister;
  5836. begin
  5837. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  5838. if not UseAVX then
  5839. InternalError(2021100501);
  5840. Result := False;
  5841. { Look for the following to simplify:
  5842. vmovdqa/u x(mem1), %xmmreg
  5843. vmovdqa/u %xmmreg, y(mem2)
  5844. vmovdqa/u x+16(mem1), %xmmreg
  5845. vmovdqa/u %xmmreg, y+16(mem2)
  5846. Change to:
  5847. vmovdqa/u x(mem1), %ymmreg
  5848. vmovdqa/u %ymmreg, y(mem2)
  5849. vpxor %ymmreg, %ymmreg, %ymmreg
  5850. ( The VPXOR instruction is to zero the upper half, thus removing the
  5851. need to call the potentially expensive VZEROUPPER instruction. Other
  5852. peephole optimisations can remove VPXOR if it's unnecessary )
  5853. }
  5854. TransferUsedRegs(TmpUsedRegs);
  5855. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5856. { NOTE: In the optimisations below, if the references dictate that an
  5857. aligned move is possible (i.e. VMOVDQA), the existing instructions
  5858. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  5859. if (taicpu(p).opsize = S_XMM) and
  5860. MatchOpType(taicpu(p), top_ref, top_reg) and
  5861. GetNextInstruction(p, hp1) and
  5862. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5863. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  5864. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5865. begin
  5866. SourceRef := taicpu(p).oper[0]^.ref^;
  5867. TargetRef := taicpu(hp1).oper[1]^.ref^;
  5868. if GetNextInstruction(hp1, hp2) and
  5869. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5870. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  5871. begin
  5872. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  5873. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5874. Inc(SourceRef.offset, 16);
  5875. { Reuse the register in the first block move }
  5876. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  5877. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  5878. begin
  5879. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5880. Inc(TargetRef.offset, 16);
  5881. if GetNextInstruction(hp2, hp3) and
  5882. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5883. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  5884. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  5885. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  5886. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  5887. begin
  5888. { Update the register tracking to the new size }
  5889. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  5890. { Remember that the offsets are 16 ahead }
  5891. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  5892. if not (
  5893. ((SourceRef.offset mod 32) = 16) and
  5894. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  5895. ) then
  5896. taicpu(p).opcode := A_VMOVDQU;
  5897. taicpu(p).opsize := S_YMM;
  5898. taicpu(p).oper[1]^.reg := CurrentReg;
  5899. if not (
  5900. ((TargetRef.offset mod 32) = 16) and
  5901. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  5902. ) then
  5903. taicpu(hp1).opcode := A_VMOVDQU;
  5904. taicpu(hp1).opsize := S_YMM;
  5905. taicpu(hp1).oper[0]^.reg := CurrentReg;
  5906. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  5907. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  5908. if (pi_uses_ymm in current_procinfo.flags) then
  5909. RemoveInstruction(hp2)
  5910. else
  5911. begin
  5912. taicpu(hp2).opcode := A_VPXOR;
  5913. taicpu(hp2).opsize := S_YMM;
  5914. taicpu(hp2).loadreg(0, CurrentReg);
  5915. taicpu(hp2).loadreg(1, CurrentReg);
  5916. taicpu(hp2).loadreg(2, CurrentReg);
  5917. taicpu(hp2).ops := 3;
  5918. end;
  5919. RemoveInstruction(hp3);
  5920. Result := True;
  5921. Exit;
  5922. end;
  5923. end
  5924. else
  5925. begin
  5926. { See if the next references are 16 less rather than 16 greater }
  5927. Dec(SourceRef.offset, 32); { -16 the other way }
  5928. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  5929. begin
  5930. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5931. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  5932. if GetNextInstruction(hp2, hp3) and
  5933. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  5934. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  5935. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  5936. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  5937. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  5938. begin
  5939. { Update the register tracking to the new size }
  5940. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  5941. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  5942. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  5943. if not(
  5944. ((SourceRef.offset mod 32) = 0) and
  5945. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  5946. ) then
  5947. taicpu(hp2).opcode := A_VMOVDQU;
  5948. taicpu(hp2).opsize := S_YMM;
  5949. taicpu(hp2).oper[1]^.reg := CurrentReg;
  5950. if not (
  5951. ((TargetRef.offset mod 32) = 0) and
  5952. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  5953. ) then
  5954. taicpu(hp3).opcode := A_VMOVDQU;
  5955. taicpu(hp3).opsize := S_YMM;
  5956. taicpu(hp3).oper[0]^.reg := CurrentReg;
  5957. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  5958. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  5959. if (pi_uses_ymm in current_procinfo.flags) then
  5960. RemoveInstruction(hp1)
  5961. else
  5962. begin
  5963. taicpu(hp1).opcode := A_VPXOR;
  5964. taicpu(hp1).opsize := S_YMM;
  5965. taicpu(hp1).loadreg(0, CurrentReg);
  5966. taicpu(hp1).loadreg(1, CurrentReg);
  5967. taicpu(hp1).loadreg(2, CurrentReg);
  5968. taicpu(hp1).ops := 3;
  5969. Asml.Remove(hp1);
  5970. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  5971. end;
  5972. RemoveCurrentP(p, hp2);
  5973. Result := True;
  5974. Exit;
  5975. end;
  5976. end;
  5977. end;
  5978. end;
  5979. end;
  5980. end;
  5981. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5982. var
  5983. hp2, hp3, first_assignment: tai;
  5984. IncCount, OperIdx: Integer;
  5985. OrigLabel: TAsmLabel;
  5986. begin
  5987. Count := 0;
  5988. Result := False;
  5989. first_assignment := nil;
  5990. if (LoopCount >= 20) then
  5991. begin
  5992. { Guard against infinite loops }
  5993. Exit;
  5994. end;
  5995. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5996. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5997. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5998. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5999. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6000. Exit;
  6001. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6002. {
  6003. change
  6004. jmp .L1
  6005. ...
  6006. .L1:
  6007. mov ##, ## ( multiple movs possible )
  6008. jmp/ret
  6009. into
  6010. mov ##, ##
  6011. jmp/ret
  6012. }
  6013. if not Assigned(hp1) then
  6014. begin
  6015. hp1 := GetLabelWithSym(OrigLabel);
  6016. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6017. Exit;
  6018. end;
  6019. hp2 := hp1;
  6020. while Assigned(hp2) do
  6021. begin
  6022. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6023. SkipLabels(hp2,hp2);
  6024. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6025. Break;
  6026. case taicpu(hp2).opcode of
  6027. A_MOVSS:
  6028. begin
  6029. if taicpu(hp2).ops = 0 then
  6030. { Wrong MOVSS }
  6031. Break;
  6032. Inc(Count);
  6033. if Count >= 5 then
  6034. { Too many to be worthwhile }
  6035. Break;
  6036. GetNextInstruction(hp2, hp2);
  6037. Continue;
  6038. end;
  6039. A_MOV,
  6040. A_MOVD,
  6041. A_MOVQ,
  6042. A_MOVSX,
  6043. {$ifdef x86_64}
  6044. A_MOVSXD,
  6045. {$endif x86_64}
  6046. A_MOVZX,
  6047. A_MOVAPS,
  6048. A_MOVUPS,
  6049. A_MOVSD,
  6050. A_MOVAPD,
  6051. A_MOVUPD,
  6052. A_MOVDQA,
  6053. A_MOVDQU,
  6054. A_VMOVSS,
  6055. A_VMOVAPS,
  6056. A_VMOVUPS,
  6057. A_VMOVSD,
  6058. A_VMOVAPD,
  6059. A_VMOVUPD,
  6060. A_VMOVDQA,
  6061. A_VMOVDQU:
  6062. begin
  6063. Inc(Count);
  6064. if Count >= 5 then
  6065. { Too many to be worthwhile }
  6066. Break;
  6067. GetNextInstruction(hp2, hp2);
  6068. Continue;
  6069. end;
  6070. A_JMP:
  6071. begin
  6072. { Guard against infinite loops }
  6073. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6074. Exit;
  6075. { Analyse this jump first in case it also duplicates assignments }
  6076. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6077. begin
  6078. { Something did change! }
  6079. Result := True;
  6080. Inc(Count, IncCount);
  6081. if Count >= 5 then
  6082. begin
  6083. { Too many to be worthwhile }
  6084. Exit;
  6085. end;
  6086. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6087. Break;
  6088. end;
  6089. Result := True;
  6090. Break;
  6091. end;
  6092. A_RET:
  6093. begin
  6094. Result := True;
  6095. Break;
  6096. end;
  6097. else
  6098. Break;
  6099. end;
  6100. end;
  6101. if Result then
  6102. begin
  6103. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6104. if Count = 0 then
  6105. begin
  6106. Result := False;
  6107. Exit;
  6108. end;
  6109. hp3 := p;
  6110. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6111. while True do
  6112. begin
  6113. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6114. SkipLabels(hp1,hp1);
  6115. if (hp1.typ <> ait_instruction) then
  6116. InternalError(2021040720);
  6117. case taicpu(hp1).opcode of
  6118. A_JMP:
  6119. begin
  6120. { Change the original jump to the new destination }
  6121. OrigLabel.decrefs;
  6122. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6123. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6124. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6125. if not Assigned(first_assignment) then
  6126. InternalError(2021040810)
  6127. else
  6128. p := first_assignment;
  6129. Exit;
  6130. end;
  6131. A_RET:
  6132. begin
  6133. { Now change the jump into a RET instruction }
  6134. ConvertJumpToRET(p, hp1);
  6135. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6136. if not Assigned(first_assignment) then
  6137. InternalError(2021040811)
  6138. else
  6139. p := first_assignment;
  6140. Exit;
  6141. end;
  6142. else
  6143. begin
  6144. { Duplicate the MOV instruction }
  6145. hp3:=tai(hp1.getcopy);
  6146. if first_assignment = nil then
  6147. first_assignment := hp3;
  6148. asml.InsertBefore(hp3, p);
  6149. { Make sure the compiler knows about any final registers written here }
  6150. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6151. with taicpu(hp3).oper[OperIdx]^ do
  6152. begin
  6153. case typ of
  6154. top_ref:
  6155. begin
  6156. if (ref^.base <> NR_NO) and
  6157. (getsupreg(ref^.base) <> RS_ESP) and
  6158. (getsupreg(ref^.base) <> RS_EBP)
  6159. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6160. then
  6161. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6162. if (ref^.index <> NR_NO) and
  6163. (getsupreg(ref^.index) <> RS_ESP) and
  6164. (getsupreg(ref^.index) <> RS_EBP)
  6165. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6166. (ref^.index <> ref^.base) then
  6167. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6168. end;
  6169. top_reg:
  6170. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6171. else
  6172. ;
  6173. end;
  6174. end;
  6175. end;
  6176. end;
  6177. if not GetNextInstruction(hp1, hp1) then
  6178. { Should have dropped out earlier }
  6179. InternalError(2021040710);
  6180. end;
  6181. end;
  6182. end;
  6183. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6184. var
  6185. hp2: tai;
  6186. X: Integer;
  6187. const
  6188. WriteOp: array[0..3] of set of TInsChange = (
  6189. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6190. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6191. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6192. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6193. RegWriteFlags: array[0..7] of set of TInsChange = (
  6194. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6195. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6196. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6197. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6198. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6199. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6200. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6201. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6202. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6203. begin
  6204. { If we have something like:
  6205. cmp ###,%reg1
  6206. mov 0,%reg2
  6207. And no modified registers are shared, move the instruction to before
  6208. the comparison as this means it can be optimised without worrying
  6209. about the FLAGS register. (CMP/MOV is generated by
  6210. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6211. As long as the second instruction doesn't use the flags or one of the
  6212. registers used by CMP or TEST (also check any references that use the
  6213. registers), then it can be moved prior to the comparison.
  6214. }
  6215. Result := False;
  6216. if (hp1.typ <> ait_instruction) or
  6217. taicpu(hp1).is_jmp or
  6218. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6219. Exit;
  6220. { NOP is a pipeline fence, likely marking the beginning of the function
  6221. epilogue, so drop out. Similarly, drop out if POP or RET are
  6222. encountered }
  6223. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6224. Exit;
  6225. if (taicpu(hp1).opcode = A_MOVSS) and
  6226. (taicpu(hp1).ops = 0) then
  6227. { Wrong MOVSS }
  6228. Exit;
  6229. { Check for writes to specific registers first }
  6230. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6231. for X := 0 to 7 do
  6232. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6233. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6234. Exit;
  6235. for X := 0 to taicpu(hp1).ops - 1 do
  6236. begin
  6237. { Check to see if this operand writes to something }
  6238. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6239. { And matches something in the CMP/TEST instruction }
  6240. (
  6241. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6242. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6243. (
  6244. { If it's a register, make sure the register written to doesn't
  6245. appear in the cmp instruction as part of a reference }
  6246. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6247. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6248. )
  6249. ) then
  6250. Exit;
  6251. end;
  6252. { The instruction can be safely moved }
  6253. asml.Remove(hp1);
  6254. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6255. if not GetLastInstruction(p, hp2) then
  6256. asml.InsertBefore(hp1, p)
  6257. else
  6258. asml.InsertAfter(hp1, hp2);
  6259. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6260. for X := 0 to taicpu(hp1).ops - 1 do
  6261. case taicpu(hp1).oper[X]^.typ of
  6262. top_reg:
  6263. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6264. top_ref:
  6265. begin
  6266. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6267. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6268. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6269. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6270. end;
  6271. else
  6272. ;
  6273. end;
  6274. if taicpu(hp1).opcode = A_LEA then
  6275. { The flags will be overwritten by the CMP/TEST instruction }
  6276. ConvertLEA(taicpu(hp1));
  6277. Result := True;
  6278. end;
  6279. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6280. function IsXCHGAcceptable: Boolean; inline;
  6281. begin
  6282. { Always accept if optimising for size }
  6283. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6284. (
  6285. {$ifdef x86_64}
  6286. { XCHG takes 3 cycles on AMD Athlon64 }
  6287. (current_settings.optimizecputype >= cpu_core_i)
  6288. {$else x86_64}
  6289. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6290. than 3, so it becomes a saving compared to three MOVs with two of
  6291. them able to execute simultaneously. [Kit] }
  6292. (current_settings.optimizecputype >= cpu_PentiumM)
  6293. {$endif x86_64}
  6294. );
  6295. end;
  6296. var
  6297. NewRef: TReference;
  6298. hp1, hp2, hp3, hp4: Tai;
  6299. {$ifndef x86_64}
  6300. OperIdx: Integer;
  6301. {$endif x86_64}
  6302. NewInstr : Taicpu;
  6303. NewAligh : Tai_align;
  6304. DestLabel: TAsmLabel;
  6305. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6306. var
  6307. NextInstr: tai;
  6308. begin
  6309. Result := False;
  6310. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6311. if not GetNextInstruction(InputInstr, NextInstr) or
  6312. (
  6313. { The FLAGS register isn't always tracked properly, so do not
  6314. perform this optimisation if a conditional statement follows }
  6315. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6316. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6317. ) then
  6318. begin
  6319. reference_reset(NewRef, 1, []);
  6320. NewRef.base := taicpu(p).oper[0]^.reg;
  6321. NewRef.scalefactor := 1;
  6322. if taicpu(InputInstr).opcode = A_ADD then
  6323. begin
  6324. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6325. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6326. end
  6327. else
  6328. begin
  6329. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6330. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6331. end;
  6332. taicpu(p).opcode := A_LEA;
  6333. taicpu(p).loadref(0, NewRef);
  6334. RemoveInstruction(InputInstr);
  6335. Result := True;
  6336. end;
  6337. end;
  6338. begin
  6339. Result:=false;
  6340. { This optimisation adds an instruction, so only do it for speed }
  6341. if not (cs_opt_size in current_settings.optimizerswitches) and
  6342. MatchOpType(taicpu(p), top_const, top_reg) and
  6343. (taicpu(p).oper[0]^.val = 0) then
  6344. begin
  6345. { To avoid compiler warning }
  6346. DestLabel := nil;
  6347. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6348. InternalError(2021040750);
  6349. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6350. Exit;
  6351. case hp1.typ of
  6352. ait_label:
  6353. begin
  6354. { Change:
  6355. mov $0,%reg mov $0,%reg
  6356. @Lbl1: @Lbl1:
  6357. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6358. je @Lbl2 jne @Lbl2
  6359. To: To:
  6360. mov $0,%reg mov $0,%reg
  6361. jmp @Lbl2 jmp @Lbl3
  6362. (align) (align)
  6363. @Lbl1: @Lbl1:
  6364. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6365. je @Lbl2 je @Lbl2
  6366. @Lbl3: <-- Only if label exists
  6367. (Not if it's optimised for size)
  6368. }
  6369. if not GetNextInstruction(hp1, hp2) then
  6370. Exit;
  6371. if not (cs_opt_size in current_settings.optimizerswitches) and
  6372. (hp2.typ = ait_instruction) and
  6373. (
  6374. { Register sizes must exactly match }
  6375. (
  6376. (taicpu(hp2).opcode = A_CMP) and
  6377. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6378. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6379. ) or (
  6380. (taicpu(hp2).opcode = A_TEST) and
  6381. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6382. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6383. )
  6384. ) and GetNextInstruction(hp2, hp3) and
  6385. (hp3.typ = ait_instruction) and
  6386. (taicpu(hp3).opcode = A_JCC) and
  6387. (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
  6388. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6389. begin
  6390. { Check condition of jump }
  6391. { Always true? }
  6392. if condition_in(C_E, taicpu(hp3).condition) then
  6393. begin
  6394. { Copy label symbol and obtain matching label entry for the
  6395. conditional jump, as this will be our destination}
  6396. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6397. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6398. Result := True;
  6399. end
  6400. { Always false? }
  6401. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6402. begin
  6403. { This is only worth it if there's a jump to take }
  6404. case hp2.typ of
  6405. ait_instruction:
  6406. begin
  6407. if taicpu(hp2).opcode = A_JMP then
  6408. begin
  6409. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6410. { An unconditional jump follows the conditional jump which will always be false,
  6411. so use this jump's destination for the new jump }
  6412. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6413. Result := True;
  6414. end
  6415. else if taicpu(hp2).opcode = A_JCC then
  6416. begin
  6417. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6418. if condition_in(C_E, taicpu(hp2).condition) then
  6419. begin
  6420. { A second conditional jump follows the conditional jump which will always be false,
  6421. while the second jump is always True, so use this jump's destination for the new jump }
  6422. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6423. Result := True;
  6424. end;
  6425. { Don't risk it if the jump isn't always true (Result remains False) }
  6426. end;
  6427. end;
  6428. else
  6429. { If anything else don't optimise };
  6430. end;
  6431. end;
  6432. if Result then
  6433. begin
  6434. { Just so we have something to insert as a paremeter}
  6435. reference_reset(NewRef, 1, []);
  6436. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6437. { Now actually load the correct parameter }
  6438. NewInstr.loadsymbol(0, DestLabel, 0);
  6439. { Get instruction before original label (may not be p under -O3) }
  6440. if not GetLastInstruction(hp1, hp2) then
  6441. { Shouldn't fail here }
  6442. InternalError(2021040701);
  6443. DestLabel.increfs;
  6444. AsmL.InsertAfter(NewInstr, hp2);
  6445. { Add new alignment field }
  6446. (* AsmL.InsertAfter(
  6447. cai_align.create_max(
  6448. current_settings.alignment.jumpalign,
  6449. current_settings.alignment.jumpalignskipmax
  6450. ),
  6451. NewInstr
  6452. ); *)
  6453. end;
  6454. Exit;
  6455. end;
  6456. end;
  6457. else
  6458. ;
  6459. end;
  6460. end;
  6461. if not GetNextInstruction(p, hp1) then
  6462. Exit;
  6463. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6464. begin
  6465. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6466. further, but we can't just put this jump optimisation in pass 1
  6467. because it tends to perform worse when conditional jumps are
  6468. nearby (e.g. when converting CMOV instructions). [Kit] }
  6469. if OptPass2JMP(hp1) then
  6470. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6471. Result := OptPass1MOV(p)
  6472. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6473. returned True and the instruction is still a MOV, thus checking
  6474. the optimisations below }
  6475. { If OptPass2JMP returned False, no optimisations were done to
  6476. the jump and there are no further optimisations that can be done
  6477. to the MOV instruction on this pass }
  6478. end
  6479. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6480. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6481. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6482. (taicpu(hp1).oper[1]^.typ = top_reg) and
  6483. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6484. begin
  6485. { Change:
  6486. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6487. addl/q $x,%reg2 subl/q $x,%reg2
  6488. To:
  6489. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6490. }
  6491. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6492. { be lazy, checking separately for sub would be slightly better }
  6493. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6494. begin
  6495. TransferUsedRegs(TmpUsedRegs);
  6496. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6497. if TryMovArith2Lea(hp1) then
  6498. begin
  6499. Result := True;
  6500. Exit;
  6501. end
  6502. end
  6503. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  6504. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  6505. { Same as above, but also adds or subtracts to %reg2 in between.
  6506. It's still valid as long as the flags aren't in use }
  6507. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6508. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6509. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6510. { be lazy, checking separately for sub would be slightly better }
  6511. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  6512. begin
  6513. TransferUsedRegs(TmpUsedRegs);
  6514. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6515. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6516. if TryMovArith2Lea(hp2) then
  6517. begin
  6518. Result := True;
  6519. Exit;
  6520. end;
  6521. end;
  6522. end
  6523. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6524. {$ifdef x86_64}
  6525. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6526. {$else x86_64}
  6527. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6528. {$endif x86_64}
  6529. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6530. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6531. { mov reg1, reg2 mov reg1, reg2
  6532. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6533. begin
  6534. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6535. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6536. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6537. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6538. TransferUsedRegs(TmpUsedRegs);
  6539. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6540. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6541. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6542. then
  6543. begin
  6544. RemoveCurrentP(p, hp1);
  6545. Result:=true;
  6546. end;
  6547. exit;
  6548. end
  6549. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6550. IsXCHGAcceptable and
  6551. { XCHG doesn't support 8-byte registers }
  6552. (taicpu(p).opsize <> S_B) and
  6553. MatchInstruction(hp1, A_MOV, []) and
  6554. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6555. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  6556. GetNextInstruction(hp1, hp2) and
  6557. MatchInstruction(hp2, A_MOV, []) and
  6558. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  6559. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6560. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6561. begin
  6562. { mov %reg1,%reg2
  6563. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6564. mov %reg2,%reg3
  6565. (%reg2 not used afterwards)
  6566. Note that xchg takes 3 cycles to execute, and generally mov's take
  6567. only one cycle apiece, but the first two mov's can be executed in
  6568. parallel, only taking 2 cycles overall. Older processors should
  6569. therefore only optimise for size. [Kit]
  6570. }
  6571. TransferUsedRegs(TmpUsedRegs);
  6572. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6573. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6574. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6575. begin
  6576. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6577. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6578. taicpu(hp1).opcode := A_XCHG;
  6579. RemoveCurrentP(p, hp1);
  6580. RemoveInstruction(hp2);
  6581. Result := True;
  6582. Exit;
  6583. end;
  6584. end
  6585. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6586. MatchInstruction(hp1, A_SAR, []) then
  6587. begin
  6588. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6589. begin
  6590. { the use of %edx also covers the opsize being S_L }
  6591. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  6592. begin
  6593. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  6594. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  6595. (taicpu(p).oper[1]^.reg = NR_EDX) then
  6596. begin
  6597. { Change:
  6598. movl %eax,%edx
  6599. sarl $31,%edx
  6600. To:
  6601. cltd
  6602. }
  6603. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  6604. RemoveInstruction(hp1);
  6605. taicpu(p).opcode := A_CDQ;
  6606. taicpu(p).opsize := S_NO;
  6607. taicpu(p).clearop(1);
  6608. taicpu(p).clearop(0);
  6609. taicpu(p).ops:=0;
  6610. Result := True;
  6611. end
  6612. else if (cs_opt_size in current_settings.optimizerswitches) and
  6613. (taicpu(p).oper[0]^.reg = NR_EDX) and
  6614. (taicpu(p).oper[1]^.reg = NR_EAX) then
  6615. begin
  6616. { Change:
  6617. movl %edx,%eax
  6618. sarl $31,%edx
  6619. To:
  6620. movl %edx,%eax
  6621. cltd
  6622. Note that this creates a dependency between the two instructions,
  6623. so only perform if optimising for size.
  6624. }
  6625. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  6626. taicpu(hp1).opcode := A_CDQ;
  6627. taicpu(hp1).opsize := S_NO;
  6628. taicpu(hp1).clearop(1);
  6629. taicpu(hp1).clearop(0);
  6630. taicpu(hp1).ops:=0;
  6631. end;
  6632. {$ifndef x86_64}
  6633. end
  6634. { Don't bother if CMOV is supported, because a more optimal
  6635. sequence would have been generated for the Abs() intrinsic }
  6636. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  6637. { the use of %eax also covers the opsize being S_L }
  6638. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  6639. (taicpu(p).oper[0]^.reg = NR_EAX) and
  6640. (taicpu(p).oper[1]^.reg = NR_EDX) and
  6641. GetNextInstruction(hp1, hp2) and
  6642. MatchInstruction(hp2, A_XOR, [S_L]) and
  6643. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  6644. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  6645. GetNextInstruction(hp2, hp3) and
  6646. MatchInstruction(hp3, A_SUB, [S_L]) and
  6647. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  6648. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  6649. begin
  6650. { Change:
  6651. movl %eax,%edx
  6652. sarl $31,%eax
  6653. xorl %eax,%edx
  6654. subl %eax,%edx
  6655. (Instruction that uses %edx)
  6656. (%eax deallocated)
  6657. (%edx deallocated)
  6658. To:
  6659. cltd
  6660. xorl %edx,%eax <-- Note the registers have swapped
  6661. subl %edx,%eax
  6662. (Instruction that uses %eax) <-- %eax rather than %edx
  6663. }
  6664. TransferUsedRegs(TmpUsedRegs);
  6665. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6666. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6667. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6668. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  6669. begin
  6670. if GetNextInstruction(hp3, hp4) and
  6671. not RegModifiedByInstruction(NR_EDX, hp4) and
  6672. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  6673. begin
  6674. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  6675. taicpu(p).opcode := A_CDQ;
  6676. taicpu(p).clearop(1);
  6677. taicpu(p).clearop(0);
  6678. taicpu(p).ops:=0;
  6679. RemoveInstruction(hp1);
  6680. taicpu(hp2).loadreg(0, NR_EDX);
  6681. taicpu(hp2).loadreg(1, NR_EAX);
  6682. taicpu(hp3).loadreg(0, NR_EDX);
  6683. taicpu(hp3).loadreg(1, NR_EAX);
  6684. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  6685. { Convert references in the following instruction (hp4) from %edx to %eax }
  6686. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  6687. with taicpu(hp4).oper[OperIdx]^ do
  6688. case typ of
  6689. top_reg:
  6690. if getsupreg(reg) = RS_EDX then
  6691. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6692. top_ref:
  6693. begin
  6694. if getsupreg(reg) = RS_EDX then
  6695. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6696. if getsupreg(reg) = RS_EDX then
  6697. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6698. end;
  6699. else
  6700. ;
  6701. end;
  6702. end;
  6703. end;
  6704. {$else x86_64}
  6705. end;
  6706. end
  6707. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  6708. { the use of %rdx also covers the opsize being S_Q }
  6709. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  6710. begin
  6711. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  6712. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  6713. (taicpu(p).oper[1]^.reg = NR_RDX) then
  6714. begin
  6715. { Change:
  6716. movq %rax,%rdx
  6717. sarq $63,%rdx
  6718. To:
  6719. cqto
  6720. }
  6721. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  6722. RemoveInstruction(hp1);
  6723. taicpu(p).opcode := A_CQO;
  6724. taicpu(p).opsize := S_NO;
  6725. taicpu(p).clearop(1);
  6726. taicpu(p).clearop(0);
  6727. taicpu(p).ops:=0;
  6728. Result := True;
  6729. end
  6730. else if (cs_opt_size in current_settings.optimizerswitches) and
  6731. (taicpu(p).oper[0]^.reg = NR_RDX) and
  6732. (taicpu(p).oper[1]^.reg = NR_RAX) then
  6733. begin
  6734. { Change:
  6735. movq %rdx,%rax
  6736. sarq $63,%rdx
  6737. To:
  6738. movq %rdx,%rax
  6739. cqto
  6740. Note that this creates a dependency between the two instructions,
  6741. so only perform if optimising for size.
  6742. }
  6743. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  6744. taicpu(hp1).opcode := A_CQO;
  6745. taicpu(hp1).opsize := S_NO;
  6746. taicpu(hp1).clearop(1);
  6747. taicpu(hp1).clearop(0);
  6748. taicpu(hp1).ops:=0;
  6749. {$endif x86_64}
  6750. end;
  6751. end;
  6752. end
  6753. else if MatchInstruction(hp1, A_MOV, []) and
  6754. (taicpu(hp1).oper[1]^.typ = top_reg) then
  6755. { Though "GetNextInstruction" could be factored out, along with
  6756. the instructions that depend on hp2, it is an expensive call that
  6757. should be delayed for as long as possible, hence we do cheaper
  6758. checks first that are likely to be False. [Kit] }
  6759. begin
  6760. if (
  6761. (
  6762. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  6763. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  6764. (
  6765. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6766. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  6767. )
  6768. ) or
  6769. (
  6770. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  6771. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  6772. (
  6773. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6774. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  6775. )
  6776. )
  6777. ) and
  6778. GetNextInstruction(hp1, hp2) and
  6779. MatchInstruction(hp2, A_SAR, []) and
  6780. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  6781. begin
  6782. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  6783. begin
  6784. { Change:
  6785. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  6786. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  6787. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  6788. To:
  6789. movl r/m,%eax <- Note the change in register
  6790. cltd
  6791. }
  6792. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  6793. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  6794. taicpu(p).loadreg(1, NR_EAX);
  6795. taicpu(hp1).opcode := A_CDQ;
  6796. taicpu(hp1).clearop(1);
  6797. taicpu(hp1).clearop(0);
  6798. taicpu(hp1).ops:=0;
  6799. RemoveInstruction(hp2);
  6800. (*
  6801. {$ifdef x86_64}
  6802. end
  6803. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  6804. { This code sequence does not get generated - however it might become useful
  6805. if and when 128-bit signed integer types make an appearance, so the code
  6806. is kept here for when it is eventually needed. [Kit] }
  6807. (
  6808. (
  6809. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  6810. (
  6811. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6812. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  6813. )
  6814. ) or
  6815. (
  6816. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  6817. (
  6818. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6819. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  6820. )
  6821. )
  6822. ) and
  6823. GetNextInstruction(hp1, hp2) and
  6824. MatchInstruction(hp2, A_SAR, [S_Q]) and
  6825. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  6826. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  6827. begin
  6828. { Change:
  6829. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  6830. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  6831. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  6832. To:
  6833. movq r/m,%rax <- Note the change in register
  6834. cqto
  6835. }
  6836. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  6837. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  6838. taicpu(p).loadreg(1, NR_RAX);
  6839. taicpu(hp1).opcode := A_CQO;
  6840. taicpu(hp1).clearop(1);
  6841. taicpu(hp1).clearop(0);
  6842. taicpu(hp1).ops:=0;
  6843. RemoveInstruction(hp2);
  6844. {$endif x86_64}
  6845. *)
  6846. end;
  6847. end;
  6848. {$ifdef x86_64}
  6849. end
  6850. else if (taicpu(p).opsize = S_L) and
  6851. (taicpu(p).oper[1]^.typ = top_reg) and
  6852. (
  6853. MatchInstruction(hp1, A_MOV,[]) and
  6854. (taicpu(hp1).opsize = S_L) and
  6855. (taicpu(hp1).oper[1]^.typ = top_reg)
  6856. ) and (
  6857. GetNextInstruction(hp1, hp2) and
  6858. (tai(hp2).typ=ait_instruction) and
  6859. (taicpu(hp2).opsize = S_Q) and
  6860. (
  6861. (
  6862. MatchInstruction(hp2, A_ADD,[]) and
  6863. (taicpu(hp2).opsize = S_Q) and
  6864. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6865. (
  6866. (
  6867. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6868. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6869. ) or (
  6870. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6871. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6872. )
  6873. )
  6874. ) or (
  6875. MatchInstruction(hp2, A_LEA,[]) and
  6876. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  6877. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  6878. (
  6879. (
  6880. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6881. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6882. ) or (
  6883. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6884. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  6885. )
  6886. ) and (
  6887. (
  6888. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6889. ) or (
  6890. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6891. )
  6892. )
  6893. )
  6894. )
  6895. ) and (
  6896. GetNextInstruction(hp2, hp3) and
  6897. MatchInstruction(hp3, A_SHR,[]) and
  6898. (taicpu(hp3).opsize = S_Q) and
  6899. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6900. (taicpu(hp3).oper[0]^.val = 1) and
  6901. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6902. ) then
  6903. begin
  6904. { Change movl x, reg1d movl x, reg1d
  6905. movl y, reg2d movl y, reg2d
  6906. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6907. shrq $1, reg1q shrq $1, reg1q
  6908. ( reg1d and reg2d can be switched around in the first two instructions )
  6909. To movl x, reg1d
  6910. addl y, reg1d
  6911. rcrl $1, reg1d
  6912. This corresponds to the common expression (x + y) shr 1, where
  6913. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6914. smaller code, but won't account for x + y causing an overflow). [Kit]
  6915. }
  6916. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6917. { Change first MOV command to have the same register as the final output }
  6918. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6919. else
  6920. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6921. { Change second MOV command to an ADD command. This is easier than
  6922. converting the existing command because it means we don't have to
  6923. touch 'y', which might be a complicated reference, and also the
  6924. fact that the third command might either be ADD or LEA. [Kit] }
  6925. taicpu(hp1).opcode := A_ADD;
  6926. { Delete old ADD/LEA instruction }
  6927. RemoveInstruction(hp2);
  6928. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6929. taicpu(hp3).opcode := A_RCR;
  6930. taicpu(hp3).changeopsize(S_L);
  6931. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6932. {$endif x86_64}
  6933. end;
  6934. end;
  6935. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6936. var
  6937. ThisReg: TRegister;
  6938. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6939. TargetSubReg: TSubRegister;
  6940. hp1, hp2: tai;
  6941. RegInUse, RegChanged, p_removed: Boolean;
  6942. { Store list of found instructions so we don't have to call
  6943. GetNextInstructionUsingReg multiple times }
  6944. InstrList: array of taicpu;
  6945. InstrMax, Index: Integer;
  6946. UpperLimit, TrySmallerLimit: TCgInt;
  6947. PreMessage: string;
  6948. { Data flow analysis }
  6949. TestValMin, TestValMax: TCgInt;
  6950. SmallerOverflow: Boolean;
  6951. begin
  6952. Result := False;
  6953. p_removed := False;
  6954. { This is anything but quick! }
  6955. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6956. Exit;
  6957. SetLength(InstrList, 0);
  6958. InstrMax := -1;
  6959. ThisReg := taicpu(p).oper[1]^.reg;
  6960. case taicpu(p).opsize of
  6961. S_BW, S_BL:
  6962. begin
  6963. {$if defined(i386) or defined(i8086)}
  6964. { If the target size is 8-bit, make sure we can actually encode it }
  6965. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6966. Exit;
  6967. {$endif i386 or i8086}
  6968. UpperLimit := $FF;
  6969. MinSize := S_B;
  6970. if taicpu(p).opsize = S_BW then
  6971. MaxSize := S_W
  6972. else
  6973. MaxSize := S_L;
  6974. end;
  6975. S_WL:
  6976. begin
  6977. UpperLimit := $FFFF;
  6978. MinSize := S_W;
  6979. MaxSize := S_L;
  6980. end
  6981. else
  6982. InternalError(2020112301);
  6983. end;
  6984. TestValMin := 0;
  6985. TestValMax := UpperLimit;
  6986. TrySmallerLimit := UpperLimit;
  6987. TrySmaller := S_NO;
  6988. SmallerOverflow := False;
  6989. RegChanged := False;
  6990. hp1 := p;
  6991. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6992. (hp1.typ = ait_instruction) and
  6993. (
  6994. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  6995. instruction that doesn't actually contain ThisReg }
  6996. (cs_opt_level3 in current_settings.optimizerswitches) or
  6997. RegInInstruction(ThisReg, hp1)
  6998. ) do
  6999. begin
  7000. case taicpu(hp1).opcode of
  7001. A_INC,A_DEC:
  7002. begin
  7003. { Has to be an exact match on the register }
  7004. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7005. Break;
  7006. if taicpu(hp1).opcode = A_INC then
  7007. begin
  7008. Inc(TestValMin);
  7009. Inc(TestValMax);
  7010. end
  7011. else
  7012. begin
  7013. Dec(TestValMin);
  7014. Dec(TestValMax);
  7015. end;
  7016. end;
  7017. A_CMP:
  7018. begin
  7019. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7020. { Has to be an exact match on the register }
  7021. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7022. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7023. { Make sure the comparison value is not smaller than the
  7024. smallest allowed signed value for the minimum size (e.g.
  7025. -128 for 8-bit) }
  7026. not (
  7027. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7028. { Is it in the negative range? }
  7029. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  7030. ) then
  7031. Break;
  7032. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  7033. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  7034. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  7035. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  7036. { Overflow }
  7037. Break;
  7038. { Check to see if the active register is used afterwards }
  7039. TransferUsedRegs(TmpUsedRegs);
  7040. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  7041. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7042. begin
  7043. case MinSize of
  7044. S_B:
  7045. TargetSubReg := R_SUBL;
  7046. S_W:
  7047. TargetSubReg := R_SUBW;
  7048. else
  7049. InternalError(2021051002);
  7050. end;
  7051. { Update the register to its new size }
  7052. setsubreg(ThisReg, TargetSubReg);
  7053. taicpu(hp1).oper[1]^.reg := ThisReg;
  7054. taicpu(hp1).opsize := MinSize;
  7055. { Convert the input MOVZX to a MOV }
  7056. if (taicpu(p).oper[0]^.typ = top_reg) and
  7057. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7058. begin
  7059. { Or remove it completely! }
  7060. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7061. RemoveCurrentP(p);
  7062. p_removed := True;
  7063. end
  7064. else
  7065. begin
  7066. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7067. taicpu(p).opcode := A_MOV;
  7068. taicpu(p).oper[1]^.reg := ThisReg;
  7069. taicpu(p).opsize := MinSize;
  7070. end;
  7071. if (InstrMax >= 0) then
  7072. begin
  7073. for Index := 0 to InstrMax do
  7074. begin
  7075. { If p_removed is true, then the original MOV/Z was removed
  7076. and removing the AND instruction may not be safe if it
  7077. appears first }
  7078. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7079. InternalError(2020112311);
  7080. if InstrList[Index].oper[0]^.typ = top_reg then
  7081. InstrList[Index].oper[0]^.reg := ThisReg;
  7082. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7083. InstrList[Index].opsize := MinSize;
  7084. end;
  7085. end;
  7086. Result := True;
  7087. Exit;
  7088. end;
  7089. end;
  7090. { OR and XOR are not included because they can too easily fool
  7091. the data flow analysis (they can cause non-linear behaviour) }
  7092. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  7093. begin
  7094. if
  7095. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7096. { Has to be an exact match on the register }
  7097. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  7098. (
  7099. (
  7100. (taicpu(hp1).oper[0]^.typ = top_const) and
  7101. (
  7102. (
  7103. (taicpu(hp1).opcode = A_SHL) and
  7104. (
  7105. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  7106. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  7107. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  7108. )
  7109. ) or (
  7110. (taicpu(hp1).opcode <> A_SHL) and
  7111. (
  7112. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7113. { Is it in the negative range? }
  7114. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  7115. )
  7116. )
  7117. )
  7118. ) or (
  7119. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  7120. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  7121. )
  7122. ) then
  7123. Break;
  7124. case taicpu(hp1).opcode of
  7125. A_ADD:
  7126. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7127. begin
  7128. TestValMin := TestValMin * 2;
  7129. TestValMax := TestValMax * 2;
  7130. end
  7131. else
  7132. begin
  7133. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  7134. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  7135. end;
  7136. A_SUB:
  7137. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7138. begin
  7139. TestValMin := 0;
  7140. TestValMax := 0;
  7141. end
  7142. else
  7143. begin
  7144. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  7145. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  7146. end;
  7147. A_AND:
  7148. if (taicpu(hp1).oper[0]^.typ = top_const) then
  7149. begin
  7150. { we might be able to go smaller if AND appears first }
  7151. if InstrMax = -1 then
  7152. case MinSize of
  7153. S_B:
  7154. ;
  7155. S_W:
  7156. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  7157. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  7158. begin
  7159. TrySmaller := S_B;
  7160. TrySmallerLimit := $FF;
  7161. end;
  7162. S_L:
  7163. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  7164. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  7165. begin
  7166. TrySmaller := S_B;
  7167. TrySmallerLimit := $FF;
  7168. end
  7169. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  7170. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  7171. begin
  7172. TrySmaller := S_W;
  7173. TrySmallerLimit := $FFFF;
  7174. end;
  7175. else
  7176. InternalError(2020112320);
  7177. end;
  7178. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  7179. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  7180. end;
  7181. A_SHL:
  7182. begin
  7183. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  7184. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  7185. end;
  7186. A_SHR:
  7187. begin
  7188. { we might be able to go smaller if SHR appears first }
  7189. if InstrMax = -1 then
  7190. case MinSize of
  7191. S_B:
  7192. ;
  7193. S_W:
  7194. if (taicpu(hp1).oper[0]^.val >= 8) then
  7195. begin
  7196. TrySmaller := S_B;
  7197. TrySmallerLimit := $FF;
  7198. end;
  7199. S_L:
  7200. if (taicpu(hp1).oper[0]^.val >= 24) then
  7201. begin
  7202. TrySmaller := S_B;
  7203. TrySmallerLimit := $FF;
  7204. end
  7205. else if (taicpu(hp1).oper[0]^.val >= 16) then
  7206. begin
  7207. TrySmaller := S_W;
  7208. TrySmallerLimit := $FFFF;
  7209. end;
  7210. else
  7211. InternalError(2020112321);
  7212. end;
  7213. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  7214. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  7215. end;
  7216. else
  7217. InternalError(2020112303);
  7218. end;
  7219. end;
  7220. (*
  7221. A_IMUL:
  7222. case taicpu(hp1).ops of
  7223. 2:
  7224. begin
  7225. if not MatchOpType(hp1, top_reg, top_reg) or
  7226. { Has to be an exact match on the register }
  7227. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  7228. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  7229. Break;
  7230. TestValMin := TestValMin * TestValMin;
  7231. TestValMax := TestValMax * TestValMax;
  7232. end;
  7233. 3:
  7234. begin
  7235. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  7236. { Has to be an exact match on the register }
  7237. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7238. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  7239. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7240. { Is it in the negative range? }
  7241. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  7242. Break;
  7243. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  7244. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  7245. end;
  7246. else
  7247. Break;
  7248. end;
  7249. A_IDIV:
  7250. case taicpu(hp1).ops of
  7251. 3:
  7252. begin
  7253. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  7254. { Has to be an exact match on the register }
  7255. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7256. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  7257. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7258. { Is it in the negative range? }
  7259. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  7260. Break;
  7261. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  7262. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  7263. end;
  7264. else
  7265. Break;
  7266. end;
  7267. *)
  7268. A_MOVZX:
  7269. begin
  7270. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  7271. Break;
  7272. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  7273. begin
  7274. { Because hp1 was obtained via GetNextInstructionUsingReg
  7275. and ThisReg doesn't appear in the first operand, it
  7276. must appear in the second operand and hence gets
  7277. overwritten }
  7278. if (InstrMax = -1) and
  7279. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7280. begin
  7281. { The two MOVZX instructions are adjacent, so remove the first one }
  7282. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  7283. RemoveCurrentP(p);
  7284. Result := True;
  7285. Exit;
  7286. end;
  7287. Break;
  7288. end;
  7289. { The objective here is to try to find a combination that
  7290. removes one of the MOV/Z instructions. }
  7291. case taicpu(hp1).opsize of
  7292. S_WL:
  7293. if (MinSize in [S_B, S_W]) then
  7294. begin
  7295. TargetSize := S_L;
  7296. TargetSubReg := R_SUBD;
  7297. end
  7298. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  7299. begin
  7300. TargetSize := TrySmaller;
  7301. if TrySmaller = S_B then
  7302. TargetSubReg := R_SUBL
  7303. else
  7304. TargetSubReg := R_SUBW;
  7305. end
  7306. else
  7307. Break;
  7308. S_BW:
  7309. if (MinSize in [S_B, S_W]) then
  7310. begin
  7311. TargetSize := S_W;
  7312. TargetSubReg := R_SUBW;
  7313. end
  7314. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  7315. begin
  7316. TargetSize := S_B;
  7317. TargetSubReg := R_SUBL;
  7318. end
  7319. else
  7320. Break;
  7321. S_BL:
  7322. if (MinSize in [S_B, S_W]) then
  7323. begin
  7324. TargetSize := S_L;
  7325. TargetSubReg := R_SUBD;
  7326. end
  7327. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  7328. begin
  7329. TargetSize := S_B;
  7330. TargetSubReg := R_SUBL;
  7331. end
  7332. else
  7333. Break;
  7334. else
  7335. InternalError(2020112302);
  7336. end;
  7337. { Update the register to its new size }
  7338. setsubreg(ThisReg, TargetSubReg);
  7339. if TargetSize = MinSize then
  7340. begin
  7341. { Convert the input MOVZX to a MOV }
  7342. if (taicpu(p).oper[0]^.typ = top_reg) and
  7343. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7344. begin
  7345. { Or remove it completely! }
  7346. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7347. RemoveCurrentP(p);
  7348. p_removed := True;
  7349. end
  7350. else
  7351. begin
  7352. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7353. taicpu(p).opcode := A_MOV;
  7354. taicpu(p).oper[1]^.reg := ThisReg;
  7355. taicpu(p).opsize := TargetSize;
  7356. end;
  7357. Result := True;
  7358. end
  7359. else if TargetSize <> MaxSize then
  7360. begin
  7361. case MaxSize of
  7362. S_L:
  7363. if TargetSize = S_W then
  7364. begin
  7365. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7366. taicpu(p).opsize := S_BW;
  7367. taicpu(p).oper[1]^.reg := ThisReg;
  7368. Result := True;
  7369. end
  7370. else
  7371. InternalError(2020112341);
  7372. S_W:
  7373. if TargetSize = S_L then
  7374. begin
  7375. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7376. taicpu(p).opsize := S_BL;
  7377. taicpu(p).oper[1]^.reg := ThisReg;
  7378. Result := True;
  7379. end
  7380. else
  7381. InternalError(2020112342);
  7382. else
  7383. ;
  7384. end;
  7385. end;
  7386. if (MaxSize = TargetSize) or
  7387. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7388. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7389. begin
  7390. { Convert the output MOVZX to a MOV }
  7391. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7392. begin
  7393. { Or remove it completely! }
  7394. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7395. { Be careful; if p = hp1 and p was also removed, p
  7396. will become a dangling pointer }
  7397. if p = hp1 then
  7398. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  7399. else
  7400. RemoveInstruction(hp1);
  7401. end
  7402. else
  7403. begin
  7404. taicpu(hp1).opcode := A_MOV;
  7405. taicpu(hp1).oper[0]^.reg := ThisReg;
  7406. taicpu(hp1).opsize := TargetSize;
  7407. { Check to see if the active register is used afterwards;
  7408. if not, we can change it and make a saving. }
  7409. RegInUse := False;
  7410. TransferUsedRegs(TmpUsedRegs);
  7411. { The target register may be marked as in use to cross
  7412. a jump to a distant label, so exclude it }
  7413. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7414. hp2 := p;
  7415. repeat
  7416. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7417. { Explicitly check for the excluded register (don't include the first
  7418. instruction as it may be reading from here }
  7419. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7420. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7421. begin
  7422. RegInUse := True;
  7423. Break;
  7424. end;
  7425. if not GetNextInstruction(hp2, hp2) then
  7426. InternalError(2020112340);
  7427. until (hp2 = hp1);
  7428. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7429. begin
  7430. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7431. ThisReg := taicpu(hp1).oper[1]^.reg;
  7432. RegChanged := True;
  7433. TransferUsedRegs(TmpUsedRegs);
  7434. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7435. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7436. if p = hp1 then
  7437. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  7438. else
  7439. RemoveInstruction(hp1);
  7440. { Instruction will become "mov %reg,%reg" }
  7441. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7442. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7443. begin
  7444. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7445. RemoveCurrentP(p);
  7446. p_removed := True;
  7447. end
  7448. else
  7449. taicpu(p).oper[1]^.reg := ThisReg;
  7450. Result := True;
  7451. end
  7452. else
  7453. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7454. end;
  7455. end
  7456. else
  7457. InternalError(2020112330);
  7458. { Now go through every instruction we found and change the
  7459. size. If TargetSize = MaxSize, then almost no changes are
  7460. needed and Result can remain False if it hasn't been set
  7461. yet.
  7462. If RegChanged is True, then the register requires changing
  7463. and so the point about TargetSize = MaxSize doesn't apply. }
  7464. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7465. begin
  7466. for Index := 0 to InstrMax do
  7467. begin
  7468. { If p_removed is true, then the original MOV/Z was removed
  7469. and removing the AND instruction may not be safe if it
  7470. appears first }
  7471. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7472. InternalError(2020112310);
  7473. if InstrList[Index].oper[0]^.typ = top_reg then
  7474. InstrList[Index].oper[0]^.reg := ThisReg;
  7475. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7476. InstrList[Index].opsize := TargetSize;
  7477. end;
  7478. Result := True;
  7479. end;
  7480. Exit;
  7481. end;
  7482. else
  7483. { This includes ADC, SBB, IDIV and SAR }
  7484. Break;
  7485. end;
  7486. if (TestValMin < 0) or (TestValMax < 0) or
  7487. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  7488. { Overflow }
  7489. Break
  7490. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  7491. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  7492. SmallerOverflow := True;
  7493. { Contains highest index (so instruction count - 1) }
  7494. Inc(InstrMax);
  7495. if InstrMax > High(InstrList) then
  7496. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7497. InstrList[InstrMax] := taicpu(hp1);
  7498. end;
  7499. end;
  7500. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  7501. var
  7502. hp1 : tai;
  7503. begin
  7504. Result:=false;
  7505. if (taicpu(p).ops >= 2) and
  7506. ((taicpu(p).oper[0]^.typ = top_const) or
  7507. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  7508. (taicpu(p).oper[1]^.typ = top_reg) and
  7509. ((taicpu(p).ops = 2) or
  7510. ((taicpu(p).oper[2]^.typ = top_reg) and
  7511. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  7512. GetLastInstruction(p,hp1) and
  7513. MatchInstruction(hp1,A_MOV,[]) and
  7514. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7515. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7516. begin
  7517. TransferUsedRegs(TmpUsedRegs);
  7518. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  7519. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  7520. { change
  7521. mov reg1,reg2
  7522. imul y,reg2 to imul y,reg1,reg2 }
  7523. begin
  7524. taicpu(p).ops := 3;
  7525. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  7526. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7527. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  7528. RemoveInstruction(hp1);
  7529. result:=true;
  7530. end;
  7531. end;
  7532. end;
  7533. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  7534. var
  7535. ThisLabel: TAsmLabel;
  7536. begin
  7537. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  7538. ThisLabel.decrefs;
  7539. taicpu(p).opcode := A_RET;
  7540. taicpu(p).is_jmp := false;
  7541. taicpu(p).ops := taicpu(ret_p).ops;
  7542. case taicpu(ret_p).ops of
  7543. 0:
  7544. taicpu(p).clearop(0);
  7545. 1:
  7546. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  7547. else
  7548. internalerror(2016041301);
  7549. end;
  7550. { If the original label is now dead, it might turn out that the label
  7551. immediately follows p. As a result, everything beyond it, which will
  7552. be just some final register configuration and a RET instruction, is
  7553. now dead code. [Kit] }
  7554. { NOTE: This is much faster than introducing a OptPass2RET routine and
  7555. running RemoveDeadCodeAfterJump for each RET instruction, because
  7556. this optimisation rarely happens and most RETs appear at the end of
  7557. routines where there is nothing that can be stripped. [Kit] }
  7558. if not ThisLabel.is_used then
  7559. RemoveDeadCodeAfterJump(p);
  7560. end;
  7561. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  7562. var
  7563. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  7564. Unconditional, PotentialModified: Boolean;
  7565. OperPtr: POper;
  7566. NewRef: TReference;
  7567. InstrList: array of taicpu;
  7568. InstrMax, Index: Integer;
  7569. const
  7570. {$ifdef DEBUG_AOPTCPU}
  7571. SNoFlags: shortstring = ' so the flags aren''t modified';
  7572. {$else DEBUG_AOPTCPU}
  7573. SNoFlags = '';
  7574. {$endif DEBUG_AOPTCPU}
  7575. begin
  7576. Result:=false;
  7577. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  7578. begin
  7579. if MatchInstruction(hp1, A_TEST, [S_B]) and
  7580. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7581. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7582. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7583. GetNextInstruction(hp1, hp2) and
  7584. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  7585. { Change from: To:
  7586. set(C) %reg j(~C) label
  7587. test %reg,%reg/cmp $0,%reg
  7588. je label
  7589. set(C) %reg j(C) label
  7590. test %reg,%reg/cmp $0,%reg
  7591. jne label
  7592. (Also do something similar with sete/setne instead of je/jne)
  7593. }
  7594. begin
  7595. { Before we do anything else, we need to check the instructions
  7596. in between SETcc and TEST to make sure they don't modify the
  7597. FLAGS register - if -O2 or under, there won't be any
  7598. instructions between SET and TEST }
  7599. TransferUsedRegs(TmpUsedRegs);
  7600. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7601. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7602. begin
  7603. next := p;
  7604. SetLength(InstrList, 0);
  7605. InstrMax := -1;
  7606. PotentialModified := False;
  7607. { Make a note of every instruction that modifies the FLAGS
  7608. register }
  7609. while GetNextInstruction(next, next) and (next <> hp1) do
  7610. begin
  7611. if next.typ <> ait_instruction then
  7612. { GetNextInstructionUsingReg should have returned False }
  7613. InternalError(2021051701);
  7614. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  7615. begin
  7616. case taicpu(next).opcode of
  7617. A_SETcc,
  7618. A_CMOVcc,
  7619. A_Jcc:
  7620. begin
  7621. if PotentialModified then
  7622. { Not safe because the flags were modified earlier }
  7623. Exit
  7624. else
  7625. { Condition is the same as the initial SETcc, so this is safe
  7626. (don't add to instruction list though) }
  7627. Continue;
  7628. end;
  7629. A_ADD:
  7630. begin
  7631. if (taicpu(next).opsize = S_B) or
  7632. { LEA doesn't support 8-bit operands }
  7633. (taicpu(next).oper[1]^.typ <> top_reg) or
  7634. { Must write to a register }
  7635. (taicpu(next).oper[0]^.typ = top_ref) then
  7636. { Require a constant or a register }
  7637. Exit;
  7638. PotentialModified := True;
  7639. end;
  7640. A_SUB:
  7641. begin
  7642. if (taicpu(next).opsize = S_B) or
  7643. { LEA doesn't support 8-bit operands }
  7644. (taicpu(next).oper[1]^.typ <> top_reg) or
  7645. { Must write to a register }
  7646. (taicpu(next).oper[0]^.typ <> top_const) or
  7647. (taicpu(next).oper[0]^.val = $80000000) then
  7648. { Can't subtract a register with LEA - also
  7649. check that the value isn't -2^31, as this
  7650. can't be negated }
  7651. Exit;
  7652. PotentialModified := True;
  7653. end;
  7654. A_SAL,
  7655. A_SHL:
  7656. begin
  7657. if (taicpu(next).opsize = S_B) or
  7658. { LEA doesn't support 8-bit operands }
  7659. (taicpu(next).oper[1]^.typ <> top_reg) or
  7660. { Must write to a register }
  7661. (taicpu(next).oper[0]^.typ <> top_const) or
  7662. (taicpu(next).oper[0]^.val < 0) or
  7663. (taicpu(next).oper[0]^.val > 3) then
  7664. Exit;
  7665. PotentialModified := True;
  7666. end;
  7667. A_IMUL:
  7668. begin
  7669. if (taicpu(next).ops <> 3) or
  7670. (taicpu(next).oper[1]^.typ <> top_reg) or
  7671. { Must write to a register }
  7672. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  7673. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  7674. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  7675. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  7676. Exit
  7677. else
  7678. PotentialModified := True;
  7679. end;
  7680. else
  7681. { Don't know how to change this, so abort }
  7682. Exit;
  7683. end;
  7684. { Contains highest index (so instruction count - 1) }
  7685. Inc(InstrMax);
  7686. if InstrMax > High(InstrList) then
  7687. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7688. InstrList[InstrMax] := taicpu(next);
  7689. end;
  7690. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  7691. end;
  7692. if not Assigned(next) or (next <> hp1) then
  7693. { It should be equal to hp1 }
  7694. InternalError(2021051702);
  7695. { Cycle through each instruction and check to see if we can
  7696. change them to versions that don't modify the flags }
  7697. if (InstrMax >= 0) then
  7698. begin
  7699. for Index := 0 to InstrMax do
  7700. case InstrList[Index].opcode of
  7701. A_ADD:
  7702. begin
  7703. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  7704. InstrList[Index].opcode := A_LEA;
  7705. reference_reset(NewRef, 1, []);
  7706. NewRef.base := InstrList[Index].oper[1]^.reg;
  7707. if InstrList[Index].oper[0]^.typ = top_reg then
  7708. begin
  7709. NewRef.index := InstrList[Index].oper[0]^.reg;
  7710. NewRef.scalefactor := 1;
  7711. end
  7712. else
  7713. NewRef.offset := InstrList[Index].oper[0]^.val;
  7714. InstrList[Index].loadref(0, NewRef);
  7715. end;
  7716. A_SUB:
  7717. begin
  7718. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  7719. InstrList[Index].opcode := A_LEA;
  7720. reference_reset(NewRef, 1, []);
  7721. NewRef.base := InstrList[Index].oper[1]^.reg;
  7722. NewRef.offset := -InstrList[Index].oper[0]^.val;
  7723. InstrList[Index].loadref(0, NewRef);
  7724. end;
  7725. A_SHL,
  7726. A_SAL:
  7727. begin
  7728. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  7729. InstrList[Index].opcode := A_LEA;
  7730. reference_reset(NewRef, 1, []);
  7731. NewRef.index := InstrList[Index].oper[1]^.reg;
  7732. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  7733. InstrList[Index].loadref(0, NewRef);
  7734. end;
  7735. A_IMUL:
  7736. begin
  7737. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  7738. InstrList[Index].opcode := A_LEA;
  7739. reference_reset(NewRef, 1, []);
  7740. NewRef.index := InstrList[Index].oper[1]^.reg;
  7741. case InstrList[Index].oper[0]^.val of
  7742. 2, 4, 8:
  7743. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  7744. else {3, 5 and 9}
  7745. begin
  7746. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  7747. NewRef.base := InstrList[Index].oper[1]^.reg;
  7748. end;
  7749. end;
  7750. InstrList[Index].loadref(0, NewRef);
  7751. end;
  7752. else
  7753. InternalError(2021051710);
  7754. end;
  7755. end;
  7756. { Mark the FLAGS register as used across this whole block }
  7757. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  7758. end;
  7759. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7760. JumpC := taicpu(hp2).condition;
  7761. Unconditional := False;
  7762. if conditions_equal(JumpC, C_E) then
  7763. SetC := inverse_cond(taicpu(p).condition)
  7764. else if conditions_equal(JumpC, C_NE) then
  7765. SetC := taicpu(p).condition
  7766. else
  7767. { We've got something weird here (and inefficent) }
  7768. begin
  7769. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  7770. SetC := C_NONE;
  7771. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  7772. if condition_in(C_AE, JumpC) then
  7773. Unconditional := True
  7774. else
  7775. { Not sure what to do with this jump - drop out }
  7776. Exit;
  7777. end;
  7778. RemoveInstruction(hp1);
  7779. if Unconditional then
  7780. MakeUnconditional(taicpu(hp2))
  7781. else
  7782. begin
  7783. if SetC = C_NONE then
  7784. InternalError(2018061402);
  7785. taicpu(hp2).SetCondition(SetC);
  7786. end;
  7787. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  7788. TmpUsedRegs }
  7789. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  7790. begin
  7791. RemoveCurrentp(p, hp2);
  7792. if taicpu(hp2).opcode = A_SETcc then
  7793. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  7794. else
  7795. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  7796. end
  7797. else
  7798. if taicpu(hp2).opcode = A_SETcc then
  7799. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  7800. else
  7801. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  7802. Result := True;
  7803. end
  7804. else if
  7805. { Make sure the instructions are adjacent }
  7806. (
  7807. not (cs_opt_level3 in current_settings.optimizerswitches) or
  7808. GetNextInstruction(p, hp1)
  7809. ) and
  7810. MatchInstruction(hp1, A_MOV, [S_B]) and
  7811. { Writing to memory is allowed }
  7812. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  7813. begin
  7814. {
  7815. Watch out for sequences such as:
  7816. set(c)b %regb
  7817. movb %regb,(ref)
  7818. movb $0,1(ref)
  7819. movb $0,2(ref)
  7820. movb $0,3(ref)
  7821. Much more efficient to turn it into:
  7822. movl $0,%regl
  7823. set(c)b %regb
  7824. movl %regl,(ref)
  7825. Or:
  7826. set(c)b %regb
  7827. movzbl %regb,%regl
  7828. movl %regl,(ref)
  7829. }
  7830. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  7831. GetNextInstruction(hp1, hp2) and
  7832. MatchInstruction(hp2, A_MOV, [S_B]) and
  7833. (taicpu(hp2).oper[1]^.typ = top_ref) and
  7834. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  7835. begin
  7836. { Don't do anything else except set Result to True }
  7837. end
  7838. else
  7839. begin
  7840. if taicpu(p).oper[0]^.typ = top_reg then
  7841. begin
  7842. TransferUsedRegs(TmpUsedRegs);
  7843. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7844. end;
  7845. { If it's not a register, it's a memory address }
  7846. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  7847. begin
  7848. { Even if the register is still in use, we can minimise the
  7849. pipeline stall by changing the MOV into another SETcc. }
  7850. taicpu(hp1).opcode := A_SETcc;
  7851. taicpu(hp1).condition := taicpu(p).condition;
  7852. if taicpu(hp1).oper[1]^.typ = top_ref then
  7853. begin
  7854. { Swapping the operand pointers like this is probably a
  7855. bit naughty, but it is far faster than using loadoper
  7856. to transfer the reference from oper[1] to oper[0] if
  7857. you take into account the extra procedure calls and
  7858. the memory allocation and deallocation required }
  7859. OperPtr := taicpu(hp1).oper[1];
  7860. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  7861. taicpu(hp1).oper[0] := OperPtr;
  7862. end
  7863. else
  7864. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  7865. taicpu(hp1).clearop(1);
  7866. taicpu(hp1).ops := 1;
  7867. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  7868. end
  7869. else
  7870. begin
  7871. if taicpu(hp1).oper[1]^.typ = top_reg then
  7872. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  7873. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7874. RemoveInstruction(hp1);
  7875. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  7876. end
  7877. end;
  7878. Result := True;
  7879. end;
  7880. end;
  7881. end;
  7882. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  7883. var
  7884. hp1: tai;
  7885. Count: Integer;
  7886. OrigLabel: TAsmLabel;
  7887. begin
  7888. result := False;
  7889. { Sometimes, the optimisations below can permit this }
  7890. RemoveDeadCodeAfterJump(p);
  7891. 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
  7892. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7893. begin
  7894. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7895. { Also a side-effect of optimisations }
  7896. if CollapseZeroDistJump(p, OrigLabel) then
  7897. begin
  7898. Result := True;
  7899. Exit;
  7900. end;
  7901. hp1 := GetLabelWithSym(OrigLabel);
  7902. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7903. begin
  7904. case taicpu(hp1).opcode of
  7905. A_RET:
  7906. {
  7907. change
  7908. jmp .L1
  7909. ...
  7910. .L1:
  7911. ret
  7912. into
  7913. ret
  7914. }
  7915. begin
  7916. ConvertJumpToRET(p, hp1);
  7917. result:=true;
  7918. end;
  7919. { Check any kind of direct assignment instruction }
  7920. A_MOV,
  7921. A_MOVD,
  7922. A_MOVQ,
  7923. A_MOVSX,
  7924. {$ifdef x86_64}
  7925. A_MOVSXD,
  7926. {$endif x86_64}
  7927. A_MOVZX,
  7928. A_MOVAPS,
  7929. A_MOVUPS,
  7930. A_MOVSD,
  7931. A_MOVAPD,
  7932. A_MOVUPD,
  7933. A_MOVDQA,
  7934. A_MOVDQU,
  7935. A_VMOVSS,
  7936. A_VMOVAPS,
  7937. A_VMOVUPS,
  7938. A_VMOVSD,
  7939. A_VMOVAPD,
  7940. A_VMOVUPD,
  7941. A_VMOVDQA,
  7942. A_VMOVDQU:
  7943. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7944. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7945. begin
  7946. Result := True;
  7947. Exit;
  7948. end;
  7949. else
  7950. ;
  7951. end;
  7952. end;
  7953. end;
  7954. end;
  7955. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7956. begin
  7957. CanBeCMOV:=assigned(p) and
  7958. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7959. { we can't use cmov ref,reg because
  7960. ref could be nil and cmov still throws an exception
  7961. if ref=nil but the mov isn't done (FK)
  7962. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7963. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7964. }
  7965. (taicpu(p).oper[1]^.typ = top_reg) and
  7966. (
  7967. (taicpu(p).oper[0]^.typ = top_reg) or
  7968. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7969. it is not expected that this can cause a seg. violation }
  7970. (
  7971. (taicpu(p).oper[0]^.typ = top_ref) and
  7972. IsRefSafe(taicpu(p).oper[0]^.ref)
  7973. )
  7974. );
  7975. end;
  7976. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7977. var
  7978. hp1,hp2: tai;
  7979. {$ifndef i8086}
  7980. hp3,hp4,hpmov2, hp5: tai;
  7981. l : Longint;
  7982. condition : TAsmCond;
  7983. {$endif i8086}
  7984. carryadd_opcode : TAsmOp;
  7985. symbol: TAsmSymbol;
  7986. reg: tsuperregister;
  7987. increg, tmpreg: TRegister;
  7988. begin
  7989. result:=false;
  7990. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7991. begin
  7992. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7993. if (
  7994. (
  7995. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  7996. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  7997. (Taicpu(hp1).oper[0]^.val=1)
  7998. ) or
  7999. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8000. ) and
  8001. GetNextInstruction(hp1,hp2) and
  8002. SkipAligns(hp2, hp2) and
  8003. (hp2.typ = ait_label) and
  8004. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8005. { jb @@1 cmc
  8006. inc/dec operand --> adc/sbb operand,0
  8007. @@1:
  8008. ... and ...
  8009. jnb @@1
  8010. inc/dec operand --> adc/sbb operand,0
  8011. @@1: }
  8012. begin
  8013. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8014. begin
  8015. case taicpu(hp1).opcode of
  8016. A_INC,
  8017. A_ADD:
  8018. carryadd_opcode:=A_ADC;
  8019. A_DEC,
  8020. A_SUB:
  8021. carryadd_opcode:=A_SBB;
  8022. else
  8023. InternalError(2021011001);
  8024. end;
  8025. Taicpu(p).clearop(0);
  8026. Taicpu(p).ops:=0;
  8027. Taicpu(p).is_jmp:=false;
  8028. Taicpu(p).opcode:=A_CMC;
  8029. Taicpu(p).condition:=C_NONE;
  8030. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8031. Taicpu(hp1).ops:=2;
  8032. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8033. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8034. else
  8035. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8036. Taicpu(hp1).loadconst(0,0);
  8037. Taicpu(hp1).opcode:=carryadd_opcode;
  8038. result:=true;
  8039. exit;
  8040. end
  8041. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8042. begin
  8043. case taicpu(hp1).opcode of
  8044. A_INC,
  8045. A_ADD:
  8046. carryadd_opcode:=A_ADC;
  8047. A_DEC,
  8048. A_SUB:
  8049. carryadd_opcode:=A_SBB;
  8050. else
  8051. InternalError(2021011002);
  8052. end;
  8053. Taicpu(hp1).ops:=2;
  8054. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8055. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8056. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8057. else
  8058. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8059. Taicpu(hp1).loadconst(0,0);
  8060. Taicpu(hp1).opcode:=carryadd_opcode;
  8061. RemoveCurrentP(p, hp1);
  8062. result:=true;
  8063. exit;
  8064. end
  8065. {
  8066. jcc @@1 setcc tmpreg
  8067. inc/dec/add/sub operand -> (movzx tmpreg)
  8068. @@1: add/sub tmpreg,operand
  8069. While this increases code size slightly, it makes the code much faster if the
  8070. jump is unpredictable
  8071. }
  8072. else if not(cs_opt_size in current_settings.optimizerswitches) then
  8073. begin
  8074. { search for an available register which is volatile }
  8075. for reg in tcpuregisterset do
  8076. begin
  8077. if
  8078. {$if defined(i386) or defined(i8086)}
  8079. { Only use registers whose lowest 8-bits can Be accessed }
  8080. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  8081. {$endif i386 or i8086}
  8082. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  8083. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  8084. { We don't need to check if tmpreg is in hp1 or not, because
  8085. it will be marked as in use at p (if not, this is
  8086. indictive of a compiler bug). }
  8087. then
  8088. begin
  8089. TAsmLabel(symbol).decrefs;
  8090. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  8091. Taicpu(p).clearop(0);
  8092. Taicpu(p).ops:=1;
  8093. Taicpu(p).is_jmp:=false;
  8094. Taicpu(p).opcode:=A_SETcc;
  8095. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  8096. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  8097. Taicpu(p).loadreg(0,increg);
  8098. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  8099. begin
  8100. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  8101. R_SUBW:
  8102. begin
  8103. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  8104. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  8105. end;
  8106. R_SUBD:
  8107. begin
  8108. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  8109. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8110. end;
  8111. {$ifdef x86_64}
  8112. R_SUBQ:
  8113. begin
  8114. { MOVZX doesn't have a 64-bit variant, because
  8115. the 32-bit version implicitly zeroes the
  8116. upper 32-bits of the destination register }
  8117. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  8118. newreg(R_INTREGISTER,reg,R_SUBD));
  8119. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  8120. end;
  8121. {$endif x86_64}
  8122. else
  8123. Internalerror(2020030601);
  8124. end;
  8125. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  8126. asml.InsertAfter(hp2,p);
  8127. end
  8128. else
  8129. tmpreg := increg;
  8130. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  8131. begin
  8132. Taicpu(hp1).ops:=2;
  8133. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  8134. end;
  8135. Taicpu(hp1).loadreg(0,tmpreg);
  8136. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  8137. Result := True;
  8138. { p is no longer a Jcc instruction, so exit }
  8139. Exit;
  8140. end;
  8141. end;
  8142. end;
  8143. end;
  8144. { Detect the following:
  8145. jmp<cond> @Lbl1
  8146. jmp @Lbl2
  8147. ...
  8148. @Lbl1:
  8149. ret
  8150. Change to:
  8151. jmp<inv_cond> @Lbl2
  8152. ret
  8153. }
  8154. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8155. begin
  8156. hp2:=getlabelwithsym(TAsmLabel(symbol));
  8157. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  8158. MatchInstruction(hp2,A_RET,[S_NO]) then
  8159. begin
  8160. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8161. { Change label address to that of the unconditional jump }
  8162. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  8163. TAsmLabel(symbol).DecRefs;
  8164. taicpu(hp1).opcode := A_RET;
  8165. taicpu(hp1).is_jmp := false;
  8166. taicpu(hp1).ops := taicpu(hp2).ops;
  8167. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  8168. case taicpu(hp2).ops of
  8169. 0:
  8170. taicpu(hp1).clearop(0);
  8171. 1:
  8172. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  8173. else
  8174. internalerror(2016041302);
  8175. end;
  8176. end;
  8177. {$ifndef i8086}
  8178. end
  8179. {
  8180. convert
  8181. j<c> .L1
  8182. mov 1,reg
  8183. jmp .L2
  8184. .L1
  8185. mov 0,reg
  8186. .L2
  8187. into
  8188. mov 0,reg
  8189. set<not(c)> reg
  8190. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8191. would destroy the flag contents
  8192. }
  8193. else if MatchInstruction(hp1,A_MOV,[]) and
  8194. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8195. {$ifdef i386}
  8196. (
  8197. { Under i386, ESI, EDI, EBP and ESP
  8198. don't have an 8-bit representation }
  8199. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8200. ) and
  8201. {$endif i386}
  8202. (taicpu(hp1).oper[0]^.val=1) and
  8203. GetNextInstruction(hp1,hp2) and
  8204. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8205. GetNextInstruction(hp2,hp3) and
  8206. { skip align }
  8207. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  8208. (hp3.typ=ait_label) and
  8209. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8210. (tai_label(hp3).labsym.getrefs=1) and
  8211. GetNextInstruction(hp3,hp4) and
  8212. MatchInstruction(hp4,A_MOV,[]) and
  8213. MatchOpType(taicpu(hp4),top_const,top_reg) and
  8214. (taicpu(hp4).oper[0]^.val=0) and
  8215. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8216. GetNextInstruction(hp4,hp5) and
  8217. (hp5.typ=ait_label) and
  8218. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  8219. (tai_label(hp5).labsym.getrefs=1) then
  8220. begin
  8221. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  8222. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  8223. { remove last label }
  8224. RemoveInstruction(hp5);
  8225. { remove second label }
  8226. RemoveInstruction(hp3);
  8227. { if align is present remove it }
  8228. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  8229. RemoveInstruction(hp3);
  8230. { remove jmp }
  8231. RemoveInstruction(hp2);
  8232. if taicpu(hp1).opsize=S_B then
  8233. RemoveInstruction(hp1)
  8234. else
  8235. taicpu(hp1).loadconst(0,0);
  8236. taicpu(hp4).opcode:=A_SETcc;
  8237. taicpu(hp4).opsize:=S_B;
  8238. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  8239. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  8240. taicpu(hp4).opercnt:=1;
  8241. taicpu(hp4).ops:=1;
  8242. taicpu(hp4).freeop(1);
  8243. RemoveCurrentP(p);
  8244. Result:=true;
  8245. exit;
  8246. end
  8247. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  8248. begin
  8249. { check for
  8250. jCC xxx
  8251. <several movs>
  8252. xxx:
  8253. }
  8254. l:=0;
  8255. while assigned(hp1) and
  8256. CanBeCMOV(hp1) and
  8257. { stop on labels }
  8258. not(hp1.typ=ait_label) do
  8259. begin
  8260. inc(l);
  8261. GetNextInstruction(hp1,hp1);
  8262. end;
  8263. if assigned(hp1) then
  8264. begin
  8265. if FindLabel(tasmlabel(symbol),hp1) then
  8266. begin
  8267. if (l<=4) and (l>0) then
  8268. begin
  8269. condition:=inverse_cond(taicpu(p).condition);
  8270. UpdateUsedRegs(tai(p.next));
  8271. GetNextInstruction(p,hp1);
  8272. repeat
  8273. if not Assigned(hp1) then
  8274. InternalError(2018062900);
  8275. taicpu(hp1).opcode:=A_CMOVcc;
  8276. taicpu(hp1).condition:=condition;
  8277. UpdateUsedRegs(tai(hp1.next));
  8278. GetNextInstruction(hp1,hp1);
  8279. until not(CanBeCMOV(hp1));
  8280. { Remember what hp1 is in case there's multiple aligns to get rid of }
  8281. hp2 := hp1;
  8282. repeat
  8283. if not Assigned(hp2) then
  8284. InternalError(2018062910);
  8285. case hp2.typ of
  8286. ait_label:
  8287. { What we expected - break out of the loop (it won't be a dead label at the top of
  8288. a cluster because that was optimised at an earlier stage) }
  8289. Break;
  8290. ait_align:
  8291. { Go to the next entry until a label is found (may be multiple aligns before it) }
  8292. begin
  8293. hp2 := tai(hp2.Next);
  8294. Continue;
  8295. end;
  8296. else
  8297. begin
  8298. { Might be a comment or temporary allocation entry }
  8299. if not (hp2.typ in SkipInstr) then
  8300. InternalError(2018062911);
  8301. hp2 := tai(hp2.Next);
  8302. Continue;
  8303. end;
  8304. end;
  8305. until False;
  8306. { Now we can safely decrement the reference count }
  8307. tasmlabel(symbol).decrefs;
  8308. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  8309. { Remove the original jump }
  8310. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  8311. UpdateUsedRegs(tai(hp2.next));
  8312. GetNextInstruction(hp2, p); { Instruction after the label }
  8313. { Remove the label if this is its final reference }
  8314. if (tasmlabel(symbol).getrefs=0) then
  8315. StripLabelFast(hp1);
  8316. if Assigned(p) then
  8317. result:=true;
  8318. exit;
  8319. end;
  8320. end
  8321. else
  8322. begin
  8323. { check further for
  8324. jCC xxx
  8325. <several movs 1>
  8326. jmp yyy
  8327. xxx:
  8328. <several movs 2>
  8329. yyy:
  8330. }
  8331. { hp2 points to jmp yyy }
  8332. hp2:=hp1;
  8333. { skip hp1 to xxx (or an align right before it) }
  8334. GetNextInstruction(hp1, hp1);
  8335. if assigned(hp2) and
  8336. assigned(hp1) and
  8337. (l<=3) and
  8338. (hp2.typ=ait_instruction) and
  8339. (taicpu(hp2).is_jmp) and
  8340. (taicpu(hp2).condition=C_None) and
  8341. { real label and jump, no further references to the
  8342. label are allowed }
  8343. (tasmlabel(symbol).getrefs=1) and
  8344. FindLabel(tasmlabel(symbol),hp1) then
  8345. begin
  8346. l:=0;
  8347. { skip hp1 to <several moves 2> }
  8348. if (hp1.typ = ait_align) then
  8349. GetNextInstruction(hp1, hp1);
  8350. GetNextInstruction(hp1, hpmov2);
  8351. hp1 := hpmov2;
  8352. while assigned(hp1) and
  8353. CanBeCMOV(hp1) do
  8354. begin
  8355. inc(l);
  8356. GetNextInstruction(hp1, hp1);
  8357. end;
  8358. { hp1 points to yyy (or an align right before it) }
  8359. hp3 := hp1;
  8360. if assigned(hp1) and
  8361. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  8362. begin
  8363. condition:=inverse_cond(taicpu(p).condition);
  8364. UpdateUsedRegs(tai(p.next));
  8365. GetNextInstruction(p,hp1);
  8366. repeat
  8367. taicpu(hp1).opcode:=A_CMOVcc;
  8368. taicpu(hp1).condition:=condition;
  8369. UpdateUsedRegs(tai(hp1.next));
  8370. GetNextInstruction(hp1,hp1);
  8371. until not(assigned(hp1)) or
  8372. not(CanBeCMOV(hp1));
  8373. condition:=inverse_cond(condition);
  8374. if GetLastInstruction(hpmov2,hp1) then
  8375. UpdateUsedRegs(tai(hp1.next));
  8376. hp1 := hpmov2;
  8377. { hp1 is now at <several movs 2> }
  8378. while Assigned(hp1) and CanBeCMOV(hp1) do
  8379. begin
  8380. taicpu(hp1).opcode:=A_CMOVcc;
  8381. taicpu(hp1).condition:=condition;
  8382. UpdateUsedRegs(tai(hp1.next));
  8383. GetNextInstruction(hp1,hp1);
  8384. end;
  8385. hp1 := p;
  8386. { Get first instruction after label }
  8387. UpdateUsedRegs(tai(hp3.next));
  8388. GetNextInstruction(hp3, p);
  8389. if assigned(p) and (hp3.typ = ait_align) then
  8390. GetNextInstruction(p, p);
  8391. { Don't dereference yet, as doing so will cause
  8392. GetNextInstruction to skip the label and
  8393. optional align marker. [Kit] }
  8394. GetNextInstruction(hp2, hp4);
  8395. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  8396. { remove jCC }
  8397. RemoveInstruction(hp1);
  8398. { Now we can safely decrement it }
  8399. tasmlabel(symbol).decrefs;
  8400. { Remove label xxx (it will have a ref of zero due to the initial check }
  8401. StripLabelFast(hp4);
  8402. { remove jmp }
  8403. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  8404. RemoveInstruction(hp2);
  8405. { As before, now we can safely decrement it }
  8406. tasmlabel(symbol).decrefs;
  8407. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  8408. if tasmlabel(symbol).getrefs = 0 then
  8409. StripLabelFast(hp3);
  8410. if Assigned(p) then
  8411. result:=true;
  8412. exit;
  8413. end;
  8414. end;
  8415. end;
  8416. end;
  8417. {$endif i8086}
  8418. end;
  8419. end;
  8420. end;
  8421. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  8422. var
  8423. hp1,hp2: tai;
  8424. reg_and_hp1_is_instr: Boolean;
  8425. begin
  8426. result:=false;
  8427. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  8428. GetNextInstruction(p,hp1) and
  8429. (hp1.typ = ait_instruction);
  8430. if reg_and_hp1_is_instr and
  8431. (
  8432. (taicpu(hp1).opcode <> A_LEA) or
  8433. { If the LEA instruction can be converted into an arithmetic instruction,
  8434. it may be possible to then fold it. }
  8435. (
  8436. { If the flags register is in use, don't change the instruction
  8437. to an ADD otherwise this will scramble the flags. [Kit] }
  8438. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8439. ConvertLEA(taicpu(hp1))
  8440. )
  8441. ) and
  8442. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  8443. GetNextInstruction(hp1,hp2) and
  8444. MatchInstruction(hp2,A_MOV,[]) and
  8445. (taicpu(hp2).oper[0]^.typ = top_reg) and
  8446. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  8447. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  8448. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  8449. {$ifdef i386}
  8450. { not all registers have byte size sub registers on i386 }
  8451. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  8452. {$endif i386}
  8453. (((taicpu(hp1).ops=2) and
  8454. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8455. ((taicpu(hp1).ops=1) and
  8456. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  8457. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  8458. begin
  8459. { change movsX/movzX reg/ref, reg2
  8460. add/sub/or/... reg3/$const, reg2
  8461. mov reg2 reg/ref
  8462. to add/sub/or/... reg3/$const, reg/ref }
  8463. { by example:
  8464. movswl %si,%eax movswl %si,%eax p
  8465. decl %eax addl %edx,%eax hp1
  8466. movw %ax,%si movw %ax,%si hp2
  8467. ->
  8468. movswl %si,%eax movswl %si,%eax p
  8469. decw %eax addw %edx,%eax hp1
  8470. movw %ax,%si movw %ax,%si hp2
  8471. }
  8472. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  8473. {
  8474. ->
  8475. movswl %si,%eax movswl %si,%eax p
  8476. decw %si addw %dx,%si hp1
  8477. movw %ax,%si movw %ax,%si hp2
  8478. }
  8479. case taicpu(hp1).ops of
  8480. 1:
  8481. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  8482. 2:
  8483. begin
  8484. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  8485. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8486. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  8487. end;
  8488. else
  8489. internalerror(2008042702);
  8490. end;
  8491. {
  8492. ->
  8493. decw %si addw %dx,%si p
  8494. }
  8495. DebugMsg(SPeepholeOptimization + 'var3',p);
  8496. RemoveCurrentP(p, hp1);
  8497. RemoveInstruction(hp2);
  8498. end
  8499. else if reg_and_hp1_is_instr and
  8500. (taicpu(hp1).opcode = A_MOV) and
  8501. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8502. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  8503. {$ifdef x86_64}
  8504. { check for implicit extension to 64 bit }
  8505. or
  8506. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8507. (taicpu(hp1).opsize=S_Q) and
  8508. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  8509. )
  8510. {$endif x86_64}
  8511. )
  8512. then
  8513. begin
  8514. { change
  8515. movx %reg1,%reg2
  8516. mov %reg2,%reg3
  8517. dealloc %reg2
  8518. into
  8519. movx %reg,%reg3
  8520. }
  8521. TransferUsedRegs(TmpUsedRegs);
  8522. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8523. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8524. begin
  8525. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  8526. {$ifdef x86_64}
  8527. if (taicpu(p).opsize in [S_BL,S_WL]) and
  8528. (taicpu(hp1).opsize=S_Q) then
  8529. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  8530. else
  8531. {$endif x86_64}
  8532. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8533. RemoveInstruction(hp1);
  8534. end;
  8535. end
  8536. else if reg_and_hp1_is_instr and
  8537. ((taicpu(hp1).opcode=A_MOV) or
  8538. (taicpu(hp1).opcode=A_ADD) or
  8539. (taicpu(hp1).opcode=A_SUB) or
  8540. (taicpu(hp1).opcode=A_CMP) or
  8541. (taicpu(hp1).opcode=A_OR) or
  8542. (taicpu(hp1).opcode=A_XOR) or
  8543. (taicpu(hp1).opcode=A_AND)
  8544. ) and
  8545. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8546. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  8547. (taicpu(hp1).opsize=S_B)) or
  8548. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  8549. (taicpu(hp1).opsize=S_W))
  8550. {$ifdef x86_64}
  8551. or ((taicpu(p).opsize=S_LQ) and
  8552. (taicpu(hp1).opsize=S_L))
  8553. {$endif x86_64}
  8554. ) and
  8555. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  8556. begin
  8557. { change
  8558. movx %reg1,%reg2
  8559. mov %reg2,%reg3
  8560. dealloc %reg2
  8561. into
  8562. mov %reg1,%reg3
  8563. if the second mov accesses only the bits stored in reg1
  8564. }
  8565. TransferUsedRegs(TmpUsedRegs);
  8566. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8567. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8568. begin
  8569. DebugMsg(SPeepholeOptimization + 'MovxOp2Op',p);
  8570. if taicpu(p).oper[0]^.typ=top_reg then
  8571. begin
  8572. case taicpu(hp1).opsize of
  8573. S_B:
  8574. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  8575. S_W:
  8576. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  8577. S_L:
  8578. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  8579. else
  8580. Internalerror(2020102301);
  8581. end;
  8582. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  8583. end
  8584. else
  8585. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  8586. RemoveCurrentP(p);
  8587. result:=true;
  8588. exit;
  8589. end;
  8590. end
  8591. else if reg_and_hp1_is_instr and
  8592. (taicpu(p).oper[0]^.typ = top_reg) and
  8593. (
  8594. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  8595. ) and
  8596. (taicpu(hp1).oper[0]^.typ = top_const) and
  8597. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8598. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8599. { Minimum shift value allowed is the bit difference between the sizes }
  8600. (taicpu(hp1).oper[0]^.val >=
  8601. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8602. 8 * (
  8603. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  8604. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8605. )
  8606. ) then
  8607. begin
  8608. { For:
  8609. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  8610. shl/sal ##, %reg1
  8611. Remove the movsx/movzx instruction if the shift overwrites the
  8612. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  8613. }
  8614. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  8615. RemoveCurrentP(p, hp1);
  8616. Result := True;
  8617. Exit;
  8618. end
  8619. else if reg_and_hp1_is_instr and
  8620. (taicpu(p).oper[0]^.typ = top_reg) and
  8621. (
  8622. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  8623. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  8624. ) and
  8625. (taicpu(hp1).oper[0]^.typ = top_const) and
  8626. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8627. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8628. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  8629. (taicpu(hp1).oper[0]^.val <
  8630. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8631. 8 * (
  8632. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8633. )
  8634. ) then
  8635. begin
  8636. { For:
  8637. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  8638. sar ##, %reg1 shr ##, %reg1
  8639. Move the shift to before the movx instruction if the shift value
  8640. is not too large.
  8641. }
  8642. asml.Remove(hp1);
  8643. asml.InsertBefore(hp1, p);
  8644. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8645. case taicpu(p).opsize of
  8646. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  8647. taicpu(hp1).opsize := S_B;
  8648. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  8649. taicpu(hp1).opsize := S_W;
  8650. {$ifdef x86_64}
  8651. S_LQ:
  8652. taicpu(hp1).opsize := S_L;
  8653. {$endif}
  8654. else
  8655. InternalError(2020112401);
  8656. end;
  8657. if (taicpu(hp1).opcode = A_SHR) then
  8658. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  8659. else
  8660. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  8661. Result := True;
  8662. end
  8663. else if taicpu(p).opcode=A_MOVZX then
  8664. begin
  8665. { removes superfluous And's after movzx's }
  8666. if reg_and_hp1_is_instr and
  8667. (taicpu(hp1).opcode = A_AND) and
  8668. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8669. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  8670. {$ifdef x86_64}
  8671. { check for implicit extension to 64 bit }
  8672. or
  8673. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8674. (taicpu(hp1).opsize=S_Q) and
  8675. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  8676. )
  8677. {$endif x86_64}
  8678. )
  8679. then
  8680. begin
  8681. case taicpu(p).opsize Of
  8682. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8683. if (taicpu(hp1).oper[0]^.val = $ff) then
  8684. begin
  8685. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  8686. RemoveInstruction(hp1);
  8687. Result:=true;
  8688. exit;
  8689. end;
  8690. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8691. if (taicpu(hp1).oper[0]^.val = $ffff) then
  8692. begin
  8693. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  8694. RemoveInstruction(hp1);
  8695. Result:=true;
  8696. exit;
  8697. end;
  8698. {$ifdef x86_64}
  8699. S_LQ:
  8700. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  8701. begin
  8702. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  8703. RemoveInstruction(hp1);
  8704. Result:=true;
  8705. exit;
  8706. end;
  8707. {$endif x86_64}
  8708. else
  8709. ;
  8710. end;
  8711. { we cannot get rid of the and, but can we get rid of the movz ?}
  8712. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  8713. begin
  8714. case taicpu(p).opsize Of
  8715. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8716. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  8717. begin
  8718. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  8719. RemoveCurrentP(p,hp1);
  8720. Result:=true;
  8721. exit;
  8722. end;
  8723. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8724. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  8725. begin
  8726. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  8727. RemoveCurrentP(p,hp1);
  8728. Result:=true;
  8729. exit;
  8730. end;
  8731. {$ifdef x86_64}
  8732. S_LQ:
  8733. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  8734. begin
  8735. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  8736. RemoveCurrentP(p,hp1);
  8737. Result:=true;
  8738. exit;
  8739. end;
  8740. {$endif x86_64}
  8741. else
  8742. ;
  8743. end;
  8744. end;
  8745. end;
  8746. { changes some movzx constructs to faster synonyms (all examples
  8747. are given with eax/ax, but are also valid for other registers)}
  8748. if MatchOpType(taicpu(p),top_reg,top_reg) then
  8749. begin
  8750. case taicpu(p).opsize of
  8751. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  8752. (the machine code is equivalent to movzbl %al,%eax), but the
  8753. code generator still generates that assembler instruction and
  8754. it is silently converted. This should probably be checked.
  8755. [Kit] }
  8756. S_BW:
  8757. begin
  8758. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8759. (
  8760. not IsMOVZXAcceptable
  8761. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  8762. or (
  8763. (cs_opt_size in current_settings.optimizerswitches) and
  8764. (taicpu(p).oper[1]^.reg = NR_AX)
  8765. )
  8766. ) then
  8767. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  8768. begin
  8769. DebugMsg(SPeepholeOptimization + 'var7',p);
  8770. taicpu(p).opcode := A_AND;
  8771. taicpu(p).changeopsize(S_W);
  8772. taicpu(p).loadConst(0,$ff);
  8773. Result := True;
  8774. end
  8775. else if not IsMOVZXAcceptable and
  8776. GetNextInstruction(p, hp1) and
  8777. (tai(hp1).typ = ait_instruction) and
  8778. (taicpu(hp1).opcode = A_AND) and
  8779. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8780. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8781. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  8782. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  8783. begin
  8784. DebugMsg(SPeepholeOptimization + 'var8',p);
  8785. taicpu(p).opcode := A_MOV;
  8786. taicpu(p).changeopsize(S_W);
  8787. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  8788. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8789. Result := True;
  8790. end;
  8791. end;
  8792. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  8793. S_BL:
  8794. begin
  8795. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8796. (
  8797. not IsMOVZXAcceptable
  8798. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  8799. or (
  8800. (cs_opt_size in current_settings.optimizerswitches) and
  8801. (taicpu(p).oper[1]^.reg = NR_EAX)
  8802. )
  8803. ) then
  8804. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  8805. begin
  8806. DebugMsg(SPeepholeOptimization + 'var9',p);
  8807. taicpu(p).opcode := A_AND;
  8808. taicpu(p).changeopsize(S_L);
  8809. taicpu(p).loadConst(0,$ff);
  8810. Result := True;
  8811. end
  8812. else if not IsMOVZXAcceptable and
  8813. GetNextInstruction(p, hp1) and
  8814. (tai(hp1).typ = ait_instruction) and
  8815. (taicpu(hp1).opcode = A_AND) and
  8816. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8817. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8818. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  8819. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  8820. begin
  8821. DebugMsg(SPeepholeOptimization + 'var10',p);
  8822. taicpu(p).opcode := A_MOV;
  8823. taicpu(p).changeopsize(S_L);
  8824. { do not use R_SUBWHOLE
  8825. as movl %rdx,%eax
  8826. is invalid in assembler PM }
  8827. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8828. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8829. Result := True;
  8830. end;
  8831. end;
  8832. {$endif i8086}
  8833. S_WL:
  8834. if not IsMOVZXAcceptable then
  8835. begin
  8836. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  8837. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  8838. begin
  8839. DebugMsg(SPeepholeOptimization + 'var11',p);
  8840. taicpu(p).opcode := A_AND;
  8841. taicpu(p).changeopsize(S_L);
  8842. taicpu(p).loadConst(0,$ffff);
  8843. Result := True;
  8844. end
  8845. else if GetNextInstruction(p, hp1) and
  8846. (tai(hp1).typ = ait_instruction) and
  8847. (taicpu(hp1).opcode = A_AND) and
  8848. (taicpu(hp1).oper[0]^.typ = top_const) and
  8849. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8850. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8851. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  8852. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  8853. begin
  8854. DebugMsg(SPeepholeOptimization + 'var12',p);
  8855. taicpu(p).opcode := A_MOV;
  8856. taicpu(p).changeopsize(S_L);
  8857. { do not use R_SUBWHOLE
  8858. as movl %rdx,%eax
  8859. is invalid in assembler PM }
  8860. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8861. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8862. Result := True;
  8863. end;
  8864. end;
  8865. else
  8866. InternalError(2017050705);
  8867. end;
  8868. end
  8869. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  8870. begin
  8871. if GetNextInstruction(p, hp1) and
  8872. (tai(hp1).typ = ait_instruction) and
  8873. (taicpu(hp1).opcode = A_AND) and
  8874. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8875. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8876. begin
  8877. //taicpu(p).opcode := A_MOV;
  8878. case taicpu(p).opsize Of
  8879. S_BL:
  8880. begin
  8881. DebugMsg(SPeepholeOptimization + 'var13',p);
  8882. taicpu(hp1).changeopsize(S_L);
  8883. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8884. end;
  8885. S_WL:
  8886. begin
  8887. DebugMsg(SPeepholeOptimization + 'var14',p);
  8888. taicpu(hp1).changeopsize(S_L);
  8889. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8890. end;
  8891. S_BW:
  8892. begin
  8893. DebugMsg(SPeepholeOptimization + 'var15',p);
  8894. taicpu(hp1).changeopsize(S_W);
  8895. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8896. end;
  8897. else
  8898. Internalerror(2017050704)
  8899. end;
  8900. Result := True;
  8901. end;
  8902. end;
  8903. end;
  8904. end;
  8905. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8906. var
  8907. hp1, hp2 : tai;
  8908. MaskLength : Cardinal;
  8909. MaskedBits : TCgInt;
  8910. begin
  8911. Result:=false;
  8912. { There are no optimisations for reference targets }
  8913. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8914. Exit;
  8915. while GetNextInstruction(p, hp1) and
  8916. (hp1.typ = ait_instruction) do
  8917. begin
  8918. if (taicpu(p).oper[0]^.typ = top_const) then
  8919. begin
  8920. case taicpu(hp1).opcode of
  8921. A_AND:
  8922. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8923. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8924. { the second register must contain the first one, so compare their subreg types }
  8925. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8926. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8927. { change
  8928. and const1, reg
  8929. and const2, reg
  8930. to
  8931. and (const1 and const2), reg
  8932. }
  8933. begin
  8934. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8935. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8936. RemoveCurrentP(p, hp1);
  8937. Result:=true;
  8938. exit;
  8939. end;
  8940. A_CMP:
  8941. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8942. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8943. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8944. { Just check that the condition on the next instruction is compatible }
  8945. GetNextInstruction(hp1, hp2) and
  8946. (hp2.typ = ait_instruction) and
  8947. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8948. then
  8949. { change
  8950. and 2^n, reg
  8951. cmp 2^n, reg
  8952. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8953. to
  8954. and 2^n, reg
  8955. test reg, reg
  8956. j(~c) / set(~c) / cmov(~c)
  8957. }
  8958. begin
  8959. { Keep TEST instruction in, rather than remove it, because
  8960. it may trigger other optimisations such as MovAndTest2Test }
  8961. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8962. taicpu(hp1).opcode := A_TEST;
  8963. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8964. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8965. Result := True;
  8966. Exit;
  8967. end;
  8968. A_MOVZX:
  8969. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8970. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8971. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8972. (
  8973. (
  8974. (taicpu(p).opsize=S_W) and
  8975. (taicpu(hp1).opsize=S_BW)
  8976. ) or
  8977. (
  8978. (taicpu(p).opsize=S_L) and
  8979. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8980. )
  8981. {$ifdef x86_64}
  8982. or
  8983. (
  8984. (taicpu(p).opsize=S_Q) and
  8985. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8986. )
  8987. {$endif x86_64}
  8988. ) then
  8989. begin
  8990. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8991. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8992. ) or
  8993. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8994. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  8995. then
  8996. begin
  8997. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  8998. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  8999. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  9000. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  9001. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  9002. }
  9003. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  9004. RemoveInstruction(hp1);
  9005. { See if there are other optimisations possible }
  9006. Continue;
  9007. end;
  9008. end;
  9009. A_SHL:
  9010. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  9011. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9012. begin
  9013. {$ifopt R+}
  9014. {$define RANGE_WAS_ON}
  9015. {$R-}
  9016. {$endif}
  9017. { get length of potential and mask }
  9018. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  9019. { really a mask? }
  9020. {$ifdef RANGE_WAS_ON}
  9021. {$R+}
  9022. {$endif}
  9023. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  9024. { unmasked part shifted out? }
  9025. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  9026. begin
  9027. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  9028. RemoveCurrentP(p, hp1);
  9029. Result:=true;
  9030. exit;
  9031. end;
  9032. end;
  9033. A_SHR:
  9034. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  9035. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9036. (taicpu(hp1).oper[0]^.val <= 63) then
  9037. begin
  9038. { Does SHR combined with the AND cover all the bits?
  9039. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  9040. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  9041. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  9042. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  9043. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  9044. begin
  9045. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  9046. RemoveCurrentP(p, hp1);
  9047. Result := True;
  9048. Exit;
  9049. end;
  9050. end;
  9051. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9052. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9053. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9054. begin
  9055. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  9056. (
  9057. (
  9058. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  9059. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  9060. ) or (
  9061. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  9062. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  9063. {$ifdef x86_64}
  9064. ) or (
  9065. (taicpu(hp1).opsize = S_LQ) and
  9066. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  9067. {$endif x86_64}
  9068. )
  9069. ) then
  9070. begin
  9071. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  9072. begin
  9073. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  9074. RemoveInstruction(hp1);
  9075. { See if there are other optimisations possible }
  9076. Continue;
  9077. end;
  9078. { The super-registers are the same though.
  9079. Note that this change by itself doesn't improve
  9080. code speed, but it opens up other optimisations. }
  9081. {$ifdef x86_64}
  9082. { Convert 64-bit register to 32-bit }
  9083. case taicpu(hp1).opsize of
  9084. S_BQ:
  9085. begin
  9086. taicpu(hp1).opsize := S_BL;
  9087. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  9088. end;
  9089. S_WQ:
  9090. begin
  9091. taicpu(hp1).opsize := S_WL;
  9092. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  9093. end
  9094. else
  9095. ;
  9096. end;
  9097. {$endif x86_64}
  9098. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  9099. taicpu(hp1).opcode := A_MOVZX;
  9100. { See if there are other optimisations possible }
  9101. Continue;
  9102. end;
  9103. end;
  9104. else
  9105. ;
  9106. end;
  9107. end;
  9108. if (taicpu(hp1).is_jmp) and
  9109. (taicpu(hp1).opcode<>A_JMP) and
  9110. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  9111. begin
  9112. { change
  9113. and x, reg
  9114. jxx
  9115. to
  9116. test x, reg
  9117. jxx
  9118. if reg is deallocated before the
  9119. jump, but only if it's a conditional jump (PFV)
  9120. }
  9121. taicpu(p).opcode := A_TEST;
  9122. Exit;
  9123. end;
  9124. Break;
  9125. end;
  9126. { Lone AND tests }
  9127. if (taicpu(p).oper[0]^.typ = top_const) then
  9128. begin
  9129. {
  9130. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  9131. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  9132. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  9133. }
  9134. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  9135. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  9136. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  9137. begin
  9138. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  9139. if taicpu(p).opsize = S_L then
  9140. begin
  9141. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  9142. Result := True;
  9143. end;
  9144. end;
  9145. end;
  9146. { Backward check to determine necessity of and %reg,%reg }
  9147. if (taicpu(p).oper[0]^.typ = top_reg) and
  9148. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9149. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9150. GetLastInstruction(p, hp2) and
  9151. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  9152. { Check size of adjacent instruction to determine if the AND is
  9153. effectively a null operation }
  9154. (
  9155. (taicpu(p).opsize = taicpu(hp2).opsize) or
  9156. { Note: Don't include S_Q }
  9157. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  9158. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  9159. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  9160. ) then
  9161. begin
  9162. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  9163. { If GetNextInstruction returned False, hp1 will be nil }
  9164. RemoveCurrentP(p, hp1);
  9165. Result := True;
  9166. Exit;
  9167. end;
  9168. end;
  9169. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  9170. var
  9171. hp1: tai; NewRef: TReference;
  9172. { This entire nested function is used in an if-statement below, but we
  9173. want to avoid all the used reg transfers and GetNextInstruction calls
  9174. until we really have to check }
  9175. function MemRegisterNotUsedLater: Boolean; inline;
  9176. var
  9177. hp2: tai;
  9178. begin
  9179. TransferUsedRegs(TmpUsedRegs);
  9180. hp2 := p;
  9181. repeat
  9182. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9183. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9184. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  9185. end;
  9186. begin
  9187. Result := False;
  9188. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  9189. Exit;
  9190. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  9191. begin
  9192. { Change:
  9193. add %reg2,%reg1
  9194. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  9195. To:
  9196. mov/s/z #(%reg1,%reg2),%reg1
  9197. }
  9198. if MatchOpType(taicpu(p), top_reg, top_reg) and
  9199. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  9200. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  9201. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  9202. (
  9203. (
  9204. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  9205. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  9206. { r/esp cannot be an index }
  9207. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  9208. ) or (
  9209. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  9210. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  9211. )
  9212. ) and (
  9213. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  9214. (
  9215. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  9216. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  9217. MemRegisterNotUsedLater
  9218. )
  9219. ) then
  9220. begin
  9221. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  9222. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  9223. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  9224. RemoveCurrentp(p, hp1);
  9225. Result := True;
  9226. Exit;
  9227. end;
  9228. { Change:
  9229. addl/q $x,%reg1
  9230. movl/q %reg1,%reg2
  9231. To:
  9232. leal/q $x(%reg1),%reg2
  9233. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  9234. Breaks the dependency chain.
  9235. }
  9236. if MatchOpType(taicpu(p),top_const,top_reg) and
  9237. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  9238. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9239. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  9240. (
  9241. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  9242. not (cs_opt_size in current_settings.optimizerswitches) or
  9243. (
  9244. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  9245. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  9246. )
  9247. ) then
  9248. begin
  9249. { Change the MOV instruction to a LEA instruction, and update the
  9250. first operand }
  9251. reference_reset(NewRef, 1, []);
  9252. NewRef.base := taicpu(p).oper[1]^.reg;
  9253. NewRef.scalefactor := 1;
  9254. NewRef.offset := taicpu(p).oper[0]^.val;
  9255. taicpu(hp1).opcode := A_LEA;
  9256. taicpu(hp1).loadref(0, NewRef);
  9257. TransferUsedRegs(TmpUsedRegs);
  9258. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9259. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  9260. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  9261. begin
  9262. { Move what is now the LEA instruction to before the SUB instruction }
  9263. Asml.Remove(hp1);
  9264. Asml.InsertBefore(hp1, p);
  9265. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  9266. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  9267. p := hp1;
  9268. end
  9269. else
  9270. begin
  9271. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  9272. RemoveCurrentP(p, hp1);
  9273. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  9274. end;
  9275. Result := True;
  9276. end;
  9277. end;
  9278. end;
  9279. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  9280. var
  9281. SubReg: TSubRegister;
  9282. begin
  9283. Result:=false;
  9284. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  9285. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9286. with taicpu(p).oper[0]^.ref^ do
  9287. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  9288. begin
  9289. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  9290. begin
  9291. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  9292. taicpu(p).opcode := A_ADD;
  9293. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  9294. Result := True;
  9295. end
  9296. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  9297. begin
  9298. if (base <> NR_NO) then
  9299. begin
  9300. if (scalefactor <= 1) then
  9301. begin
  9302. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  9303. taicpu(p).opcode := A_ADD;
  9304. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  9305. Result := True;
  9306. end;
  9307. end
  9308. else
  9309. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  9310. if (scalefactor in [2, 4, 8]) then
  9311. begin
  9312. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  9313. taicpu(p).loadconst(0, BsrByte(scalefactor));
  9314. taicpu(p).opcode := A_SHL;
  9315. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  9316. Result := True;
  9317. end;
  9318. end;
  9319. end;
  9320. end;
  9321. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  9322. var
  9323. hp1: tai; NewRef: TReference;
  9324. begin
  9325. { Change:
  9326. subl/q $x,%reg1
  9327. movl/q %reg1,%reg2
  9328. To:
  9329. leal/q $-x(%reg1),%reg2
  9330. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  9331. Breaks the dependency chain and potentially permits the removal of
  9332. a CMP instruction if one follows.
  9333. }
  9334. Result := False;
  9335. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9336. MatchOpType(taicpu(p),top_const,top_reg) and
  9337. GetNextInstruction(p, hp1) and
  9338. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  9339. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9340. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  9341. (
  9342. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  9343. not (cs_opt_size in current_settings.optimizerswitches) or
  9344. (
  9345. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  9346. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  9347. )
  9348. ) then
  9349. begin
  9350. { Change the MOV instruction to a LEA instruction, and update the
  9351. first operand }
  9352. reference_reset(NewRef, 1, []);
  9353. NewRef.base := taicpu(p).oper[1]^.reg;
  9354. NewRef.scalefactor := 1;
  9355. NewRef.offset := -taicpu(p).oper[0]^.val;
  9356. taicpu(hp1).opcode := A_LEA;
  9357. taicpu(hp1).loadref(0, NewRef);
  9358. TransferUsedRegs(TmpUsedRegs);
  9359. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9360. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  9361. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  9362. begin
  9363. { Move what is now the LEA instruction to before the SUB instruction }
  9364. Asml.Remove(hp1);
  9365. Asml.InsertBefore(hp1, p);
  9366. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  9367. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  9368. p := hp1;
  9369. end
  9370. else
  9371. begin
  9372. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  9373. RemoveCurrentP(p, hp1);
  9374. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  9375. end;
  9376. Result := True;
  9377. end;
  9378. end;
  9379. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  9380. begin
  9381. { we can skip all instructions not messing with the stack pointer }
  9382. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  9383. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  9384. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  9385. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  9386. ({(taicpu(hp1).ops=0) or }
  9387. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  9388. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  9389. ) and }
  9390. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  9391. )
  9392. ) do
  9393. GetNextInstruction(hp1,hp1);
  9394. Result:=assigned(hp1);
  9395. end;
  9396. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  9397. var
  9398. hp1, hp2, hp3, hp4, hp5: tai;
  9399. begin
  9400. Result:=false;
  9401. hp5:=nil;
  9402. { replace
  9403. leal(q) x(<stackpointer>),<stackpointer>
  9404. call procname
  9405. leal(q) -x(<stackpointer>),<stackpointer>
  9406. ret
  9407. by
  9408. jmp procname
  9409. but do it only on level 4 because it destroys stack back traces
  9410. }
  9411. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9412. MatchOpType(taicpu(p),top_ref,top_reg) and
  9413. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  9414. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  9415. { the -8 or -24 are not required, but bail out early if possible,
  9416. higher values are unlikely }
  9417. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  9418. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  9419. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  9420. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  9421. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  9422. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  9423. GetNextInstruction(p, hp1) and
  9424. { Take a copy of hp1 }
  9425. SetAndTest(hp1, hp4) and
  9426. { trick to skip label }
  9427. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  9428. SkipSimpleInstructions(hp1) and
  9429. MatchInstruction(hp1,A_CALL,[S_NO]) and
  9430. GetNextInstruction(hp1, hp2) and
  9431. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  9432. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  9433. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  9434. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  9435. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  9436. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  9437. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  9438. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  9439. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  9440. GetNextInstruction(hp2, hp3) and
  9441. { trick to skip label }
  9442. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  9443. (MatchInstruction(hp3,A_RET,[S_NO]) or
  9444. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  9445. SetAndTest(hp3,hp5) and
  9446. GetNextInstruction(hp3,hp3) and
  9447. MatchInstruction(hp3,A_RET,[S_NO])
  9448. )
  9449. ) and
  9450. (taicpu(hp3).ops=0) then
  9451. begin
  9452. taicpu(hp1).opcode := A_JMP;
  9453. taicpu(hp1).is_jmp := true;
  9454. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  9455. RemoveCurrentP(p, hp4);
  9456. RemoveInstruction(hp2);
  9457. RemoveInstruction(hp3);
  9458. if Assigned(hp5) then
  9459. begin
  9460. AsmL.Remove(hp5);
  9461. ASmL.InsertBefore(hp5,hp1)
  9462. end;
  9463. Result:=true;
  9464. end;
  9465. end;
  9466. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  9467. {$ifdef x86_64}
  9468. var
  9469. hp1, hp2, hp3, hp4, hp5: tai;
  9470. {$endif x86_64}
  9471. begin
  9472. Result:=false;
  9473. {$ifdef x86_64}
  9474. hp5:=nil;
  9475. { replace
  9476. push %rax
  9477. call procname
  9478. pop %rcx
  9479. ret
  9480. by
  9481. jmp procname
  9482. but do it only on level 4 because it destroys stack back traces
  9483. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  9484. for all supported calling conventions
  9485. }
  9486. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9487. MatchOpType(taicpu(p),top_reg) and
  9488. (taicpu(p).oper[0]^.reg=NR_RAX) and
  9489. GetNextInstruction(p, hp1) and
  9490. { Take a copy of hp1 }
  9491. SetAndTest(hp1, hp4) and
  9492. { trick to skip label }
  9493. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  9494. SkipSimpleInstructions(hp1) and
  9495. MatchInstruction(hp1,A_CALL,[S_NO]) and
  9496. GetNextInstruction(hp1, hp2) and
  9497. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  9498. MatchOpType(taicpu(hp2),top_reg) and
  9499. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  9500. GetNextInstruction(hp2, hp3) and
  9501. { trick to skip label }
  9502. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  9503. (MatchInstruction(hp3,A_RET,[S_NO]) or
  9504. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  9505. SetAndTest(hp3,hp5) and
  9506. GetNextInstruction(hp3,hp3) and
  9507. MatchInstruction(hp3,A_RET,[S_NO])
  9508. )
  9509. ) and
  9510. (taicpu(hp3).ops=0) then
  9511. begin
  9512. taicpu(hp1).opcode := A_JMP;
  9513. taicpu(hp1).is_jmp := true;
  9514. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  9515. RemoveCurrentP(p, hp4);
  9516. RemoveInstruction(hp2);
  9517. RemoveInstruction(hp3);
  9518. if Assigned(hp5) then
  9519. begin
  9520. AsmL.Remove(hp5);
  9521. ASmL.InsertBefore(hp5,hp1)
  9522. end;
  9523. Result:=true;
  9524. end;
  9525. {$endif x86_64}
  9526. end;
  9527. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  9528. var
  9529. Value, RegName: string;
  9530. begin
  9531. Result:=false;
  9532. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  9533. begin
  9534. case taicpu(p).oper[0]^.val of
  9535. 0:
  9536. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  9537. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9538. begin
  9539. { change "mov $0,%reg" into "xor %reg,%reg" }
  9540. taicpu(p).opcode := A_XOR;
  9541. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  9542. Result := True;
  9543. {$ifdef x86_64}
  9544. end
  9545. else if (taicpu(p).opsize = S_Q) then
  9546. begin
  9547. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9548. { The actual optimization }
  9549. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9550. taicpu(p).changeopsize(S_L);
  9551. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9552. Result := True;
  9553. end;
  9554. $1..$FFFFFFFF:
  9555. begin
  9556. { Code size reduction by J. Gareth "Kit" Moreton }
  9557. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  9558. case taicpu(p).opsize of
  9559. S_Q:
  9560. begin
  9561. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9562. Value := debug_tostr(taicpu(p).oper[0]^.val);
  9563. { The actual optimization }
  9564. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9565. taicpu(p).changeopsize(S_L);
  9566. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9567. Result := True;
  9568. end;
  9569. else
  9570. { Do nothing };
  9571. end;
  9572. {$endif x86_64}
  9573. end;
  9574. -1:
  9575. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  9576. if (cs_opt_size in current_settings.optimizerswitches) and
  9577. (taicpu(p).opsize <> S_B) and
  9578. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9579. begin
  9580. { change "mov $-1,%reg" into "or $-1,%reg" }
  9581. { NOTES:
  9582. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  9583. - This operation creates a false dependency on the register, so only do it when optimising for size
  9584. - 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
  9585. }
  9586. taicpu(p).opcode := A_OR;
  9587. Result := True;
  9588. end;
  9589. else
  9590. { Do nothing };
  9591. end;
  9592. end;
  9593. end;
  9594. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  9595. var
  9596. hp1: tai;
  9597. begin
  9598. { Detect:
  9599. andw x, %ax (0 <= x < $8000)
  9600. ...
  9601. movzwl %ax,%eax
  9602. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9603. }
  9604. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  9605. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9606. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  9607. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9608. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9609. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9610. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9611. begin
  9612. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  9613. taicpu(hp1).opcode := A_CWDE;
  9614. taicpu(hp1).clearop(0);
  9615. taicpu(hp1).clearop(1);
  9616. taicpu(hp1).ops := 0;
  9617. { A change was made, but not with p, so move forward 1 }
  9618. p := tai(p.Next);
  9619. Result := True;
  9620. end;
  9621. end;
  9622. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  9623. begin
  9624. Result := False;
  9625. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  9626. Exit;
  9627. { Convert:
  9628. movswl %ax,%eax -> cwtl
  9629. movslq %eax,%rax -> cdqe
  9630. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  9631. refer to the same opcode and depends only on the assembler's
  9632. current operand-size attribute. [Kit]
  9633. }
  9634. with taicpu(p) do
  9635. case opsize of
  9636. S_WL:
  9637. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  9638. begin
  9639. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  9640. opcode := A_CWDE;
  9641. clearop(0);
  9642. clearop(1);
  9643. ops := 0;
  9644. Result := True;
  9645. end;
  9646. {$ifdef x86_64}
  9647. S_LQ:
  9648. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  9649. begin
  9650. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  9651. opcode := A_CDQE;
  9652. clearop(0);
  9653. clearop(1);
  9654. ops := 0;
  9655. Result := True;
  9656. end;
  9657. {$endif x86_64}
  9658. else
  9659. ;
  9660. end;
  9661. end;
  9662. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  9663. var
  9664. hp1: tai;
  9665. begin
  9666. { Detect:
  9667. shr x, %ax (x > 0)
  9668. ...
  9669. movzwl %ax,%eax
  9670. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9671. }
  9672. Result := False;
  9673. if MatchOpType(taicpu(p), top_const, top_reg) and
  9674. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9675. (taicpu(p).oper[0]^.val > 0) and
  9676. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9677. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9678. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9679. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9680. begin
  9681. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  9682. taicpu(hp1).opcode := A_CWDE;
  9683. taicpu(hp1).clearop(0);
  9684. taicpu(hp1).clearop(1);
  9685. taicpu(hp1).ops := 0;
  9686. { A change was made, but not with p, so move forward 1 }
  9687. p := tai(p.Next);
  9688. Result := True;
  9689. end;
  9690. end;
  9691. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  9692. var
  9693. hp1, hp2: tai;
  9694. begin
  9695. { Detect:
  9696. add/sub %reg2,(dest)
  9697. add/sub x, (dest)
  9698. (dest can be a register or a reference)
  9699. Swap the instructions to minimise a pipeline stall. This reverses the
  9700. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  9701. optimisations could be made.
  9702. }
  9703. Result := False;
  9704. if (taicpu(p).oper[0]^.typ = top_reg) and
  9705. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  9706. (
  9707. (
  9708. (taicpu(p).oper[1]^.typ = top_reg) and
  9709. { We can try searching further ahead if we're writing to a register }
  9710. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  9711. ) or
  9712. (
  9713. (taicpu(p).oper[1]^.typ = top_ref) and
  9714. GetNextInstruction(p, hp1)
  9715. )
  9716. ) and
  9717. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  9718. (taicpu(hp1).oper[0]^.typ = top_const) and
  9719. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  9720. begin
  9721. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  9722. TransferUsedRegs(TmpUsedRegs);
  9723. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9724. hp2 := p;
  9725. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  9726. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  9727. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9728. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  9729. begin
  9730. asml.remove(hp1);
  9731. asml.InsertBefore(hp1, p);
  9732. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  9733. Result := True;
  9734. end;
  9735. end;
  9736. end;
  9737. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  9738. begin
  9739. Result:=false;
  9740. { change "cmp $0, %reg" to "test %reg, %reg" }
  9741. if MatchOpType(taicpu(p),top_const,top_reg) and
  9742. (taicpu(p).oper[0]^.val = 0) then
  9743. begin
  9744. taicpu(p).opcode := A_TEST;
  9745. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  9746. Result:=true;
  9747. end;
  9748. end;
  9749. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  9750. var
  9751. IsTestConstX : Boolean;
  9752. hp1,hp2 : tai;
  9753. begin
  9754. Result:=false;
  9755. { removes the line marked with (x) from the sequence
  9756. and/or/xor/add/sub/... $x, %y
  9757. test/or %y, %y | test $-1, %y (x)
  9758. j(n)z _Label
  9759. as the first instruction already adjusts the ZF
  9760. %y operand may also be a reference }
  9761. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  9762. MatchOperand(taicpu(p).oper[0]^,-1);
  9763. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  9764. GetLastInstruction(p, hp1) and
  9765. (tai(hp1).typ = ait_instruction) and
  9766. GetNextInstruction(p,hp2) and
  9767. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  9768. case taicpu(hp1).opcode Of
  9769. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  9770. begin
  9771. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9772. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9773. { and in case of carry for A(E)/B(E)/C/NC }
  9774. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  9775. ((taicpu(hp1).opcode <> A_ADD) and
  9776. (taicpu(hp1).opcode <> A_SUB))) then
  9777. begin
  9778. RemoveCurrentP(p, hp2);
  9779. Result:=true;
  9780. Exit;
  9781. end;
  9782. end;
  9783. A_SHL, A_SAL, A_SHR, A_SAR:
  9784. begin
  9785. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9786. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  9787. { therefore, it's only safe to do this optimization for }
  9788. { shifts by a (nonzero) constant }
  9789. (taicpu(hp1).oper[0]^.typ = top_const) and
  9790. (taicpu(hp1).oper[0]^.val <> 0) and
  9791. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9792. { and in case of carry for A(E)/B(E)/C/NC }
  9793. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9794. begin
  9795. RemoveCurrentP(p, hp2);
  9796. Result:=true;
  9797. Exit;
  9798. end;
  9799. end;
  9800. A_DEC, A_INC, A_NEG:
  9801. begin
  9802. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  9803. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9804. { and in case of carry for A(E)/B(E)/C/NC }
  9805. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9806. begin
  9807. RemoveCurrentP(p, hp2);
  9808. Result:=true;
  9809. Exit;
  9810. end;
  9811. end
  9812. else
  9813. ;
  9814. end; { case }
  9815. { change "test $-1,%reg" into "test %reg,%reg" }
  9816. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  9817. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  9818. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  9819. if MatchInstruction(p, A_OR, []) and
  9820. { Can only match if they're both registers }
  9821. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  9822. begin
  9823. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  9824. taicpu(p).opcode := A_TEST;
  9825. { No need to set Result to True, as we've done all the optimisations we can }
  9826. end;
  9827. end;
  9828. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  9829. var
  9830. hp1,hp3 : tai;
  9831. {$ifndef x86_64}
  9832. hp2 : taicpu;
  9833. {$endif x86_64}
  9834. begin
  9835. Result:=false;
  9836. hp3:=nil;
  9837. {$ifndef x86_64}
  9838. { don't do this on modern CPUs, this really hurts them due to
  9839. broken call/ret pairing }
  9840. if (current_settings.optimizecputype < cpu_Pentium2) and
  9841. not(cs_create_pic in current_settings.moduleswitches) and
  9842. GetNextInstruction(p, hp1) and
  9843. MatchInstruction(hp1,A_JMP,[S_NO]) and
  9844. MatchOpType(taicpu(hp1),top_ref) and
  9845. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9846. begin
  9847. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  9848. InsertLLItem(p.previous, p, hp2);
  9849. taicpu(p).opcode := A_JMP;
  9850. taicpu(p).is_jmp := true;
  9851. RemoveInstruction(hp1);
  9852. Result:=true;
  9853. end
  9854. else
  9855. {$endif x86_64}
  9856. { replace
  9857. call procname
  9858. ret
  9859. by
  9860. jmp procname
  9861. but do it only on level 4 because it destroys stack back traces
  9862. else if the subroutine is marked as no return, remove the ret
  9863. }
  9864. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  9865. (po_noreturn in current_procinfo.procdef.procoptions)) and
  9866. GetNextInstruction(p, hp1) and
  9867. (MatchInstruction(hp1,A_RET,[S_NO]) or
  9868. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  9869. SetAndTest(hp1,hp3) and
  9870. GetNextInstruction(hp1,hp1) and
  9871. MatchInstruction(hp1,A_RET,[S_NO])
  9872. )
  9873. ) and
  9874. (taicpu(hp1).ops=0) then
  9875. begin
  9876. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9877. { we might destroy stack alignment here if we do not do a call }
  9878. (target_info.stackalign<=sizeof(SizeUInt)) then
  9879. begin
  9880. taicpu(p).opcode := A_JMP;
  9881. taicpu(p).is_jmp := true;
  9882. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  9883. end
  9884. else
  9885. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  9886. RemoveInstruction(hp1);
  9887. if Assigned(hp3) then
  9888. begin
  9889. AsmL.Remove(hp3);
  9890. AsmL.InsertBefore(hp3,p)
  9891. end;
  9892. Result:=true;
  9893. end;
  9894. end;
  9895. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  9896. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  9897. begin
  9898. case OpSize of
  9899. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9900. Result := (Val <= $FF) and (Val >= -128);
  9901. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9902. Result := (Val <= $FFFF) and (Val >= -32768);
  9903. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  9904. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  9905. else
  9906. Result := True;
  9907. end;
  9908. end;
  9909. var
  9910. hp1, hp2 : tai;
  9911. SizeChange: Boolean;
  9912. PreMessage: string;
  9913. begin
  9914. Result := False;
  9915. if (taicpu(p).oper[0]^.typ = top_reg) and
  9916. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9917. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  9918. begin
  9919. { Change (using movzbl %al,%eax as an example):
  9920. movzbl %al, %eax movzbl %al, %eax
  9921. cmpl x, %eax testl %eax,%eax
  9922. To:
  9923. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  9924. movzbl %al, %eax movzbl %al, %eax
  9925. Smaller instruction and minimises pipeline stall as the CPU
  9926. doesn't have to wait for the register to get zero-extended. [Kit]
  9927. Also allow if the smaller of the two registers is being checked,
  9928. as this still removes the false dependency.
  9929. }
  9930. if
  9931. (
  9932. (
  9933. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  9934. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  9935. ) or (
  9936. { If MatchOperand returns True, they must both be registers }
  9937. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  9938. )
  9939. ) and
  9940. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  9941. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  9942. begin
  9943. 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);
  9944. asml.Remove(hp1);
  9945. asml.InsertBefore(hp1, p);
  9946. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  9947. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  9948. begin
  9949. taicpu(hp1).opcode := A_TEST;
  9950. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  9951. end;
  9952. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9953. case taicpu(p).opsize of
  9954. S_BW, S_BL:
  9955. begin
  9956. SizeChange := taicpu(hp1).opsize <> S_B;
  9957. taicpu(hp1).changeopsize(S_B);
  9958. end;
  9959. S_WL:
  9960. begin
  9961. SizeChange := taicpu(hp1).opsize <> S_W;
  9962. taicpu(hp1).changeopsize(S_W);
  9963. end
  9964. else
  9965. InternalError(2020112701);
  9966. end;
  9967. UpdateUsedRegs(tai(p.Next));
  9968. { Check if the register is used aferwards - if not, we can
  9969. remove the movzx instruction completely }
  9970. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9971. begin
  9972. { Hp1 is a better position than p for debugging purposes }
  9973. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  9974. RemoveCurrentp(p, hp1);
  9975. Result := True;
  9976. end;
  9977. if SizeChange then
  9978. DebugMsg(SPeepholeOptimization + PreMessage +
  9979. 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)
  9980. else
  9981. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  9982. Exit;
  9983. end;
  9984. { Change (using movzwl %ax,%eax as an example):
  9985. movzwl %ax, %eax
  9986. movb %al, (dest) (Register is smaller than read register in movz)
  9987. To:
  9988. movb %al, (dest) (Move one back to avoid a false dependency)
  9989. movzwl %ax, %eax
  9990. }
  9991. if (taicpu(hp1).opcode = A_MOV) and
  9992. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9993. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  9994. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  9995. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  9996. begin
  9997. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  9998. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  9999. asml.Remove(hp1);
  10000. asml.InsertBefore(hp1, p);
  10001. if taicpu(hp1).oper[1]^.typ = top_reg then
  10002. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  10003. { Check if the register is used aferwards - if not, we can
  10004. remove the movzx instruction completely }
  10005. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  10006. begin
  10007. { Hp1 is a better position than p for debugging purposes }
  10008. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  10009. RemoveCurrentp(p, hp1);
  10010. Result := True;
  10011. end;
  10012. Exit;
  10013. end;
  10014. end;
  10015. end;
  10016. {$ifdef x86_64}
  10017. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  10018. var
  10019. PreMessage, RegName: string;
  10020. begin
  10021. { Code size reduction by J. Gareth "Kit" Moreton }
  10022. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  10023. as this removes the REX prefix }
  10024. Result := False;
  10025. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  10026. Exit;
  10027. if taicpu(p).oper[0]^.typ <> top_reg then
  10028. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  10029. InternalError(2018011500);
  10030. case taicpu(p).opsize of
  10031. S_Q:
  10032. begin
  10033. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  10034. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  10035. { The actual optimization }
  10036. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10037. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10038. taicpu(p).changeopsize(S_L);
  10039. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  10040. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  10041. end;
  10042. else
  10043. ;
  10044. end;
  10045. end;
  10046. {$endif}
  10047. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  10048. var
  10049. XReg: TRegister;
  10050. begin
  10051. Result := False;
  10052. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  10053. Smaller encoding and slightly faster on some platforms (also works for
  10054. ZMM-sized registers) }
  10055. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  10056. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  10057. begin
  10058. XReg := taicpu(p).oper[0]^.reg;
  10059. if (taicpu(p).oper[1]^.reg = XReg) then
  10060. begin
  10061. taicpu(p).changeopsize(S_XMM);
  10062. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  10063. if (cs_opt_size in current_settings.optimizerswitches) then
  10064. begin
  10065. { Change input registers to %xmm0 to reduce size. Note that
  10066. there's a risk of a false dependency doing this, so only
  10067. optimise for size here }
  10068. XReg := NR_XMM0;
  10069. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  10070. end
  10071. else
  10072. begin
  10073. setsubreg(XReg, R_SUBMMX);
  10074. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  10075. end;
  10076. taicpu(p).oper[0]^.reg := XReg;
  10077. taicpu(p).oper[1]^.reg := XReg;
  10078. Result := True;
  10079. end;
  10080. end;
  10081. end;
  10082. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  10083. var
  10084. OperIdx: Integer;
  10085. begin
  10086. for OperIdx := 0 to p.ops - 1 do
  10087. if p.oper[OperIdx]^.typ = top_ref then
  10088. optimize_ref(p.oper[OperIdx]^.ref^, False);
  10089. end;
  10090. end.