aoptx86.pas 558 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074
  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 DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  108. function PrePeepholeOptSxx(var p : tai) : boolean;
  109. function PrePeepholeOptIMUL(var p : tai) : boolean;
  110. function PrePeepholeOptAND(var p : tai) : boolean;
  111. function OptPass1Test(var p: tai): boolean;
  112. function OptPass1Add(var p: tai): boolean;
  113. function OptPass1AND(var p : tai) : boolean;
  114. function OptPass1_V_MOVAP(var p : tai) : boolean;
  115. function OptPass1VOP(var p : tai) : boolean;
  116. function OptPass1MOV(var p : tai) : boolean;
  117. function OptPass1Movx(var p : tai) : boolean;
  118. function OptPass1MOVXX(var p : tai) : boolean;
  119. function OptPass1OP(var p : tai) : boolean;
  120. function OptPass1LEA(var p : tai) : boolean;
  121. function OptPass1Sub(var p : tai) : boolean;
  122. function OptPass1SHLSAL(var p : tai) : boolean;
  123. function OptPass1FSTP(var p : tai) : boolean;
  124. function OptPass1FLD(var p : tai) : boolean;
  125. function OptPass1Cmp(var p : tai) : boolean;
  126. function OptPass1PXor(var p : tai) : boolean;
  127. function OptPass1VPXor(var p: tai): boolean;
  128. function OptPass1Imul(var p : tai) : boolean;
  129. function OptPass1Jcc(var p : tai) : boolean;
  130. function OptPass1SHXX(var p: tai): boolean;
  131. function OptPass1VMOVDQ(var p: tai): Boolean;
  132. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  133. function OptPass2Movx(var p : tai): Boolean;
  134. function OptPass2MOV(var p : tai) : boolean;
  135. function OptPass2Imul(var p : tai) : boolean;
  136. function OptPass2Jmp(var p : tai) : boolean;
  137. function OptPass2Jcc(var p : tai) : boolean;
  138. function OptPass2Lea(var p: tai): Boolean;
  139. function OptPass2SUB(var p: tai): Boolean;
  140. function OptPass2ADD(var p : tai): Boolean;
  141. function OptPass2SETcc(var p : tai) : boolean;
  142. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  143. function PostPeepholeOptMov(var p : tai) : Boolean;
  144. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  145. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  146. function PostPeepholeOptXor(var p : tai) : Boolean;
  147. {$endif x86_64}
  148. function PostPeepholeOptAnd(var p : tai) : boolean;
  149. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  150. function PostPeepholeOptCmp(var p : tai) : Boolean;
  151. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  152. function PostPeepholeOptCall(var p : tai) : Boolean;
  153. function PostPeepholeOptLea(var p : tai) : Boolean;
  154. function PostPeepholeOptPush(var p: tai): Boolean;
  155. function PostPeepholeOptShr(var p : tai) : boolean;
  156. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  157. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  158. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  159. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  160. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  161. { Processor-dependent reference optimisation }
  162. class procedure OptimizeRefs(var p: taicpu); static;
  163. end;
  164. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  168. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  169. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  170. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  171. {$if max_operands>2}
  172. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  173. {$endif max_operands>2}
  174. function RefsEqual(const r1, r2: treference): boolean;
  175. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  176. { returns true, if ref is a reference using only the registers passed as base and index
  177. and having an offset }
  178. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  179. implementation
  180. uses
  181. cutils,verbose,
  182. systems,
  183. globals,
  184. cpuinfo,
  185. procinfo,
  186. paramgr,
  187. aasmbase,
  188. aoptbase,aoptutils,
  189. symconst,symsym,
  190. cgx86,
  191. itcpugas;
  192. {$ifdef DEBUG_AOPTCPU}
  193. const
  194. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  195. {$else DEBUG_AOPTCPU}
  196. { Empty strings help the optimizer to remove string concatenations that won't
  197. ever appear to the user on release builds. [Kit] }
  198. const
  199. SPeepholeOptimization = '';
  200. {$endif DEBUG_AOPTCPU}
  201. LIST_STEP_SIZE = 4;
  202. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  203. begin
  204. result :=
  205. (instr.typ = ait_instruction) and
  206. (taicpu(instr).opcode = op) and
  207. ((opsize = []) or (taicpu(instr).opsize in opsize));
  208. end;
  209. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  210. begin
  211. result :=
  212. (instr.typ = ait_instruction) and
  213. ((taicpu(instr).opcode = op1) or
  214. (taicpu(instr).opcode = op2)
  215. ) and
  216. ((opsize = []) or (taicpu(instr).opsize in opsize));
  217. end;
  218. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  219. begin
  220. result :=
  221. (instr.typ = ait_instruction) and
  222. ((taicpu(instr).opcode = op1) or
  223. (taicpu(instr).opcode = op2) or
  224. (taicpu(instr).opcode = op3)
  225. ) and
  226. ((opsize = []) or (taicpu(instr).opsize in opsize));
  227. end;
  228. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  229. const opsize : topsizes) : boolean;
  230. var
  231. op : TAsmOp;
  232. begin
  233. result:=false;
  234. if (instr.typ <> ait_instruction) or
  235. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  236. exit;
  237. for op in ops do
  238. begin
  239. if taicpu(instr).opcode = op then
  240. begin
  241. result:=true;
  242. exit;
  243. end;
  244. end;
  245. end;
  246. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  247. begin
  248. result := (oper.typ = top_reg) and (oper.reg = reg);
  249. end;
  250. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  251. begin
  252. result := (oper.typ = top_const) and (oper.val = a);
  253. end;
  254. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  255. begin
  256. result := oper1.typ = oper2.typ;
  257. if result then
  258. case oper1.typ of
  259. top_const:
  260. Result:=oper1.val = oper2.val;
  261. top_reg:
  262. Result:=oper1.reg = oper2.reg;
  263. top_ref:
  264. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  265. else
  266. internalerror(2013102801);
  267. end
  268. end;
  269. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  270. begin
  271. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  272. if result then
  273. case oper1.typ of
  274. top_const:
  275. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  276. top_reg:
  277. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  278. top_ref:
  279. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  280. else
  281. internalerror(2020052401);
  282. end
  283. end;
  284. function RefsEqual(const r1, r2: treference): boolean;
  285. begin
  286. RefsEqual :=
  287. (r1.offset = r2.offset) and
  288. (r1.segment = r2.segment) and (r1.base = r2.base) and
  289. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  290. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  291. (r1.relsymbol = r2.relsymbol) and
  292. (r1.volatility=[]) and
  293. (r2.volatility=[]);
  294. end;
  295. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  296. begin
  297. Result:=(ref.offset=0) and
  298. (ref.scalefactor in [0,1]) and
  299. (ref.segment=NR_NO) and
  300. (ref.symbol=nil) and
  301. (ref.relsymbol=nil) and
  302. ((base=NR_INVALID) or
  303. (ref.base=base)) and
  304. ((index=NR_INVALID) or
  305. (ref.index=index)) and
  306. (ref.volatility=[]);
  307. end;
  308. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  309. begin
  310. Result:=(ref.scalefactor in [0,1]) and
  311. (ref.segment=NR_NO) and
  312. (ref.symbol=nil) and
  313. (ref.relsymbol=nil) and
  314. ((base=NR_INVALID) or
  315. (ref.base=base)) and
  316. ((index=NR_INVALID) or
  317. (ref.index=index)) and
  318. (ref.volatility=[]);
  319. end;
  320. function InstrReadsFlags(p: tai): boolean;
  321. begin
  322. InstrReadsFlags := true;
  323. case p.typ of
  324. ait_instruction:
  325. if InsProp[taicpu(p).opcode].Ch*
  326. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  327. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  328. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  329. exit;
  330. ait_label:
  331. exit;
  332. else
  333. ;
  334. end;
  335. InstrReadsFlags := false;
  336. end;
  337. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  338. begin
  339. Next:=Current;
  340. repeat
  341. Result:=GetNextInstruction(Next,Next);
  342. until not (Result) or
  343. not(cs_opt_level3 in current_settings.optimizerswitches) or
  344. (Next.typ<>ait_instruction) or
  345. RegInInstruction(reg,Next) or
  346. is_calljmp(taicpu(Next).opcode);
  347. end;
  348. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  349. begin
  350. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  351. Next := Current;
  352. repeat
  353. Result := GetNextInstruction(Next,Next);
  354. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  355. if is_calljmpuncondret(taicpu(Next).opcode) then
  356. begin
  357. Result := False;
  358. Exit;
  359. end
  360. else
  361. CrossJump := True;
  362. until not Result or
  363. not (cs_opt_level3 in current_settings.optimizerswitches) or
  364. (Next.typ <> ait_instruction) or
  365. RegInInstruction(reg,Next);
  366. end;
  367. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  368. begin
  369. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  370. begin
  371. Result:=GetNextInstruction(Current,Next);
  372. exit;
  373. end;
  374. Next:=tai(Current.Next);
  375. Result:=false;
  376. while assigned(Next) do
  377. begin
  378. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  379. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  380. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  381. exit
  382. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  383. begin
  384. Result:=true;
  385. exit;
  386. end;
  387. Next:=tai(Next.Next);
  388. end;
  389. end;
  390. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  391. begin
  392. Result:=RegReadByInstruction(reg,hp);
  393. end;
  394. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  395. var
  396. p: taicpu;
  397. opcount: longint;
  398. begin
  399. RegReadByInstruction := false;
  400. if hp.typ <> ait_instruction then
  401. exit;
  402. p := taicpu(hp);
  403. case p.opcode of
  404. A_CALL:
  405. regreadbyinstruction := true;
  406. A_IMUL:
  407. case p.ops of
  408. 1:
  409. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  410. (
  411. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  412. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  413. );
  414. 2,3:
  415. regReadByInstruction :=
  416. reginop(reg,p.oper[0]^) or
  417. reginop(reg,p.oper[1]^);
  418. else
  419. InternalError(2019112801);
  420. end;
  421. A_MUL:
  422. begin
  423. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  424. (
  425. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  426. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  427. );
  428. end;
  429. A_IDIV,A_DIV:
  430. begin
  431. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  432. (
  433. (getregtype(reg)=R_INTREGISTER) and
  434. (
  435. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  436. )
  437. );
  438. end;
  439. else
  440. begin
  441. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  442. begin
  443. RegReadByInstruction := false;
  444. exit;
  445. end;
  446. for opcount := 0 to p.ops-1 do
  447. if (p.oper[opCount]^.typ = top_ref) and
  448. RegInRef(reg,p.oper[opcount]^.ref^) then
  449. begin
  450. RegReadByInstruction := true;
  451. exit
  452. end;
  453. { special handling for SSE MOVSD }
  454. if (p.opcode=A_MOVSD) and (p.ops>0) then
  455. begin
  456. if p.ops<>2 then
  457. internalerror(2017042702);
  458. regReadByInstruction := reginop(reg,p.oper[0]^) or
  459. (
  460. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  461. );
  462. exit;
  463. end;
  464. with insprop[p.opcode] do
  465. begin
  466. case getregtype(reg) of
  467. R_INTREGISTER:
  468. begin
  469. case getsupreg(reg) of
  470. RS_EAX:
  471. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  472. begin
  473. RegReadByInstruction := true;
  474. exit
  475. end;
  476. RS_ECX:
  477. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  478. begin
  479. RegReadByInstruction := true;
  480. exit
  481. end;
  482. RS_EDX:
  483. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  484. begin
  485. RegReadByInstruction := true;
  486. exit
  487. end;
  488. RS_EBX:
  489. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  490. begin
  491. RegReadByInstruction := true;
  492. exit
  493. end;
  494. RS_ESP:
  495. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  496. begin
  497. RegReadByInstruction := true;
  498. exit
  499. end;
  500. RS_EBP:
  501. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  502. begin
  503. RegReadByInstruction := true;
  504. exit
  505. end;
  506. RS_ESI:
  507. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  508. begin
  509. RegReadByInstruction := true;
  510. exit
  511. end;
  512. RS_EDI:
  513. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  514. begin
  515. RegReadByInstruction := true;
  516. exit
  517. end;
  518. end;
  519. end;
  520. R_MMREGISTER:
  521. begin
  522. case getsupreg(reg) of
  523. RS_XMM0:
  524. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  525. begin
  526. RegReadByInstruction := true;
  527. exit
  528. end;
  529. end;
  530. end;
  531. else
  532. ;
  533. end;
  534. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  535. begin
  536. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  537. begin
  538. case p.condition of
  539. C_A,C_NBE, { CF=0 and ZF=0 }
  540. C_BE,C_NA: { CF=1 or ZF=1 }
  541. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  542. C_AE,C_NB,C_NC, { CF=0 }
  543. C_B,C_NAE,C_C: { CF=1 }
  544. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  545. C_NE,C_NZ, { ZF=0 }
  546. C_E,C_Z: { ZF=1 }
  547. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  548. C_G,C_NLE, { ZF=0 and SF=OF }
  549. C_LE,C_NG: { ZF=1 or SF<>OF }
  550. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  551. C_GE,C_NL, { SF=OF }
  552. C_L,C_NGE: { SF<>OF }
  553. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  554. C_NO, { OF=0 }
  555. C_O: { OF=1 }
  556. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  557. C_NP,C_PO, { PF=0 }
  558. C_P,C_PE: { PF=1 }
  559. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  560. C_NS, { SF=0 }
  561. C_S: { SF=1 }
  562. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  563. else
  564. internalerror(2017042701);
  565. end;
  566. if RegReadByInstruction then
  567. exit;
  568. end;
  569. case getsubreg(reg) of
  570. R_SUBW,R_SUBD,R_SUBQ:
  571. RegReadByInstruction :=
  572. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  573. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  574. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  575. R_SUBFLAGCARRY:
  576. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  577. R_SUBFLAGPARITY:
  578. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  579. R_SUBFLAGAUXILIARY:
  580. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  581. R_SUBFLAGZERO:
  582. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  583. R_SUBFLAGSIGN:
  584. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  585. R_SUBFLAGOVERFLOW:
  586. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  587. R_SUBFLAGINTERRUPT:
  588. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  589. R_SUBFLAGDIRECTION:
  590. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  591. else
  592. internalerror(2017042601);
  593. end;
  594. exit;
  595. end;
  596. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  597. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  598. (p.oper[0]^.reg=p.oper[1]^.reg) then
  599. exit;
  600. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  601. begin
  602. RegReadByInstruction := true;
  603. exit
  604. end;
  605. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  606. begin
  607. RegReadByInstruction := true;
  608. exit
  609. end;
  610. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  611. begin
  612. RegReadByInstruction := true;
  613. exit
  614. end;
  615. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  616. begin
  617. RegReadByInstruction := true;
  618. exit
  619. end;
  620. end;
  621. end;
  622. end;
  623. end;
  624. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  625. begin
  626. result:=false;
  627. if p1.typ<>ait_instruction then
  628. exit;
  629. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  630. exit(true);
  631. if (getregtype(reg)=R_INTREGISTER) and
  632. { change information for xmm movsd are not correct }
  633. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  634. begin
  635. case getsupreg(reg) of
  636. { RS_EAX = RS_RAX on x86-64 }
  637. RS_EAX:
  638. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. RS_ECX:
  640. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. RS_EDX:
  642. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. RS_EBX:
  644. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. RS_ESP:
  646. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. RS_EBP:
  648. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  649. RS_ESI:
  650. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  651. RS_EDI:
  652. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  653. else
  654. ;
  655. end;
  656. if result then
  657. exit;
  658. end
  659. else if getregtype(reg)=R_MMREGISTER then
  660. begin
  661. case getsupreg(reg) of
  662. RS_XMM0:
  663. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  664. else
  665. ;
  666. end;
  667. if result then
  668. exit;
  669. end
  670. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  671. begin
  672. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  673. exit(true);
  674. case getsubreg(reg) of
  675. R_SUBFLAGCARRY:
  676. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  677. R_SUBFLAGPARITY:
  678. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  679. R_SUBFLAGAUXILIARY:
  680. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  681. R_SUBFLAGZERO:
  682. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. R_SUBFLAGSIGN:
  684. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  685. R_SUBFLAGOVERFLOW:
  686. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  687. R_SUBFLAGINTERRUPT:
  688. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  689. R_SUBFLAGDIRECTION:
  690. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  691. R_SUBW,R_SUBD,R_SUBQ:
  692. { Everything except the direction bits }
  693. Result:=
  694. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  695. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  696. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  697. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  698. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  699. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  700. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  701. else
  702. ;
  703. end;
  704. if result then
  705. exit;
  706. end
  707. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  708. exit(true);
  709. Result:=inherited RegInInstruction(Reg, p1);
  710. end;
  711. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  712. const
  713. WriteOps: array[0..3] of set of TInsChange =
  714. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  715. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  716. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  717. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  718. var
  719. OperIdx: Integer;
  720. begin
  721. Result := False;
  722. if p1.typ <> ait_instruction then
  723. exit;
  724. with insprop[taicpu(p1).opcode] do
  725. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  726. begin
  727. case getsubreg(reg) of
  728. R_SUBW,R_SUBD,R_SUBQ:
  729. Result :=
  730. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  731. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  732. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  733. R_SUBFLAGCARRY:
  734. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  735. R_SUBFLAGPARITY:
  736. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  737. R_SUBFLAGAUXILIARY:
  738. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  739. R_SUBFLAGZERO:
  740. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  741. R_SUBFLAGSIGN:
  742. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  743. R_SUBFLAGOVERFLOW:
  744. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  745. R_SUBFLAGINTERRUPT:
  746. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  747. R_SUBFLAGDIRECTION:
  748. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  749. else
  750. internalerror(2017042602);
  751. end;
  752. exit;
  753. end;
  754. case taicpu(p1).opcode of
  755. A_CALL:
  756. { We could potentially set Result to False if the register in
  757. question is non-volatile for the subroutine's calling convention,
  758. but this would require detecting the calling convention in use and
  759. also assuming that the routine doesn't contain malformed assembly
  760. language, for example... so it could only be done under -O4 as it
  761. would be considered a side-effect. [Kit] }
  762. Result := True;
  763. A_MOVSD:
  764. { special handling for SSE MOVSD }
  765. if (taicpu(p1).ops>0) then
  766. begin
  767. if taicpu(p1).ops<>2 then
  768. internalerror(2017042703);
  769. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  770. end;
  771. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  772. so fix it here (FK)
  773. }
  774. A_VMOVSS,
  775. A_VMOVSD:
  776. begin
  777. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  778. exit;
  779. end;
  780. A_IMUL:
  781. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  782. else
  783. ;
  784. end;
  785. if Result then
  786. exit;
  787. with insprop[taicpu(p1).opcode] do
  788. begin
  789. if getregtype(reg)=R_INTREGISTER then
  790. begin
  791. case getsupreg(reg) of
  792. RS_EAX:
  793. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  794. begin
  795. Result := True;
  796. exit
  797. end;
  798. RS_ECX:
  799. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  800. begin
  801. Result := True;
  802. exit
  803. end;
  804. RS_EDX:
  805. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  806. begin
  807. Result := True;
  808. exit
  809. end;
  810. RS_EBX:
  811. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  812. begin
  813. Result := True;
  814. exit
  815. end;
  816. RS_ESP:
  817. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  818. begin
  819. Result := True;
  820. exit
  821. end;
  822. RS_EBP:
  823. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  824. begin
  825. Result := True;
  826. exit
  827. end;
  828. RS_ESI:
  829. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  830. begin
  831. Result := True;
  832. exit
  833. end;
  834. RS_EDI:
  835. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  836. begin
  837. Result := True;
  838. exit
  839. end;
  840. end;
  841. end;
  842. for OperIdx := 0 to taicpu(p1).ops - 1 do
  843. if (WriteOps[OperIdx]*Ch<>[]) and
  844. { The register doesn't get modified inside a reference }
  845. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  846. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  847. begin
  848. Result := true;
  849. exit
  850. end;
  851. end;
  852. end;
  853. {$ifdef DEBUG_AOPTCPU}
  854. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  855. begin
  856. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  857. end;
  858. function debug_tostr(i: tcgint): string; inline;
  859. begin
  860. Result := tostr(i);
  861. end;
  862. function debug_regname(r: TRegister): string; inline;
  863. begin
  864. Result := '%' + std_regname(r);
  865. end;
  866. { Debug output function - creates a string representation of an operator }
  867. function debug_operstr(oper: TOper): string;
  868. begin
  869. case oper.typ of
  870. top_const:
  871. Result := '$' + debug_tostr(oper.val);
  872. top_reg:
  873. Result := debug_regname(oper.reg);
  874. top_ref:
  875. begin
  876. if oper.ref^.offset <> 0 then
  877. Result := debug_tostr(oper.ref^.offset) + '('
  878. else
  879. Result := '(';
  880. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  881. begin
  882. Result := Result + debug_regname(oper.ref^.base);
  883. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  884. Result := Result + ',' + debug_regname(oper.ref^.index);
  885. end
  886. else
  887. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  888. Result := Result + debug_regname(oper.ref^.index);
  889. if (oper.ref^.scalefactor > 1) then
  890. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  891. else
  892. Result := Result + ')';
  893. end;
  894. else
  895. Result := '[UNKNOWN]';
  896. end;
  897. end;
  898. function debug_op2str(opcode: tasmop): string; inline;
  899. begin
  900. Result := std_op2str[opcode];
  901. end;
  902. function debug_opsize2str(opsize: topsize): string; inline;
  903. begin
  904. Result := gas_opsize2str[opsize];
  905. end;
  906. {$else DEBUG_AOPTCPU}
  907. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  908. begin
  909. end;
  910. function debug_tostr(i: tcgint): string; inline;
  911. begin
  912. Result := '';
  913. end;
  914. function debug_regname(r: TRegister): string; inline;
  915. begin
  916. Result := '';
  917. end;
  918. function debug_operstr(oper: TOper): string; inline;
  919. begin
  920. Result := '';
  921. end;
  922. function debug_op2str(opcode: tasmop): string; inline;
  923. begin
  924. Result := '';
  925. end;
  926. function debug_opsize2str(opsize: topsize): string; inline;
  927. begin
  928. Result := '';
  929. end;
  930. {$endif DEBUG_AOPTCPU}
  931. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  932. begin
  933. {$ifdef x86_64}
  934. { Always fine on x86-64 }
  935. Result := True;
  936. {$else x86_64}
  937. Result :=
  938. {$ifdef i8086}
  939. (current_settings.cputype >= cpu_386) and
  940. {$endif i8086}
  941. (
  942. { Always accept if optimising for size }
  943. (cs_opt_size in current_settings.optimizerswitches) or
  944. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  945. (current_settings.optimizecputype >= cpu_Pentium2)
  946. );
  947. {$endif x86_64}
  948. end;
  949. { Attempts to allocate a volatile integer register for use between p and hp,
  950. using AUsedRegs for the current register usage information. Returns NR_NO
  951. if no free register could be found }
  952. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  953. var
  954. RegSet: TCPURegisterSet;
  955. CurrentSuperReg: Integer;
  956. CurrentReg: TRegister;
  957. Currentp: tai;
  958. Breakout: Boolean;
  959. begin
  960. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  961. Result := NR_NO;
  962. RegSet :=
  963. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  964. current_procinfo.saved_regs_int;
  965. for CurrentSuperReg in RegSet do
  966. begin
  967. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  968. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  969. {$if defined(i386) or defined(i8086)}
  970. { If the target size is 8-bit, make sure we can actually encode it }
  971. and (
  972. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  973. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  974. )
  975. {$endif i386 or i8086}
  976. then
  977. begin
  978. Currentp := p;
  979. Breakout := False;
  980. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  981. begin
  982. case Currentp.typ of
  983. ait_instruction:
  984. begin
  985. if RegInInstruction(CurrentReg, Currentp) then
  986. begin
  987. Breakout := True;
  988. Break;
  989. end;
  990. { Cannot allocate across an unconditional jump }
  991. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  992. Exit;
  993. end;
  994. ait_marker:
  995. { Don't try anything more if a marker is hit }
  996. Exit;
  997. ait_regalloc:
  998. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  999. begin
  1000. Breakout := True;
  1001. Break;
  1002. end;
  1003. else
  1004. ;
  1005. end;
  1006. end;
  1007. if Breakout then
  1008. { Try the next register }
  1009. Continue;
  1010. { We have a free register available }
  1011. Result := CurrentReg;
  1012. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1013. Exit;
  1014. end;
  1015. end;
  1016. end;
  1017. { Attempts to allocate a volatile MM register for use between p and hp,
  1018. using AUsedRegs for the current register usage information. Returns NR_NO
  1019. if no free register could be found }
  1020. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1021. var
  1022. RegSet: TCPURegisterSet;
  1023. CurrentSuperReg: Integer;
  1024. CurrentReg: TRegister;
  1025. Currentp: tai;
  1026. Breakout: Boolean;
  1027. begin
  1028. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1029. Result := NR_NO;
  1030. RegSet :=
  1031. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1032. current_procinfo.saved_regs_mm;
  1033. for CurrentSuperReg in RegSet do
  1034. begin
  1035. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1036. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1037. begin
  1038. Currentp := p;
  1039. Breakout := False;
  1040. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1041. begin
  1042. case Currentp.typ of
  1043. ait_instruction:
  1044. begin
  1045. if RegInInstruction(CurrentReg, Currentp) then
  1046. begin
  1047. Breakout := True;
  1048. Break;
  1049. end;
  1050. { Cannot allocate across an unconditional jump }
  1051. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1052. Exit;
  1053. end;
  1054. ait_marker:
  1055. { Don't try anything more if a marker is hit }
  1056. Exit;
  1057. ait_regalloc:
  1058. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1059. begin
  1060. Breakout := True;
  1061. Break;
  1062. end;
  1063. else
  1064. ;
  1065. end;
  1066. end;
  1067. if Breakout then
  1068. { Try the next register }
  1069. Continue;
  1070. { We have a free register available }
  1071. Result := CurrentReg;
  1072. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1073. Exit;
  1074. end;
  1075. end;
  1076. end;
  1077. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1078. begin
  1079. if not SuperRegistersEqual(reg1,reg2) then
  1080. exit(false);
  1081. if getregtype(reg1)<>R_INTREGISTER then
  1082. exit(true); {because SuperRegisterEqual is true}
  1083. case getsubreg(reg1) of
  1084. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1085. higher, it preserves the high bits, so the new value depends on
  1086. reg2's previous value. In other words, it is equivalent to doing:
  1087. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1088. R_SUBL:
  1089. exit(getsubreg(reg2)=R_SUBL);
  1090. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1091. higher, it actually does a:
  1092. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1093. R_SUBH:
  1094. exit(getsubreg(reg2)=R_SUBH);
  1095. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1096. bits of reg2:
  1097. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1098. R_SUBW:
  1099. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1100. { a write to R_SUBD always overwrites every other subregister,
  1101. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1102. R_SUBD,
  1103. R_SUBQ:
  1104. exit(true);
  1105. else
  1106. internalerror(2017042801);
  1107. end;
  1108. end;
  1109. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1110. begin
  1111. if not SuperRegistersEqual(reg1,reg2) then
  1112. exit(false);
  1113. if getregtype(reg1)<>R_INTREGISTER then
  1114. exit(true); {because SuperRegisterEqual is true}
  1115. case getsubreg(reg1) of
  1116. R_SUBL:
  1117. exit(getsubreg(reg2)<>R_SUBH);
  1118. R_SUBH:
  1119. exit(getsubreg(reg2)<>R_SUBL);
  1120. R_SUBW,
  1121. R_SUBD,
  1122. R_SUBQ:
  1123. exit(true);
  1124. else
  1125. internalerror(2017042802);
  1126. end;
  1127. end;
  1128. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1129. var
  1130. hp1 : tai;
  1131. l : TCGInt;
  1132. begin
  1133. result:=false;
  1134. { changes the code sequence
  1135. shr/sar const1, x
  1136. shl const2, x
  1137. to
  1138. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1139. if GetNextInstruction(p, hp1) and
  1140. MatchInstruction(hp1,A_SHL,[]) and
  1141. (taicpu(p).oper[0]^.typ = top_const) and
  1142. (taicpu(hp1).oper[0]^.typ = top_const) and
  1143. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1144. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1145. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1146. begin
  1147. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1148. not(cs_opt_size in current_settings.optimizerswitches) then
  1149. begin
  1150. { shr/sar const1, %reg
  1151. shl const2, %reg
  1152. with const1 > const2 }
  1153. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1154. taicpu(hp1).opcode := A_AND;
  1155. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1156. case taicpu(p).opsize Of
  1157. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1158. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1159. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1160. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1161. else
  1162. Internalerror(2017050703)
  1163. end;
  1164. end
  1165. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1166. not(cs_opt_size in current_settings.optimizerswitches) then
  1167. begin
  1168. { shr/sar const1, %reg
  1169. shl const2, %reg
  1170. with const1 < const2 }
  1171. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1172. taicpu(p).opcode := A_AND;
  1173. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1174. case taicpu(p).opsize Of
  1175. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1176. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1177. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1178. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1179. else
  1180. Internalerror(2017050702)
  1181. end;
  1182. end
  1183. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1184. begin
  1185. { shr/sar const1, %reg
  1186. shl const2, %reg
  1187. with const1 = const2 }
  1188. taicpu(p).opcode := A_AND;
  1189. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1190. case taicpu(p).opsize Of
  1191. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1192. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1193. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1194. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1195. else
  1196. Internalerror(2017050701)
  1197. end;
  1198. RemoveInstruction(hp1);
  1199. end;
  1200. end;
  1201. end;
  1202. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1203. var
  1204. opsize : topsize;
  1205. hp1 : tai;
  1206. tmpref : treference;
  1207. ShiftValue : Cardinal;
  1208. BaseValue : TCGInt;
  1209. begin
  1210. result:=false;
  1211. opsize:=taicpu(p).opsize;
  1212. { changes certain "imul const, %reg"'s to lea sequences }
  1213. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1214. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1215. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1216. if (taicpu(p).oper[0]^.val = 1) then
  1217. if (taicpu(p).ops = 2) then
  1218. { remove "imul $1, reg" }
  1219. begin
  1220. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1221. Result := RemoveCurrentP(p);
  1222. end
  1223. else
  1224. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1225. begin
  1226. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1227. InsertLLItem(p.previous, p.next, hp1);
  1228. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1229. p.free;
  1230. p := hp1;
  1231. end
  1232. else if ((taicpu(p).ops <= 2) or
  1233. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1234. not(cs_opt_size in current_settings.optimizerswitches) and
  1235. (not(GetNextInstruction(p, hp1)) or
  1236. not((tai(hp1).typ = ait_instruction) and
  1237. ((taicpu(hp1).opcode=A_Jcc) and
  1238. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1239. begin
  1240. {
  1241. imul X, reg1, reg2 to
  1242. lea (reg1,reg1,Y), reg2
  1243. shl ZZ,reg2
  1244. imul XX, reg1 to
  1245. lea (reg1,reg1,YY), reg1
  1246. shl ZZ,reg2
  1247. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1248. it does not exist as a separate optimization target in FPC though.
  1249. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1250. at most two zeros
  1251. }
  1252. reference_reset(tmpref,1,[]);
  1253. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1254. begin
  1255. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1256. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1257. TmpRef.base := taicpu(p).oper[1]^.reg;
  1258. TmpRef.index := taicpu(p).oper[1]^.reg;
  1259. if not(BaseValue in [3,5,9]) then
  1260. Internalerror(2018110101);
  1261. TmpRef.ScaleFactor := BaseValue-1;
  1262. if (taicpu(p).ops = 2) then
  1263. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1264. else
  1265. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1266. AsmL.InsertAfter(hp1,p);
  1267. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1268. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1269. RemoveCurrentP(p, hp1);
  1270. if ShiftValue>0 then
  1271. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1272. end;
  1273. end;
  1274. end;
  1275. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1276. begin
  1277. Result := False;
  1278. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1279. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1280. begin
  1281. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1282. taicpu(p).opcode := A_MOV;
  1283. Result := True;
  1284. end;
  1285. end;
  1286. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1287. var
  1288. p: taicpu absolute hp;
  1289. i: Integer;
  1290. begin
  1291. Result := False;
  1292. if not assigned(hp) or
  1293. (hp.typ <> ait_instruction) then
  1294. Exit;
  1295. // p := taicpu(hp);
  1296. Prefetch(insprop[p.opcode]);
  1297. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1298. with insprop[p.opcode] do
  1299. begin
  1300. case getsubreg(reg) of
  1301. R_SUBW,R_SUBD,R_SUBQ:
  1302. Result:=
  1303. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1304. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1305. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1306. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1307. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1308. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1309. R_SUBFLAGCARRY:
  1310. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1311. R_SUBFLAGPARITY:
  1312. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1313. R_SUBFLAGAUXILIARY:
  1314. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1315. R_SUBFLAGZERO:
  1316. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1317. R_SUBFLAGSIGN:
  1318. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1319. R_SUBFLAGOVERFLOW:
  1320. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1321. R_SUBFLAGINTERRUPT:
  1322. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1323. R_SUBFLAGDIRECTION:
  1324. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1325. else
  1326. begin
  1327. writeln(getsubreg(reg));
  1328. internalerror(2017050501);
  1329. end;
  1330. end;
  1331. exit;
  1332. end;
  1333. { Handle special cases first }
  1334. case p.opcode of
  1335. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1336. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1337. begin
  1338. Result :=
  1339. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1340. (p.oper[1]^.typ = top_reg) and
  1341. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1342. (
  1343. (p.oper[0]^.typ = top_const) or
  1344. (
  1345. (p.oper[0]^.typ = top_reg) and
  1346. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1347. ) or (
  1348. (p.oper[0]^.typ = top_ref) and
  1349. not RegInRef(reg,p.oper[0]^.ref^)
  1350. )
  1351. );
  1352. end;
  1353. A_MUL, A_IMUL:
  1354. Result :=
  1355. (
  1356. (p.ops=3) and { IMUL only }
  1357. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1358. (
  1359. (
  1360. (p.oper[1]^.typ=top_reg) and
  1361. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1362. ) or (
  1363. (p.oper[1]^.typ=top_ref) and
  1364. not RegInRef(reg,p.oper[1]^.ref^)
  1365. )
  1366. )
  1367. ) or (
  1368. (
  1369. (p.ops=1) and
  1370. (
  1371. (
  1372. (
  1373. (p.oper[0]^.typ=top_reg) and
  1374. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1375. )
  1376. ) or (
  1377. (p.oper[0]^.typ=top_ref) and
  1378. not RegInRef(reg,p.oper[0]^.ref^)
  1379. )
  1380. ) and (
  1381. (
  1382. (p.opsize=S_B) and
  1383. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1384. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1385. ) or (
  1386. (p.opsize=S_W) and
  1387. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1388. ) or (
  1389. (p.opsize=S_L) and
  1390. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1391. {$ifdef x86_64}
  1392. ) or (
  1393. (p.opsize=S_Q) and
  1394. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1395. {$endif x86_64}
  1396. )
  1397. )
  1398. )
  1399. );
  1400. A_CBW:
  1401. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1402. {$ifndef x86_64}
  1403. A_LDS:
  1404. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1405. A_LES:
  1406. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1407. {$endif not x86_64}
  1408. A_LFS:
  1409. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1410. A_LGS:
  1411. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1412. A_LSS:
  1413. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1414. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1415. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1416. A_LODSB:
  1417. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1418. A_LODSW:
  1419. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1420. {$ifdef x86_64}
  1421. A_LODSQ:
  1422. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1423. {$endif x86_64}
  1424. A_LODSD:
  1425. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1426. A_FSTSW, A_FNSTSW:
  1427. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1428. else
  1429. begin
  1430. with insprop[p.opcode] do
  1431. begin
  1432. if (
  1433. { xor %reg,%reg etc. is classed as a new value }
  1434. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1435. MatchOpType(p, top_reg, top_reg) and
  1436. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1437. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1438. ) then
  1439. begin
  1440. Result := True;
  1441. Exit;
  1442. end;
  1443. { Make sure the entire register is overwritten }
  1444. if (getregtype(reg) = R_INTREGISTER) then
  1445. begin
  1446. if (p.ops > 0) then
  1447. begin
  1448. if RegInOp(reg, p.oper[0]^) then
  1449. begin
  1450. if (p.oper[0]^.typ = top_ref) then
  1451. begin
  1452. if RegInRef(reg, p.oper[0]^.ref^) then
  1453. begin
  1454. Result := False;
  1455. Exit;
  1456. end;
  1457. end
  1458. else if (p.oper[0]^.typ = top_reg) then
  1459. begin
  1460. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1461. begin
  1462. Result := False;
  1463. Exit;
  1464. end
  1465. else if ([Ch_WOp1]*Ch<>[]) then
  1466. begin
  1467. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1468. Result := True
  1469. else
  1470. begin
  1471. Result := False;
  1472. Exit;
  1473. end;
  1474. end;
  1475. end;
  1476. end;
  1477. if (p.ops > 1) then
  1478. begin
  1479. if RegInOp(reg, p.oper[1]^) then
  1480. begin
  1481. if (p.oper[1]^.typ = top_ref) then
  1482. begin
  1483. if RegInRef(reg, p.oper[1]^.ref^) then
  1484. begin
  1485. Result := False;
  1486. Exit;
  1487. end;
  1488. end
  1489. else if (p.oper[1]^.typ = top_reg) then
  1490. begin
  1491. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1492. begin
  1493. Result := False;
  1494. Exit;
  1495. end
  1496. else if ([Ch_WOp2]*Ch<>[]) then
  1497. begin
  1498. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1499. Result := True
  1500. else
  1501. begin
  1502. Result := False;
  1503. Exit;
  1504. end;
  1505. end;
  1506. end;
  1507. end;
  1508. if (p.ops > 2) then
  1509. begin
  1510. if RegInOp(reg, p.oper[2]^) then
  1511. begin
  1512. if (p.oper[2]^.typ = top_ref) then
  1513. begin
  1514. if RegInRef(reg, p.oper[2]^.ref^) then
  1515. begin
  1516. Result := False;
  1517. Exit;
  1518. end;
  1519. end
  1520. else if (p.oper[2]^.typ = top_reg) then
  1521. begin
  1522. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1523. begin
  1524. Result := False;
  1525. Exit;
  1526. end
  1527. else if ([Ch_WOp3]*Ch<>[]) then
  1528. begin
  1529. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1530. Result := True
  1531. else
  1532. begin
  1533. Result := False;
  1534. Exit;
  1535. end;
  1536. end;
  1537. end;
  1538. end;
  1539. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1540. begin
  1541. if (p.oper[3]^.typ = top_ref) then
  1542. begin
  1543. if RegInRef(reg, p.oper[3]^.ref^) then
  1544. begin
  1545. Result := False;
  1546. Exit;
  1547. end;
  1548. end
  1549. else if (p.oper[3]^.typ = top_reg) then
  1550. begin
  1551. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1552. begin
  1553. Result := False;
  1554. Exit;
  1555. end
  1556. else if ([Ch_WOp4]*Ch<>[]) then
  1557. begin
  1558. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1559. Result := True
  1560. else
  1561. begin
  1562. Result := False;
  1563. Exit;
  1564. end;
  1565. end;
  1566. end;
  1567. end;
  1568. end;
  1569. end;
  1570. end;
  1571. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1572. case getsupreg(reg) of
  1573. RS_EAX:
  1574. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1575. begin
  1576. Result := True;
  1577. Exit;
  1578. end;
  1579. RS_ECX:
  1580. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1581. begin
  1582. Result := True;
  1583. Exit;
  1584. end;
  1585. RS_EDX:
  1586. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1587. begin
  1588. Result := True;
  1589. Exit;
  1590. end;
  1591. RS_EBX:
  1592. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1593. begin
  1594. Result := True;
  1595. Exit;
  1596. end;
  1597. RS_ESP:
  1598. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1599. begin
  1600. Result := True;
  1601. Exit;
  1602. end;
  1603. RS_EBP:
  1604. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1605. begin
  1606. Result := True;
  1607. Exit;
  1608. end;
  1609. RS_ESI:
  1610. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1611. begin
  1612. Result := True;
  1613. Exit;
  1614. end;
  1615. RS_EDI:
  1616. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1617. begin
  1618. Result := True;
  1619. Exit;
  1620. end;
  1621. else
  1622. ;
  1623. end;
  1624. end;
  1625. end;
  1626. end;
  1627. end;
  1628. end;
  1629. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1630. var
  1631. hp2,hp3 : tai;
  1632. begin
  1633. { some x86-64 issue a NOP before the real exit code }
  1634. if MatchInstruction(p,A_NOP,[]) then
  1635. GetNextInstruction(p,p);
  1636. result:=assigned(p) and (p.typ=ait_instruction) and
  1637. ((taicpu(p).opcode = A_RET) or
  1638. ((taicpu(p).opcode=A_LEAVE) and
  1639. GetNextInstruction(p,hp2) and
  1640. MatchInstruction(hp2,A_RET,[S_NO])
  1641. ) or
  1642. (((taicpu(p).opcode=A_LEA) and
  1643. MatchOpType(taicpu(p),top_ref,top_reg) and
  1644. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1645. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1646. ) and
  1647. GetNextInstruction(p,hp2) and
  1648. MatchInstruction(hp2,A_RET,[S_NO])
  1649. ) or
  1650. ((((taicpu(p).opcode=A_MOV) and
  1651. MatchOpType(taicpu(p),top_reg,top_reg) and
  1652. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1653. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1654. ((taicpu(p).opcode=A_LEA) and
  1655. MatchOpType(taicpu(p),top_ref,top_reg) and
  1656. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1657. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1658. )
  1659. ) and
  1660. GetNextInstruction(p,hp2) and
  1661. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1662. MatchOpType(taicpu(hp2),top_reg) and
  1663. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1664. GetNextInstruction(hp2,hp3) and
  1665. MatchInstruction(hp3,A_RET,[S_NO])
  1666. )
  1667. );
  1668. end;
  1669. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1670. begin
  1671. isFoldableArithOp := False;
  1672. case hp1.opcode of
  1673. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1674. isFoldableArithOp :=
  1675. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1676. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1677. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1678. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1679. (taicpu(hp1).oper[1]^.reg = reg);
  1680. A_INC,A_DEC,A_NEG,A_NOT:
  1681. isFoldableArithOp :=
  1682. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1683. (taicpu(hp1).oper[0]^.reg = reg);
  1684. else
  1685. ;
  1686. end;
  1687. end;
  1688. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1689. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1690. var
  1691. hp2: tai;
  1692. begin
  1693. hp2 := p;
  1694. repeat
  1695. hp2 := tai(hp2.previous);
  1696. if assigned(hp2) and
  1697. (hp2.typ = ait_regalloc) and
  1698. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1699. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1700. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1701. begin
  1702. RemoveInstruction(hp2);
  1703. break;
  1704. end;
  1705. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1706. end;
  1707. begin
  1708. case current_procinfo.procdef.returndef.typ of
  1709. arraydef,recorddef,pointerdef,
  1710. stringdef,enumdef,procdef,objectdef,errordef,
  1711. filedef,setdef,procvardef,
  1712. classrefdef,forwarddef:
  1713. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1714. orddef:
  1715. if current_procinfo.procdef.returndef.size <> 0 then
  1716. begin
  1717. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1718. { for int64/qword }
  1719. if current_procinfo.procdef.returndef.size = 8 then
  1720. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1721. end;
  1722. else
  1723. ;
  1724. end;
  1725. end;
  1726. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1727. var
  1728. hp1,hp2 : tai;
  1729. begin
  1730. result:=false;
  1731. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1732. begin
  1733. { vmova* reg1,reg1
  1734. =>
  1735. <nop> }
  1736. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1737. begin
  1738. RemoveCurrentP(p);
  1739. result:=true;
  1740. exit;
  1741. end
  1742. else if GetNextInstruction(p,hp1) then
  1743. begin
  1744. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1745. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1746. begin
  1747. { vmova* reg1,reg2
  1748. vmova* reg2,reg3
  1749. dealloc reg2
  1750. =>
  1751. vmova* reg1,reg3 }
  1752. TransferUsedRegs(TmpUsedRegs);
  1753. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1754. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1755. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1756. begin
  1757. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1758. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1759. RemoveInstruction(hp1);
  1760. result:=true;
  1761. exit;
  1762. end
  1763. { special case:
  1764. vmova* reg1,<op>
  1765. vmova* <op>,reg1
  1766. =>
  1767. vmova* reg1,<op> }
  1768. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1769. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1770. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1771. ) then
  1772. begin
  1773. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1774. RemoveInstruction(hp1);
  1775. result:=true;
  1776. exit;
  1777. end
  1778. end
  1779. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1780. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1781. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1782. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1783. ) and
  1784. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1785. begin
  1786. { vmova* reg1,reg2
  1787. vmovs* reg2,<op>
  1788. dealloc reg2
  1789. =>
  1790. vmovs* reg1,reg3 }
  1791. TransferUsedRegs(TmpUsedRegs);
  1792. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1793. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1794. begin
  1795. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1796. taicpu(p).opcode:=taicpu(hp1).opcode;
  1797. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1798. RemoveInstruction(hp1);
  1799. result:=true;
  1800. exit;
  1801. end
  1802. end;
  1803. end;
  1804. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1805. begin
  1806. if MatchInstruction(hp1,[A_VFMADDPD,
  1807. A_VFMADD132PD,
  1808. A_VFMADD132PS,
  1809. A_VFMADD132SD,
  1810. A_VFMADD132SS,
  1811. A_VFMADD213PD,
  1812. A_VFMADD213PS,
  1813. A_VFMADD213SD,
  1814. A_VFMADD213SS,
  1815. A_VFMADD231PD,
  1816. A_VFMADD231PS,
  1817. A_VFMADD231SD,
  1818. A_VFMADD231SS,
  1819. A_VFMADDSUB132PD,
  1820. A_VFMADDSUB132PS,
  1821. A_VFMADDSUB213PD,
  1822. A_VFMADDSUB213PS,
  1823. A_VFMADDSUB231PD,
  1824. A_VFMADDSUB231PS,
  1825. A_VFMSUB132PD,
  1826. A_VFMSUB132PS,
  1827. A_VFMSUB132SD,
  1828. A_VFMSUB132SS,
  1829. A_VFMSUB213PD,
  1830. A_VFMSUB213PS,
  1831. A_VFMSUB213SD,
  1832. A_VFMSUB213SS,
  1833. A_VFMSUB231PD,
  1834. A_VFMSUB231PS,
  1835. A_VFMSUB231SD,
  1836. A_VFMSUB231SS,
  1837. A_VFMSUBADD132PD,
  1838. A_VFMSUBADD132PS,
  1839. A_VFMSUBADD213PD,
  1840. A_VFMSUBADD213PS,
  1841. A_VFMSUBADD231PD,
  1842. A_VFMSUBADD231PS,
  1843. A_VFNMADD132PD,
  1844. A_VFNMADD132PS,
  1845. A_VFNMADD132SD,
  1846. A_VFNMADD132SS,
  1847. A_VFNMADD213PD,
  1848. A_VFNMADD213PS,
  1849. A_VFNMADD213SD,
  1850. A_VFNMADD213SS,
  1851. A_VFNMADD231PD,
  1852. A_VFNMADD231PS,
  1853. A_VFNMADD231SD,
  1854. A_VFNMADD231SS,
  1855. A_VFNMSUB132PD,
  1856. A_VFNMSUB132PS,
  1857. A_VFNMSUB132SD,
  1858. A_VFNMSUB132SS,
  1859. A_VFNMSUB213PD,
  1860. A_VFNMSUB213PS,
  1861. A_VFNMSUB213SD,
  1862. A_VFNMSUB213SS,
  1863. A_VFNMSUB231PD,
  1864. A_VFNMSUB231PS,
  1865. A_VFNMSUB231SD,
  1866. A_VFNMSUB231SS],[S_NO]) and
  1867. { we mix single and double opperations here because we assume that the compiler
  1868. generates vmovapd only after double operations and vmovaps only after single operations }
  1869. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1870. GetNextInstruction(hp1,hp2) and
  1871. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1872. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1873. begin
  1874. TransferUsedRegs(TmpUsedRegs);
  1875. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1876. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1877. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1878. begin
  1879. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1880. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1881. RemoveInstruction(hp2);
  1882. end;
  1883. end
  1884. else if (hp1.typ = ait_instruction) and
  1885. GetNextInstruction(hp1, hp2) and
  1886. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1887. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1888. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1889. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1890. (((taicpu(p).opcode=A_MOVAPS) and
  1891. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1892. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1893. ((taicpu(p).opcode=A_MOVAPD) and
  1894. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1895. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1896. ) then
  1897. { change
  1898. movapX reg,reg2
  1899. addsX/subsX/... reg3, reg2
  1900. movapX reg2,reg
  1901. to
  1902. addsX/subsX/... reg3,reg
  1903. }
  1904. begin
  1905. TransferUsedRegs(TmpUsedRegs);
  1906. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1907. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1908. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1909. begin
  1910. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1911. debug_op2str(taicpu(p).opcode)+' '+
  1912. debug_op2str(taicpu(hp1).opcode)+' '+
  1913. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1914. { we cannot eliminate the first move if
  1915. the operations uses the same register for source and dest }
  1916. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1917. RemoveCurrentP(p, nil);
  1918. p:=hp1;
  1919. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1920. RemoveInstruction(hp2);
  1921. result:=true;
  1922. end;
  1923. end
  1924. else if (hp1.typ = ait_instruction) and
  1925. (((taicpu(p).opcode=A_VMOVAPD) and
  1926. (taicpu(hp1).opcode=A_VCOMISD)) or
  1927. ((taicpu(p).opcode=A_VMOVAPS) and
  1928. ((taicpu(hp1).opcode=A_VCOMISS))
  1929. )
  1930. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1931. { change
  1932. movapX reg,reg2
  1933. addsX/subsX/... reg3, reg2
  1934. movapX reg2,reg
  1935. to
  1936. addsX/subsX/... reg3,reg
  1937. }
  1938. begin
  1939. TransferUsedRegs(TmpUsedRegs);
  1940. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1941. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1942. begin
  1943. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1944. debug_op2str(taicpu(p).opcode)+' '+
  1945. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1946. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1947. taicpu(hp1).loadoper(0, taicpu(p).oper[1]^);
  1948. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1949. taicpu(hp1).loadoper(1, taicpu(p).oper[1]^);
  1950. RemoveCurrentP(p, nil);
  1951. result:=true;
  1952. exit;
  1953. end;
  1954. end
  1955. end;
  1956. end;
  1957. end;
  1958. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1959. var
  1960. hp1 : tai;
  1961. begin
  1962. result:=false;
  1963. { replace
  1964. V<Op>X %mreg1,%mreg2,%mreg3
  1965. VMovX %mreg3,%mreg4
  1966. dealloc %mreg3
  1967. by
  1968. V<Op>X %mreg1,%mreg2,%mreg4
  1969. ?
  1970. }
  1971. if GetNextInstruction(p,hp1) and
  1972. { we mix single and double operations here because we assume that the compiler
  1973. generates vmovapd only after double operations and vmovaps only after single operations }
  1974. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1975. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1976. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1977. begin
  1978. TransferUsedRegs(TmpUsedRegs);
  1979. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1980. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1981. begin
  1982. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1983. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1984. RemoveInstruction(hp1);
  1985. result:=true;
  1986. end;
  1987. end;
  1988. end;
  1989. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1990. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1991. begin
  1992. Result := False;
  1993. { For safety reasons, only check for exact register matches }
  1994. { Check base register }
  1995. if (ref.base = AOldReg) then
  1996. begin
  1997. ref.base := ANewReg;
  1998. Result := True;
  1999. end;
  2000. { Check index register }
  2001. if (ref.index = AOldReg) then
  2002. begin
  2003. ref.index := ANewReg;
  2004. Result := True;
  2005. end;
  2006. end;
  2007. { Replaces all references to AOldReg in an operand to ANewReg }
  2008. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2009. var
  2010. OldSupReg, NewSupReg: TSuperRegister;
  2011. OldSubReg, NewSubReg: TSubRegister;
  2012. OldRegType: TRegisterType;
  2013. ThisOper: POper;
  2014. begin
  2015. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2016. Result := False;
  2017. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2018. InternalError(2020011801);
  2019. OldSupReg := getsupreg(AOldReg);
  2020. OldSubReg := getsubreg(AOldReg);
  2021. OldRegType := getregtype(AOldReg);
  2022. NewSupReg := getsupreg(ANewReg);
  2023. NewSubReg := getsubreg(ANewReg);
  2024. if OldRegType <> getregtype(ANewReg) then
  2025. InternalError(2020011802);
  2026. if OldSubReg <> NewSubReg then
  2027. InternalError(2020011803);
  2028. case ThisOper^.typ of
  2029. top_reg:
  2030. if (
  2031. (ThisOper^.reg = AOldReg) or
  2032. (
  2033. (OldRegType = R_INTREGISTER) and
  2034. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2035. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2036. (
  2037. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2038. {$ifndef x86_64}
  2039. and (
  2040. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2041. don't have an 8-bit representation }
  2042. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2043. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2044. )
  2045. {$endif x86_64}
  2046. )
  2047. )
  2048. ) then
  2049. begin
  2050. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2051. Result := True;
  2052. end;
  2053. top_ref:
  2054. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2055. Result := True;
  2056. else
  2057. ;
  2058. end;
  2059. end;
  2060. { Replaces all references to AOldReg in an instruction to ANewReg }
  2061. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2062. const
  2063. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2064. var
  2065. OperIdx: Integer;
  2066. begin
  2067. Result := False;
  2068. for OperIdx := 0 to p.ops - 1 do
  2069. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2070. begin
  2071. { The shift and rotate instructions can only use CL }
  2072. if not (
  2073. (OperIdx = 0) and
  2074. { This second condition just helps to avoid unnecessarily
  2075. calling MatchInstruction for 10 different opcodes }
  2076. (p.oper[0]^.reg = NR_CL) and
  2077. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2078. ) then
  2079. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2080. end
  2081. else if p.oper[OperIdx]^.typ = top_ref then
  2082. { It's okay to replace registers in references that get written to }
  2083. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2084. end;
  2085. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2086. begin
  2087. with ref^ do
  2088. Result :=
  2089. (index = NR_NO) and
  2090. (
  2091. {$ifdef x86_64}
  2092. (
  2093. (base = NR_RIP) and
  2094. (refaddr in [addr_pic, addr_pic_no_got])
  2095. ) or
  2096. {$endif x86_64}
  2097. (base = NR_STACK_POINTER_REG) or
  2098. (base = current_procinfo.framepointer)
  2099. );
  2100. end;
  2101. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2102. var
  2103. l: asizeint;
  2104. begin
  2105. Result := False;
  2106. { Should have been checked previously }
  2107. if p.opcode <> A_LEA then
  2108. InternalError(2020072501);
  2109. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2110. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2111. not(cs_opt_size in current_settings.optimizerswitches) then
  2112. exit;
  2113. with p.oper[0]^.ref^ do
  2114. begin
  2115. if (base <> p.oper[1]^.reg) or
  2116. (index <> NR_NO) or
  2117. assigned(symbol) then
  2118. exit;
  2119. l:=offset;
  2120. if (l=1) and UseIncDec then
  2121. begin
  2122. p.opcode:=A_INC;
  2123. p.loadreg(0,p.oper[1]^.reg);
  2124. p.ops:=1;
  2125. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2126. end
  2127. else if (l=-1) and UseIncDec then
  2128. begin
  2129. p.opcode:=A_DEC;
  2130. p.loadreg(0,p.oper[1]^.reg);
  2131. p.ops:=1;
  2132. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2133. end
  2134. else
  2135. begin
  2136. if (l<0) and (l<>-2147483648) then
  2137. begin
  2138. p.opcode:=A_SUB;
  2139. p.loadConst(0,-l);
  2140. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2141. end
  2142. else
  2143. begin
  2144. p.opcode:=A_ADD;
  2145. p.loadConst(0,l);
  2146. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2147. end;
  2148. end;
  2149. end;
  2150. Result := True;
  2151. end;
  2152. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2153. var
  2154. CurrentReg, ReplaceReg: TRegister;
  2155. begin
  2156. Result := False;
  2157. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2158. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2159. case hp.opcode of
  2160. A_FSTSW, A_FNSTSW,
  2161. A_IN, A_INS, A_OUT, A_OUTS,
  2162. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2163. { These routines have explicit operands, but they are restricted in
  2164. what they can be (e.g. IN and OUT can only read from AL, AX or
  2165. EAX. }
  2166. Exit;
  2167. A_IMUL:
  2168. begin
  2169. { The 1-operand version writes to implicit registers
  2170. The 2-operand version reads from the first operator, and reads
  2171. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2172. the 3-operand version reads from a register that it doesn't write to
  2173. }
  2174. case hp.ops of
  2175. 1:
  2176. if (
  2177. (
  2178. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2179. ) or
  2180. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2181. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2182. begin
  2183. Result := True;
  2184. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2185. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2186. end;
  2187. 2:
  2188. { Only modify the first parameter }
  2189. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2190. begin
  2191. Result := True;
  2192. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2193. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2194. end;
  2195. 3:
  2196. { Only modify the second parameter }
  2197. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2198. begin
  2199. Result := True;
  2200. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2201. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2202. end;
  2203. else
  2204. InternalError(2020012901);
  2205. end;
  2206. end;
  2207. else
  2208. if (hp.ops > 0) and
  2209. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2210. begin
  2211. Result := True;
  2212. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2213. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2214. end;
  2215. end;
  2216. end;
  2217. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2218. var
  2219. hp1, hp2, hp3: tai;
  2220. DoOptimisation, TempBool: Boolean;
  2221. {$ifdef x86_64}
  2222. NewConst: TCGInt;
  2223. {$endif x86_64}
  2224. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2225. begin
  2226. if taicpu(hp1).opcode = signed_movop then
  2227. begin
  2228. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2229. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2230. end
  2231. else
  2232. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2233. end;
  2234. function TryConstMerge(var p1, p2: tai): Boolean;
  2235. var
  2236. ThisRef: TReference;
  2237. begin
  2238. Result := False;
  2239. ThisRef := taicpu(p2).oper[1]^.ref^;
  2240. { Only permit writes to the stack, since we can guarantee alignment with that }
  2241. if (ThisRef.index = NR_NO) and
  2242. (
  2243. (ThisRef.base = NR_STACK_POINTER_REG) or
  2244. (ThisRef.base = current_procinfo.framepointer)
  2245. ) then
  2246. begin
  2247. case taicpu(p).opsize of
  2248. S_B:
  2249. begin
  2250. { Word writes must be on a 2-byte boundary }
  2251. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2252. begin
  2253. { Reduce offset of second reference to see if it is sequential with the first }
  2254. Dec(ThisRef.offset, 1);
  2255. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2256. begin
  2257. { Make sure the constants aren't represented as a
  2258. negative number, as these won't merge properly }
  2259. taicpu(p1).opsize := S_W;
  2260. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2261. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2262. RemoveInstruction(p2);
  2263. Result := True;
  2264. end;
  2265. end;
  2266. end;
  2267. S_W:
  2268. begin
  2269. { Longword writes must be on a 4-byte boundary }
  2270. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2271. begin
  2272. { Reduce offset of second reference to see if it is sequential with the first }
  2273. Dec(ThisRef.offset, 2);
  2274. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2275. begin
  2276. { Make sure the constants aren't represented as a
  2277. negative number, as these won't merge properly }
  2278. taicpu(p1).opsize := S_L;
  2279. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2280. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2281. RemoveInstruction(p2);
  2282. Result := True;
  2283. end;
  2284. end;
  2285. end;
  2286. {$ifdef x86_64}
  2287. S_L:
  2288. begin
  2289. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2290. see if the constants can be encoded this way. }
  2291. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2292. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2293. { Quadword writes must be on an 8-byte boundary }
  2294. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2295. begin
  2296. { Reduce offset of second reference to see if it is sequential with the first }
  2297. Dec(ThisRef.offset, 4);
  2298. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2299. begin
  2300. { Make sure the constants aren't represented as a
  2301. negative number, as these won't merge properly }
  2302. taicpu(p1).opsize := S_Q;
  2303. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2304. taicpu(p1).oper[0]^.val := NewConst;
  2305. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2306. RemoveInstruction(p2);
  2307. Result := True;
  2308. end;
  2309. end;
  2310. end;
  2311. {$endif x86_64}
  2312. else
  2313. ;
  2314. end;
  2315. end;
  2316. end;
  2317. var
  2318. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2319. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2320. NewSize: topsize;
  2321. CurrentReg, ActiveReg: TRegister;
  2322. SourceRef, TargetRef: TReference;
  2323. MovAligned, MovUnaligned: TAsmOp;
  2324. ThisRef: TReference;
  2325. begin
  2326. Result:=false;
  2327. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2328. { remove mov reg1,reg1? }
  2329. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2330. then
  2331. begin
  2332. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2333. { take care of the register (de)allocs following p }
  2334. RemoveCurrentP(p, hp1);
  2335. Result:=true;
  2336. exit;
  2337. end;
  2338. { All the next optimisations require a next instruction }
  2339. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2340. Exit;
  2341. { Look for:
  2342. mov %reg1,%reg2
  2343. ??? %reg2,r/m
  2344. Change to:
  2345. mov %reg1,%reg2
  2346. ??? %reg1,r/m
  2347. }
  2348. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2349. begin
  2350. CurrentReg := taicpu(p).oper[1]^.reg;
  2351. if RegReadByInstruction(CurrentReg, hp1) and
  2352. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2353. begin
  2354. { A change has occurred, just not in p }
  2355. Result := True;
  2356. TransferUsedRegs(TmpUsedRegs);
  2357. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2358. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2359. { Just in case something didn't get modified (e.g. an
  2360. implicit register) }
  2361. not RegReadByInstruction(CurrentReg, hp1) then
  2362. begin
  2363. { We can remove the original MOV }
  2364. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2365. RemoveCurrentp(p, hp1);
  2366. { UsedRegs got updated by RemoveCurrentp }
  2367. Result := True;
  2368. Exit;
  2369. end;
  2370. { If we know a MOV instruction has become a null operation, we might as well
  2371. get rid of it now to save time. }
  2372. if (taicpu(hp1).opcode = A_MOV) and
  2373. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2374. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2375. { Just being a register is enough to confirm it's a null operation }
  2376. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2377. begin
  2378. Result := True;
  2379. { Speed-up to reduce a pipeline stall... if we had something like...
  2380. movl %eax,%edx
  2381. movw %dx,%ax
  2382. ... the second instruction would change to movw %ax,%ax, but
  2383. given that it is now %ax that's active rather than %eax,
  2384. penalties might occur due to a partial register write, so instead,
  2385. change it to a MOVZX instruction when optimising for speed.
  2386. }
  2387. if not (cs_opt_size in current_settings.optimizerswitches) and
  2388. IsMOVZXAcceptable and
  2389. (taicpu(hp1).opsize < taicpu(p).opsize)
  2390. {$ifdef x86_64}
  2391. { operations already implicitly set the upper 64 bits to zero }
  2392. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2393. {$endif x86_64}
  2394. then
  2395. begin
  2396. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2397. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2398. case taicpu(p).opsize of
  2399. S_W:
  2400. if taicpu(hp1).opsize = S_B then
  2401. taicpu(hp1).opsize := S_BL
  2402. else
  2403. InternalError(2020012911);
  2404. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2405. case taicpu(hp1).opsize of
  2406. S_B:
  2407. taicpu(hp1).opsize := S_BL;
  2408. S_W:
  2409. taicpu(hp1).opsize := S_WL;
  2410. else
  2411. InternalError(2020012912);
  2412. end;
  2413. else
  2414. InternalError(2020012910);
  2415. end;
  2416. taicpu(hp1).opcode := A_MOVZX;
  2417. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2418. end
  2419. else
  2420. begin
  2421. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2422. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2423. RemoveInstruction(hp1);
  2424. { The instruction after what was hp1 is now the immediate next instruction,
  2425. so we can continue to make optimisations if it's present }
  2426. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2427. Exit;
  2428. hp1 := hp2;
  2429. end;
  2430. end;
  2431. end;
  2432. end;
  2433. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2434. overwrites the original destination register. e.g.
  2435. movl ###,%reg2d
  2436. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2437. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2438. }
  2439. if (taicpu(p).oper[1]^.typ = top_reg) and
  2440. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2441. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2442. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2443. begin
  2444. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2445. begin
  2446. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2447. case taicpu(p).oper[0]^.typ of
  2448. top_const:
  2449. { We have something like:
  2450. movb $x, %regb
  2451. movzbl %regb,%regd
  2452. Change to:
  2453. movl $x, %regd
  2454. }
  2455. begin
  2456. case taicpu(hp1).opsize of
  2457. S_BW:
  2458. begin
  2459. convert_mov_value(A_MOVSX, $FF);
  2460. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2461. taicpu(p).opsize := S_W;
  2462. end;
  2463. S_BL:
  2464. begin
  2465. convert_mov_value(A_MOVSX, $FF);
  2466. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2467. taicpu(p).opsize := S_L;
  2468. end;
  2469. S_WL:
  2470. begin
  2471. convert_mov_value(A_MOVSX, $FFFF);
  2472. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2473. taicpu(p).opsize := S_L;
  2474. end;
  2475. {$ifdef x86_64}
  2476. S_BQ:
  2477. begin
  2478. convert_mov_value(A_MOVSX, $FF);
  2479. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2480. taicpu(p).opsize := S_Q;
  2481. end;
  2482. S_WQ:
  2483. begin
  2484. convert_mov_value(A_MOVSX, $FFFF);
  2485. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2486. taicpu(p).opsize := S_Q;
  2487. end;
  2488. S_LQ:
  2489. begin
  2490. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2491. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2492. taicpu(p).opsize := S_Q;
  2493. end;
  2494. {$endif x86_64}
  2495. else
  2496. { If hp1 was a MOV instruction, it should have been
  2497. optimised already }
  2498. InternalError(2020021001);
  2499. end;
  2500. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2501. RemoveInstruction(hp1);
  2502. Result := True;
  2503. Exit;
  2504. end;
  2505. top_ref:
  2506. begin
  2507. { We have something like:
  2508. movb mem, %regb
  2509. movzbl %regb,%regd
  2510. Change to:
  2511. movzbl mem, %regd
  2512. }
  2513. ThisRef := taicpu(p).oper[0]^.ref^;
  2514. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2515. begin
  2516. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2517. taicpu(hp1).loadref(0, ThisRef);
  2518. { Make sure any registers in the references are properly tracked }
  2519. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2520. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2521. if (ThisRef.index <> NR_NO) then
  2522. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2523. RemoveCurrentP(p, hp1);
  2524. Result := True;
  2525. Exit;
  2526. end;
  2527. end;
  2528. else
  2529. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2530. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2531. Exit;
  2532. end;
  2533. end
  2534. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2535. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2536. optimised }
  2537. else
  2538. begin
  2539. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2540. RemoveCurrentP(p, hp1);
  2541. Result := True;
  2542. Exit;
  2543. end;
  2544. end;
  2545. if (taicpu(hp1).opcode = A_AND) and
  2546. (taicpu(p).oper[1]^.typ = top_reg) and
  2547. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2548. begin
  2549. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2550. begin
  2551. case taicpu(p).opsize of
  2552. S_L:
  2553. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2554. begin
  2555. { Optimize out:
  2556. mov x, %reg
  2557. and ffffffffh, %reg
  2558. }
  2559. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2560. RemoveInstruction(hp1);
  2561. Result:=true;
  2562. exit;
  2563. end;
  2564. S_Q: { TODO: Confirm if this is even possible }
  2565. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2566. begin
  2567. { Optimize out:
  2568. mov x, %reg
  2569. and ffffffffffffffffh, %reg
  2570. }
  2571. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2572. RemoveInstruction(hp1);
  2573. Result:=true;
  2574. exit;
  2575. end;
  2576. else
  2577. ;
  2578. end;
  2579. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2580. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2581. GetNextInstruction(hp1,hp2) and
  2582. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2583. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2584. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2585. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2586. GetNextInstruction(hp2,hp3) and
  2587. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2588. (taicpu(hp3).condition in [C_E,C_NE]) then
  2589. begin
  2590. TransferUsedRegs(TmpUsedRegs);
  2591. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2592. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2593. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2594. begin
  2595. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2596. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2597. taicpu(hp1).opcode:=A_TEST;
  2598. RemoveInstruction(hp2);
  2599. RemoveCurrentP(p, hp1);
  2600. Result:=true;
  2601. exit;
  2602. end;
  2603. end;
  2604. end
  2605. else if IsMOVZXAcceptable and
  2606. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2607. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2608. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2609. then
  2610. begin
  2611. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2612. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2613. case taicpu(p).opsize of
  2614. S_B:
  2615. if (taicpu(hp1).oper[0]^.val = $ff) then
  2616. begin
  2617. { Convert:
  2618. movb x, %regl movb x, %regl
  2619. andw ffh, %regw andl ffh, %regd
  2620. To:
  2621. movzbw x, %regd movzbl x, %regd
  2622. (Identical registers, just different sizes)
  2623. }
  2624. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2625. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2626. case taicpu(hp1).opsize of
  2627. S_W: NewSize := S_BW;
  2628. S_L: NewSize := S_BL;
  2629. {$ifdef x86_64}
  2630. S_Q: NewSize := S_BQ;
  2631. {$endif x86_64}
  2632. else
  2633. InternalError(2018011510);
  2634. end;
  2635. end
  2636. else
  2637. NewSize := S_NO;
  2638. S_W:
  2639. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2640. begin
  2641. { Convert:
  2642. movw x, %regw
  2643. andl ffffh, %regd
  2644. To:
  2645. movzwl x, %regd
  2646. (Identical registers, just different sizes)
  2647. }
  2648. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2649. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2650. case taicpu(hp1).opsize of
  2651. S_L: NewSize := S_WL;
  2652. {$ifdef x86_64}
  2653. S_Q: NewSize := S_WQ;
  2654. {$endif x86_64}
  2655. else
  2656. InternalError(2018011511);
  2657. end;
  2658. end
  2659. else
  2660. NewSize := S_NO;
  2661. else
  2662. NewSize := S_NO;
  2663. end;
  2664. if NewSize <> S_NO then
  2665. begin
  2666. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2667. { The actual optimization }
  2668. taicpu(p).opcode := A_MOVZX;
  2669. taicpu(p).changeopsize(NewSize);
  2670. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2671. { Safeguard if "and" is followed by a conditional command }
  2672. TransferUsedRegs(TmpUsedRegs);
  2673. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2674. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2675. begin
  2676. { At this point, the "and" command is effectively equivalent to
  2677. "test %reg,%reg". This will be handled separately by the
  2678. Peephole Optimizer. [Kit] }
  2679. DebugMsg(SPeepholeOptimization + PreMessage +
  2680. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2681. end
  2682. else
  2683. begin
  2684. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2685. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2686. RemoveInstruction(hp1);
  2687. end;
  2688. Result := True;
  2689. Exit;
  2690. end;
  2691. end;
  2692. end;
  2693. if (taicpu(hp1).opcode = A_OR) and
  2694. (taicpu(p).oper[1]^.typ = top_reg) and
  2695. MatchOperand(taicpu(p).oper[0]^, 0) and
  2696. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2697. begin
  2698. { mov 0, %reg
  2699. or ###,%reg
  2700. Change to (only if the flags are not used):
  2701. mov ###,%reg
  2702. }
  2703. TransferUsedRegs(TmpUsedRegs);
  2704. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2705. DoOptimisation := True;
  2706. { Even if the flags are used, we might be able to do the optimisation
  2707. if the conditions are predictable }
  2708. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2709. begin
  2710. { Only perform if ### = %reg (the same register) or equal to 0,
  2711. so %reg is guaranteed to still have a value of zero }
  2712. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2713. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2714. begin
  2715. hp2 := hp1;
  2716. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2717. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2718. GetNextInstruction(hp2, hp3) do
  2719. begin
  2720. { Don't continue modifying if the flags state is getting changed }
  2721. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2722. Break;
  2723. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2724. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2725. begin
  2726. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2727. begin
  2728. { Condition is always true }
  2729. case taicpu(hp3).opcode of
  2730. A_Jcc:
  2731. begin
  2732. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2733. { Check for jump shortcuts before we destroy the condition }
  2734. DoJumpOptimizations(hp3, TempBool);
  2735. MakeUnconditional(taicpu(hp3));
  2736. Result := True;
  2737. end;
  2738. A_CMOVcc:
  2739. begin
  2740. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2741. taicpu(hp3).opcode := A_MOV;
  2742. taicpu(hp3).condition := C_None;
  2743. Result := True;
  2744. end;
  2745. A_SETcc:
  2746. begin
  2747. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2748. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2749. taicpu(hp3).opcode := A_MOV;
  2750. taicpu(hp3).ops := 2;
  2751. taicpu(hp3).condition := C_None;
  2752. taicpu(hp3).opsize := S_B;
  2753. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2754. taicpu(hp3).loadconst(0, 1);
  2755. Result := True;
  2756. end;
  2757. else
  2758. InternalError(2021090701);
  2759. end;
  2760. end
  2761. 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
  2762. begin
  2763. { Condition is always false }
  2764. case taicpu(hp3).opcode of
  2765. A_Jcc:
  2766. begin
  2767. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2768. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2769. RemoveInstruction(hp3);
  2770. Result := True;
  2771. { Since hp3 was deleted, hp2 must not be updated }
  2772. Continue;
  2773. end;
  2774. A_CMOVcc:
  2775. begin
  2776. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2777. RemoveInstruction(hp3);
  2778. Result := True;
  2779. { Since hp3 was deleted, hp2 must not be updated }
  2780. Continue;
  2781. end;
  2782. A_SETcc:
  2783. begin
  2784. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2785. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2786. taicpu(hp3).opcode := A_MOV;
  2787. taicpu(hp3).ops := 2;
  2788. taicpu(hp3).condition := C_None;
  2789. taicpu(hp3).opsize := S_B;
  2790. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2791. taicpu(hp3).loadconst(0, 0);
  2792. Result := True;
  2793. end;
  2794. else
  2795. InternalError(2021090702);
  2796. end;
  2797. end
  2798. else
  2799. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2800. DoOptimisation := False;
  2801. end;
  2802. hp2 := hp3;
  2803. end;
  2804. { Flags are still in use - don't optimise }
  2805. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2806. DoOptimisation := False;
  2807. end
  2808. else
  2809. DoOptimisation := False;
  2810. end;
  2811. if DoOptimisation then
  2812. begin
  2813. {$ifdef x86_64}
  2814. { OR only supports 32-bit sign-extended constants for 64-bit
  2815. instructions, so compensate for this if the constant is
  2816. encoded as a value greater than or equal to 2^31 }
  2817. if (taicpu(hp1).opsize = S_Q) and
  2818. (taicpu(hp1).oper[0]^.typ = top_const) and
  2819. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2820. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2821. {$endif x86_64}
  2822. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2823. taicpu(hp1).opcode := A_MOV;
  2824. RemoveCurrentP(p, hp1);
  2825. Result := True;
  2826. Exit;
  2827. end;
  2828. end;
  2829. { Next instruction is also a MOV ? }
  2830. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2831. begin
  2832. if MatchOpType(taicpu(p), top_const, top_ref) and
  2833. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2834. TryConstMerge(p, hp1) then
  2835. begin
  2836. Result := True;
  2837. { In case we have four byte writes in a row, check for 2 more
  2838. right now so we don't have to wait for another iteration of
  2839. pass 1
  2840. }
  2841. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2842. case taicpu(p).opsize of
  2843. S_W:
  2844. begin
  2845. if GetNextInstruction(p, hp1) and
  2846. MatchInstruction(hp1, A_MOV, [S_B]) and
  2847. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2848. GetNextInstruction(hp1, hp2) and
  2849. MatchInstruction(hp2, A_MOV, [S_B]) and
  2850. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2851. { Try to merge the two bytes }
  2852. TryConstMerge(hp1, hp2) then
  2853. { Now try to merge the two words (hp2 will get deleted) }
  2854. TryConstMerge(p, hp1);
  2855. end;
  2856. S_L:
  2857. begin
  2858. { Though this only really benefits x86_64 and not i386, it
  2859. gets a potential optimisation done faster and hence
  2860. reduces the number of times OptPass1MOV is entered }
  2861. if GetNextInstruction(p, hp1) and
  2862. MatchInstruction(hp1, A_MOV, [S_W]) and
  2863. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2864. GetNextInstruction(hp1, hp2) and
  2865. MatchInstruction(hp2, A_MOV, [S_W]) and
  2866. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2867. { Try to merge the two words }
  2868. TryConstMerge(hp1, hp2) then
  2869. { This will always fail on i386, so don't bother
  2870. calling it unless we're doing x86_64 }
  2871. {$ifdef x86_64}
  2872. { Now try to merge the two longwords (hp2 will get deleted) }
  2873. TryConstMerge(p, hp1)
  2874. {$endif x86_64}
  2875. ;
  2876. end;
  2877. else
  2878. ;
  2879. end;
  2880. Exit;
  2881. end;
  2882. if (taicpu(p).oper[1]^.typ = top_reg) and
  2883. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2884. begin
  2885. CurrentReg := taicpu(p).oper[1]^.reg;
  2886. TransferUsedRegs(TmpUsedRegs);
  2887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2888. { we have
  2889. mov x, %treg
  2890. mov %treg, y
  2891. }
  2892. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2893. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2894. { we've got
  2895. mov x, %treg
  2896. mov %treg, y
  2897. with %treg is not used after }
  2898. case taicpu(p).oper[0]^.typ Of
  2899. { top_reg is covered by DeepMOVOpt }
  2900. top_const:
  2901. begin
  2902. { change
  2903. mov const, %treg
  2904. mov %treg, y
  2905. to
  2906. mov const, y
  2907. }
  2908. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2909. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2910. begin
  2911. if taicpu(hp1).oper[1]^.typ=top_reg then
  2912. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2913. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2914. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2915. RemoveInstruction(hp1);
  2916. Result:=true;
  2917. Exit;
  2918. end;
  2919. end;
  2920. top_ref:
  2921. case taicpu(hp1).oper[1]^.typ of
  2922. top_reg:
  2923. begin
  2924. { change
  2925. mov mem, %treg
  2926. mov %treg, %reg
  2927. to
  2928. mov mem, %reg"
  2929. }
  2930. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2931. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2932. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2933. RemoveInstruction(hp1);
  2934. Result:=true;
  2935. Exit;
  2936. end;
  2937. top_ref:
  2938. begin
  2939. {$ifdef x86_64}
  2940. { Look for the following to simplify:
  2941. mov x(mem1), %reg
  2942. mov %reg, y(mem2)
  2943. mov x+8(mem1), %reg
  2944. mov %reg, y+8(mem2)
  2945. Change to:
  2946. movdqu x(mem1), %xmmreg
  2947. movdqu %xmmreg, y(mem2)
  2948. }
  2949. SourceRef := taicpu(p).oper[0]^.ref^;
  2950. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2951. if (taicpu(p).opsize = S_Q) and
  2952. GetNextInstruction(hp1, hp2) and
  2953. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2954. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2955. begin
  2956. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2957. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2958. Inc(SourceRef.offset, 8);
  2959. if UseAVX then
  2960. begin
  2961. MovAligned := A_VMOVDQA;
  2962. MovUnaligned := A_VMOVDQU;
  2963. end
  2964. else
  2965. begin
  2966. MovAligned := A_MOVDQA;
  2967. MovUnaligned := A_MOVDQU;
  2968. end;
  2969. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2970. begin
  2971. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2972. Inc(TargetRef.offset, 8);
  2973. if GetNextInstruction(hp2, hp3) and
  2974. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2975. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2976. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2977. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2978. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2979. begin
  2980. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2981. if CurrentReg <> NR_NO then
  2982. begin
  2983. { Remember that the offsets are 8 ahead }
  2984. if ((SourceRef.offset mod 16) = 8) and
  2985. (
  2986. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2987. (SourceRef.base = current_procinfo.framepointer) or
  2988. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2989. ) then
  2990. taicpu(p).opcode := MovAligned
  2991. else
  2992. taicpu(p).opcode := MovUnaligned;
  2993. taicpu(p).opsize := S_XMM;
  2994. taicpu(p).oper[1]^.reg := CurrentReg;
  2995. if ((TargetRef.offset mod 16) = 8) and
  2996. (
  2997. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2998. (TargetRef.base = current_procinfo.framepointer) or
  2999. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3000. ) then
  3001. taicpu(hp1).opcode := MovAligned
  3002. else
  3003. taicpu(hp1).opcode := MovUnaligned;
  3004. taicpu(hp1).opsize := S_XMM;
  3005. taicpu(hp1).oper[0]^.reg := CurrentReg;
  3006. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3007. RemoveInstruction(hp2);
  3008. RemoveInstruction(hp3);
  3009. Result := True;
  3010. Exit;
  3011. end;
  3012. end;
  3013. end
  3014. else
  3015. begin
  3016. { See if the next references are 8 less rather than 8 greater }
  3017. Dec(SourceRef.offset, 16); { -8 the other way }
  3018. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3019. begin
  3020. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3021. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3022. if GetNextInstruction(hp2, hp3) and
  3023. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3024. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3025. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3026. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3027. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3028. begin
  3029. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3030. if CurrentReg <> NR_NO then
  3031. begin
  3032. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3033. if ((SourceRef.offset mod 16) = 0) and
  3034. (
  3035. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3036. (SourceRef.base = current_procinfo.framepointer) or
  3037. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3038. ) then
  3039. taicpu(hp2).opcode := MovAligned
  3040. else
  3041. taicpu(hp2).opcode := MovUnaligned;
  3042. taicpu(hp2).opsize := S_XMM;
  3043. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3044. if ((TargetRef.offset mod 16) = 0) and
  3045. (
  3046. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3047. (TargetRef.base = current_procinfo.framepointer) or
  3048. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3049. ) then
  3050. taicpu(hp3).opcode := MovAligned
  3051. else
  3052. taicpu(hp3).opcode := MovUnaligned;
  3053. taicpu(hp3).opsize := S_XMM;
  3054. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3055. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3056. RemoveInstruction(hp1);
  3057. RemoveCurrentP(p, hp2);
  3058. Result := True;
  3059. Exit;
  3060. end;
  3061. end;
  3062. end;
  3063. end;
  3064. end;
  3065. {$endif x86_64}
  3066. end;
  3067. else
  3068. { The write target should be a reg or a ref }
  3069. InternalError(2021091601);
  3070. end;
  3071. else
  3072. ;
  3073. end
  3074. else
  3075. { %treg is used afterwards, but all eventualities
  3076. other than the first MOV instruction being a constant
  3077. are covered by DeepMOVOpt, so only check for that }
  3078. if (taicpu(p).oper[0]^.typ = top_const) and
  3079. (
  3080. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3081. not (cs_opt_size in current_settings.optimizerswitches) or
  3082. (taicpu(hp1).opsize = S_B)
  3083. ) and
  3084. (
  3085. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3086. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3087. ) then
  3088. begin
  3089. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3090. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3091. end;
  3092. end;
  3093. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3094. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3095. { mov reg1, mem1 or mov mem1, reg1
  3096. mov mem2, reg2 mov reg2, mem2}
  3097. begin
  3098. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3099. { mov reg1, mem1 or mov mem1, reg1
  3100. mov mem2, reg1 mov reg2, mem1}
  3101. begin
  3102. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3103. { Removes the second statement from
  3104. mov reg1, mem1/reg2
  3105. mov mem1/reg2, reg1 }
  3106. begin
  3107. if taicpu(p).oper[0]^.typ=top_reg then
  3108. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3109. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3110. RemoveInstruction(hp1);
  3111. Result:=true;
  3112. exit;
  3113. end
  3114. else
  3115. begin
  3116. TransferUsedRegs(TmpUsedRegs);
  3117. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3118. if (taicpu(p).oper[1]^.typ = top_ref) and
  3119. { mov reg1, mem1
  3120. mov mem2, reg1 }
  3121. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3122. GetNextInstruction(hp1, hp2) and
  3123. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3124. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3125. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3126. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3127. { change to
  3128. mov reg1, mem1 mov reg1, mem1
  3129. mov mem2, reg1 cmp reg1, mem2
  3130. cmp mem1, reg1
  3131. }
  3132. begin
  3133. RemoveInstruction(hp2);
  3134. taicpu(hp1).opcode := A_CMP;
  3135. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3136. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3137. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3138. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3139. end;
  3140. end;
  3141. end
  3142. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3143. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3144. begin
  3145. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3146. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3147. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3148. end
  3149. else
  3150. begin
  3151. TransferUsedRegs(TmpUsedRegs);
  3152. if GetNextInstruction(hp1, hp2) and
  3153. MatchOpType(taicpu(p),top_ref,top_reg) and
  3154. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3155. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3156. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3157. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3158. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3159. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3160. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3161. { mov mem1, %reg1
  3162. mov %reg1, mem2
  3163. mov mem2, reg2
  3164. to:
  3165. mov mem1, reg2
  3166. mov reg2, mem2}
  3167. begin
  3168. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3169. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3170. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3171. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3172. RemoveInstruction(hp2);
  3173. Result := True;
  3174. end
  3175. {$ifdef i386}
  3176. { this is enabled for i386 only, as the rules to create the reg sets below
  3177. are too complicated for x86-64, so this makes this code too error prone
  3178. on x86-64
  3179. }
  3180. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3181. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3182. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3183. { mov mem1, reg1 mov mem1, reg1
  3184. mov reg1, mem2 mov reg1, mem2
  3185. mov mem2, reg2 mov mem2, reg1
  3186. to: to:
  3187. mov mem1, reg1 mov mem1, reg1
  3188. mov mem1, reg2 mov reg1, mem2
  3189. mov reg1, mem2
  3190. or (if mem1 depends on reg1
  3191. and/or if mem2 depends on reg2)
  3192. to:
  3193. mov mem1, reg1
  3194. mov reg1, mem2
  3195. mov reg1, reg2
  3196. }
  3197. begin
  3198. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3199. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3200. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3201. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3202. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3203. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3204. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3205. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3206. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3207. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3208. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3209. end
  3210. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3211. begin
  3212. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3213. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3214. end
  3215. else
  3216. begin
  3217. RemoveInstruction(hp2);
  3218. end
  3219. {$endif i386}
  3220. ;
  3221. end;
  3222. end
  3223. { movl [mem1],reg1
  3224. movl [mem1],reg2
  3225. to
  3226. movl [mem1],reg1
  3227. movl reg1,reg2
  3228. }
  3229. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3230. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3231. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3232. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3233. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3234. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3235. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3236. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3237. begin
  3238. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3239. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3240. end;
  3241. { movl const1,[mem1]
  3242. movl [mem1],reg1
  3243. to
  3244. movl const1,reg1
  3245. movl reg1,[mem1]
  3246. }
  3247. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3248. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3249. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3250. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3251. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3252. begin
  3253. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3254. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3255. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3256. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3257. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3258. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3259. Result:=true;
  3260. exit;
  3261. end;
  3262. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3263. { Change:
  3264. movl %reg1,%reg2
  3265. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3266. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3267. To:
  3268. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3269. movl x(%reg1),%reg1
  3270. movl %reg1,%regX
  3271. }
  3272. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3273. begin
  3274. CurrentReg := taicpu(p).oper[0]^.reg;
  3275. ActiveReg := taicpu(p).oper[1]^.reg;
  3276. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3277. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3278. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3279. GetNextInstruction(hp1, hp2) and
  3280. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3281. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3282. begin
  3283. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3284. if RegInRef(ActiveReg, SourceRef) and
  3285. { If %reg1 also appears in the second reference, then it will
  3286. not refer to the same memory block as the first reference }
  3287. not RegInRef(CurrentReg, SourceRef) then
  3288. begin
  3289. { Check to see if the references match if %reg2 is changed to %reg1 }
  3290. if SourceRef.base = ActiveReg then
  3291. SourceRef.base := CurrentReg;
  3292. if SourceRef.index = ActiveReg then
  3293. SourceRef.index := CurrentReg;
  3294. { RefsEqual also checks to ensure both references are non-volatile }
  3295. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3296. begin
  3297. taicpu(hp2).loadreg(0, CurrentReg);
  3298. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3299. Result := True;
  3300. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3301. begin
  3302. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3303. RemoveCurrentP(p, hp1);
  3304. Exit;
  3305. end
  3306. else
  3307. begin
  3308. { Check to see if %reg2 is no longer in use }
  3309. TransferUsedRegs(TmpUsedRegs);
  3310. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3311. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3312. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3313. begin
  3314. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3315. RemoveCurrentP(p, hp1);
  3316. Exit;
  3317. end;
  3318. end;
  3319. { If we reach this point, p and hp1 weren't actually modified,
  3320. so we can do a bit more work on this pass }
  3321. end;
  3322. end;
  3323. end;
  3324. end;
  3325. end;
  3326. { search further than the next instruction for a mov (as long as it's not a jump) }
  3327. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3328. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3329. (taicpu(p).oper[1]^.typ = top_reg) and
  3330. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3331. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3332. begin
  3333. { we work with hp2 here, so hp1 can be still used later on when
  3334. checking for GetNextInstruction_p }
  3335. hp3 := hp1;
  3336. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3337. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3338. { Saves on a large number of dereferences }
  3339. ActiveReg := taicpu(p).oper[1]^.reg;
  3340. TransferUsedRegs(TmpUsedRegs);
  3341. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3342. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3343. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3344. (hp2.typ=ait_instruction) do
  3345. begin
  3346. case taicpu(hp2).opcode of
  3347. A_POP:
  3348. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3349. begin
  3350. if not CrossJump and
  3351. not RegUsedBetween(ActiveReg, p, hp2) then
  3352. begin
  3353. { We can remove the original MOV since the register
  3354. wasn't used between it and its popping from the stack }
  3355. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3356. RemoveCurrentp(p, hp1);
  3357. Result := True;
  3358. Exit;
  3359. end;
  3360. { Can't go any further }
  3361. Break;
  3362. end;
  3363. A_MOV:
  3364. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3365. ((taicpu(p).oper[0]^.typ=top_const) or
  3366. ((taicpu(p).oper[0]^.typ=top_reg) and
  3367. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3368. )
  3369. ) then
  3370. begin
  3371. { we have
  3372. mov x, %treg
  3373. mov %treg, y
  3374. }
  3375. { We don't need to call UpdateUsedRegs for every instruction between
  3376. p and hp2 because the register we're concerned about will not
  3377. become deallocated (otherwise GetNextInstructionUsingReg would
  3378. have stopped at an earlier instruction). [Kit] }
  3379. TempRegUsed :=
  3380. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3381. RegReadByInstruction(ActiveReg, hp3) or
  3382. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3383. case taicpu(p).oper[0]^.typ Of
  3384. top_reg:
  3385. begin
  3386. { change
  3387. mov %reg, %treg
  3388. mov %treg, y
  3389. to
  3390. mov %reg, y
  3391. }
  3392. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3393. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3394. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3395. begin
  3396. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3397. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3398. if TempRegUsed then
  3399. begin
  3400. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3401. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3402. { Set the start of the next GetNextInstructionUsingRegCond search
  3403. to start at the entry right before hp2 (which is about to be removed) }
  3404. hp3 := tai(hp2.Previous);
  3405. RemoveInstruction(hp2);
  3406. { See if there's more we can optimise }
  3407. Continue;
  3408. end
  3409. else
  3410. begin
  3411. RemoveInstruction(hp2);
  3412. { We can remove the original MOV too }
  3413. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3414. RemoveCurrentP(p, hp1);
  3415. Result:=true;
  3416. Exit;
  3417. end;
  3418. end
  3419. else
  3420. begin
  3421. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3422. taicpu(hp2).loadReg(0, CurrentReg);
  3423. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3424. { Check to see if the register also appears in the reference }
  3425. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3426. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3427. { Don't remove the first instruction if the temporary register is in use }
  3428. if not TempRegUsed and
  3429. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3430. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3431. begin
  3432. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3433. RemoveCurrentP(p, hp1);
  3434. Result:=true;
  3435. Exit;
  3436. end;
  3437. { No need to set Result to True here. If there's another instruction later
  3438. on that can be optimised, it will be detected when the main Pass 1 loop
  3439. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3440. end;
  3441. end;
  3442. top_const:
  3443. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3444. begin
  3445. { change
  3446. mov const, %treg
  3447. mov %treg, y
  3448. to
  3449. mov const, y
  3450. }
  3451. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3452. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3453. begin
  3454. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3455. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3456. if TempRegUsed then
  3457. begin
  3458. { Don't remove the first instruction if the temporary register is in use }
  3459. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3460. { No need to set Result to True. If there's another instruction later on
  3461. that can be optimised, it will be detected when the main Pass 1 loop
  3462. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3463. end
  3464. else
  3465. begin
  3466. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3467. RemoveCurrentP(p, hp1);
  3468. Result:=true;
  3469. Exit;
  3470. end;
  3471. end;
  3472. end;
  3473. else
  3474. Internalerror(2019103001);
  3475. end;
  3476. end
  3477. else
  3478. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3479. begin
  3480. if not CrossJump and
  3481. not RegUsedBetween(ActiveReg, p, hp2) and
  3482. not RegReadByInstruction(ActiveReg, hp2) then
  3483. begin
  3484. { Register is not used before it is overwritten }
  3485. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3486. RemoveCurrentp(p, hp1);
  3487. Result := True;
  3488. Exit;
  3489. end;
  3490. if (taicpu(p).oper[0]^.typ = top_const) and
  3491. (taicpu(hp2).oper[0]^.typ = top_const) then
  3492. begin
  3493. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3494. begin
  3495. { Same value - register hasn't changed }
  3496. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3497. RemoveInstruction(hp2);
  3498. Result := True;
  3499. { See if there's more we can optimise }
  3500. Continue;
  3501. end;
  3502. end;
  3503. end;
  3504. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3505. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3506. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3507. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3508. begin
  3509. {
  3510. Change from:
  3511. mov ###, %reg
  3512. ...
  3513. movs/z %reg,%reg (Same register, just different sizes)
  3514. To:
  3515. movs/z ###, %reg (Longer version)
  3516. ...
  3517. (remove)
  3518. }
  3519. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3520. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3521. { Keep the first instruction as mov if ### is a constant }
  3522. if taicpu(p).oper[0]^.typ = top_const then
  3523. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3524. else
  3525. begin
  3526. taicpu(p).opcode := taicpu(hp2).opcode;
  3527. taicpu(p).opsize := taicpu(hp2).opsize;
  3528. end;
  3529. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3530. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3531. RemoveInstruction(hp2);
  3532. Result := True;
  3533. Exit;
  3534. end;
  3535. else
  3536. { Move down to the MatchOpType if-block below };
  3537. end;
  3538. { Also catches MOV/S/Z instructions that aren't modified }
  3539. if taicpu(p).oper[0]^.typ = top_reg then
  3540. begin
  3541. CurrentReg := taicpu(p).oper[0]^.reg;
  3542. if
  3543. not RegModifiedByInstruction(CurrentReg, hp3) and
  3544. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3545. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3546. begin
  3547. Result := True;
  3548. { Just in case something didn't get modified (e.g. an
  3549. implicit register). Also, if it does read from this
  3550. register, then there's no longer an advantage to
  3551. changing the register on subsequent instructions.}
  3552. if not RegReadByInstruction(ActiveReg, hp2) then
  3553. begin
  3554. { If a conditional jump was crossed, do not delete
  3555. the original MOV no matter what }
  3556. if not CrossJump and
  3557. { RegEndOfLife returns True if the register is
  3558. deallocated before the next instruction or has
  3559. been loaded with a new value }
  3560. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3561. begin
  3562. { We can remove the original MOV }
  3563. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3564. RemoveCurrentp(p, hp1);
  3565. Exit;
  3566. end;
  3567. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3568. begin
  3569. { See if there's more we can optimise }
  3570. hp3 := hp2;
  3571. Continue;
  3572. end;
  3573. end;
  3574. end;
  3575. end;
  3576. { Break out of the while loop under normal circumstances }
  3577. Break;
  3578. end;
  3579. end;
  3580. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3581. (taicpu(p).oper[1]^.typ = top_reg) and
  3582. (taicpu(p).opsize = S_L) and
  3583. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3584. (taicpu(hp2).opcode = A_AND) and
  3585. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3586. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3587. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3588. ) then
  3589. begin
  3590. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3591. begin
  3592. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3593. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3594. begin
  3595. { Optimize out:
  3596. mov x, %reg
  3597. and ffffffffh, %reg
  3598. }
  3599. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3600. RemoveInstruction(hp2);
  3601. Result:=true;
  3602. exit;
  3603. end;
  3604. end;
  3605. end;
  3606. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3607. x >= RetOffset) as it doesn't do anything (it writes either to a
  3608. parameter or to the temporary storage room for the function
  3609. result)
  3610. }
  3611. if IsExitCode(hp1) and
  3612. (taicpu(p).oper[1]^.typ = top_ref) and
  3613. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3614. (
  3615. (
  3616. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3617. not (
  3618. assigned(current_procinfo.procdef.funcretsym) and
  3619. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3620. )
  3621. ) or
  3622. { Also discard writes to the stack that are below the base pointer,
  3623. as this is temporary storage rather than a function result on the
  3624. stack, say. }
  3625. (
  3626. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3627. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3628. )
  3629. ) then
  3630. begin
  3631. RemoveCurrentp(p, hp1);
  3632. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3633. RemoveLastDeallocForFuncRes(p);
  3634. Result:=true;
  3635. exit;
  3636. end;
  3637. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3638. begin
  3639. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3640. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3641. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3642. begin
  3643. { change
  3644. mov reg1, mem1
  3645. test/cmp x, mem1
  3646. to
  3647. mov reg1, mem1
  3648. test/cmp x, reg1
  3649. }
  3650. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3651. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3652. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3653. Result := True;
  3654. Exit;
  3655. end;
  3656. if DoMovCmpMemOpt(p, hp1, True) then
  3657. begin
  3658. Result := True;
  3659. Exit;
  3660. end;
  3661. end;
  3662. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3663. { If the flags register is in use, don't change the instruction to an
  3664. ADD otherwise this will scramble the flags. [Kit] }
  3665. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3666. begin
  3667. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3668. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3669. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3670. ) or
  3671. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3672. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3673. )
  3674. ) then
  3675. { mov reg1,ref
  3676. lea reg2,[reg1,reg2]
  3677. to
  3678. add reg2,ref}
  3679. begin
  3680. TransferUsedRegs(TmpUsedRegs);
  3681. { reg1 may not be used afterwards }
  3682. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3683. begin
  3684. Taicpu(hp1).opcode:=A_ADD;
  3685. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3686. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3687. RemoveCurrentp(p, hp1);
  3688. result:=true;
  3689. exit;
  3690. end;
  3691. end;
  3692. { If the LEA instruction can be converted into an arithmetic instruction,
  3693. it may be possible to then fold it in the next optimisation, otherwise
  3694. there's nothing more that can be optimised here. }
  3695. if not ConvertLEA(taicpu(hp1)) then
  3696. Exit;
  3697. end;
  3698. if (taicpu(p).oper[1]^.typ = top_reg) and
  3699. (hp1.typ = ait_instruction) and
  3700. GetNextInstruction(hp1, hp2) and
  3701. MatchInstruction(hp2,A_MOV,[]) and
  3702. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3703. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3704. (
  3705. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3706. {$ifdef x86_64}
  3707. or
  3708. (
  3709. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3710. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3711. )
  3712. {$endif x86_64}
  3713. ) then
  3714. begin
  3715. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3716. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3717. { change movsX/movzX reg/ref, reg2
  3718. add/sub/or/... reg3/$const, reg2
  3719. mov reg2 reg/ref
  3720. dealloc reg2
  3721. to
  3722. add/sub/or/... reg3/$const, reg/ref }
  3723. begin
  3724. TransferUsedRegs(TmpUsedRegs);
  3725. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3726. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3727. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3728. begin
  3729. { by example:
  3730. movswl %si,%eax movswl %si,%eax p
  3731. decl %eax addl %edx,%eax hp1
  3732. movw %ax,%si movw %ax,%si hp2
  3733. ->
  3734. movswl %si,%eax movswl %si,%eax p
  3735. decw %eax addw %edx,%eax hp1
  3736. movw %ax,%si movw %ax,%si hp2
  3737. }
  3738. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3739. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3740. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3741. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3742. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3743. {
  3744. ->
  3745. movswl %si,%eax movswl %si,%eax p
  3746. decw %si addw %dx,%si hp1
  3747. movw %ax,%si movw %ax,%si hp2
  3748. }
  3749. case taicpu(hp1).ops of
  3750. 1:
  3751. begin
  3752. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3753. if taicpu(hp1).oper[0]^.typ=top_reg then
  3754. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3755. end;
  3756. 2:
  3757. begin
  3758. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3759. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3760. (taicpu(hp1).opcode<>A_SHL) and
  3761. (taicpu(hp1).opcode<>A_SHR) and
  3762. (taicpu(hp1).opcode<>A_SAR) then
  3763. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3764. end;
  3765. else
  3766. internalerror(2008042701);
  3767. end;
  3768. {
  3769. ->
  3770. decw %si addw %dx,%si p
  3771. }
  3772. RemoveInstruction(hp2);
  3773. RemoveCurrentP(p, hp1);
  3774. Result:=True;
  3775. Exit;
  3776. end;
  3777. end;
  3778. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3779. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3780. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3781. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3782. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3783. )
  3784. {$ifdef i386}
  3785. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3786. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3787. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3788. {$endif i386}
  3789. then
  3790. { change movsX/movzX reg/ref, reg2
  3791. add/sub/or/... regX/$const, reg2
  3792. mov reg2, reg3
  3793. dealloc reg2
  3794. to
  3795. movsX/movzX reg/ref, reg3
  3796. add/sub/or/... reg3/$const, reg3
  3797. }
  3798. begin
  3799. TransferUsedRegs(TmpUsedRegs);
  3800. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3801. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3802. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3803. begin
  3804. { by example:
  3805. movswl %si,%eax movswl %si,%eax p
  3806. decl %eax addl %edx,%eax hp1
  3807. movw %ax,%si movw %ax,%si hp2
  3808. ->
  3809. movswl %si,%eax movswl %si,%eax p
  3810. decw %eax addw %edx,%eax hp1
  3811. movw %ax,%si movw %ax,%si hp2
  3812. }
  3813. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3814. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3815. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3816. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3817. { limit size of constants as well to avoid assembler errors, but
  3818. check opsize to avoid overflow when left shifting the 1 }
  3819. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3820. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3821. {$ifdef x86_64}
  3822. { Be careful of, for example:
  3823. movl %reg1,%reg2
  3824. addl %reg3,%reg2
  3825. movq %reg2,%reg4
  3826. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3827. }
  3828. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3829. begin
  3830. taicpu(hp2).changeopsize(S_L);
  3831. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3832. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3833. end;
  3834. {$endif x86_64}
  3835. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3836. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3837. if taicpu(p).oper[0]^.typ=top_reg then
  3838. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3839. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3840. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3841. {
  3842. ->
  3843. movswl %si,%eax movswl %si,%eax p
  3844. decw %si addw %dx,%si hp1
  3845. movw %ax,%si movw %ax,%si hp2
  3846. }
  3847. case taicpu(hp1).ops of
  3848. 1:
  3849. begin
  3850. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3851. if taicpu(hp1).oper[0]^.typ=top_reg then
  3852. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3853. end;
  3854. 2:
  3855. begin
  3856. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3857. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3858. (taicpu(hp1).opcode<>A_SHL) and
  3859. (taicpu(hp1).opcode<>A_SHR) and
  3860. (taicpu(hp1).opcode<>A_SAR) then
  3861. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3862. end;
  3863. else
  3864. internalerror(2018111801);
  3865. end;
  3866. {
  3867. ->
  3868. decw %si addw %dx,%si p
  3869. }
  3870. RemoveInstruction(hp2);
  3871. end;
  3872. end;
  3873. end;
  3874. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3875. GetNextInstruction(hp1, hp2) and
  3876. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3877. MatchOperand(Taicpu(p).oper[0]^,0) and
  3878. (Taicpu(p).oper[1]^.typ = top_reg) and
  3879. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3880. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3881. { mov reg1,0
  3882. bts reg1,operand1 --> mov reg1,operand2
  3883. or reg1,operand2 bts reg1,operand1}
  3884. begin
  3885. Taicpu(hp2).opcode:=A_MOV;
  3886. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3887. asml.remove(hp1);
  3888. insertllitem(hp2,hp2.next,hp1);
  3889. RemoveCurrentp(p, hp1);
  3890. Result:=true;
  3891. exit;
  3892. end;
  3893. {
  3894. mov ref,reg0
  3895. <op> reg0,reg1
  3896. dealloc reg0
  3897. to
  3898. <op> ref,reg1
  3899. }
  3900. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3901. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3902. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3903. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3904. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3905. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3906. begin
  3907. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3908. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3909. RemoveCurrentp(p, hp1);
  3910. Result:=true;
  3911. exit;
  3912. end;
  3913. {$ifdef x86_64}
  3914. { Convert:
  3915. movq x(ref),%reg64
  3916. shrq y,%reg64
  3917. To:
  3918. movl x+4(ref),%reg32
  3919. shrl y-32,%reg32 (Remove if y = 32)
  3920. }
  3921. if (taicpu(p).opsize = S_Q) and
  3922. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3923. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3924. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3925. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3926. (taicpu(hp1).oper[0]^.val >= 32) and
  3927. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3928. begin
  3929. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3930. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3931. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3932. { Convert to 32-bit }
  3933. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3934. taicpu(p).opsize := S_L;
  3935. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3936. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3937. if (taicpu(hp1).oper[0]^.val = 32) then
  3938. begin
  3939. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3940. RemoveInstruction(hp1);
  3941. end
  3942. else
  3943. begin
  3944. { This will potentially open up more arithmetic operations since
  3945. the peephole optimizer now has a big hint that only the lower
  3946. 32 bits are currently in use (and opcodes are smaller in size) }
  3947. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3948. taicpu(hp1).opsize := S_L;
  3949. Dec(taicpu(hp1).oper[0]^.val, 32);
  3950. DebugMsg(SPeepholeOptimization + PreMessage +
  3951. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3952. end;
  3953. Result := True;
  3954. Exit;
  3955. end;
  3956. {$endif x86_64}
  3957. { Backward optimisation. If we have:
  3958. func. %reg1,%reg2
  3959. mov %reg2,%reg3
  3960. (dealloc %reg2)
  3961. Change to:
  3962. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3963. }
  3964. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3965. begin
  3966. CurrentReg := taicpu(p).oper[0]^.reg;
  3967. ActiveReg := taicpu(p).oper[1]^.reg;
  3968. TransferUsedRegs(TmpUsedRegs);
  3969. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3970. GetLastInstruction(p, hp2) and
  3971. (hp2.typ = ait_instruction) and
  3972. { Have to make sure it's an instruction that only reads from
  3973. operand 1 and only writes (not reads or modifies) from operand 2;
  3974. in essence, a one-operand pure function such as BSR or POPCNT }
  3975. (taicpu(hp2).ops = 2) and
  3976. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3977. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3978. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3979. begin
  3980. case taicpu(hp2).opcode of
  3981. A_FSTSW, A_FNSTSW,
  3982. A_IN, A_INS, A_OUT, A_OUTS,
  3983. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3984. { These routines have explicit operands, but they are restricted in
  3985. what they can be (e.g. IN and OUT can only read from AL, AX or
  3986. EAX. }
  3987. A_CMOVcc:
  3988. { CMOV is not valid either because then CurrentReg will depend
  3989. on an unknown value if the condition is False and hence is
  3990. not a pure write }
  3991. ;
  3992. else
  3993. begin
  3994. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3995. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3996. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3997. RemoveCurrentp(p, hp1);
  3998. Result := True;
  3999. Exit;
  4000. end;
  4001. end;
  4002. end;
  4003. end;
  4004. end;
  4005. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4006. var
  4007. hp1 : tai;
  4008. begin
  4009. Result:=false;
  4010. if taicpu(p).ops <> 2 then
  4011. exit;
  4012. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4013. GetNextInstruction(p,hp1) then
  4014. begin
  4015. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4016. (taicpu(hp1).ops = 2) then
  4017. begin
  4018. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4019. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4020. { movXX reg1, mem1 or movXX mem1, reg1
  4021. movXX mem2, reg2 movXX reg2, mem2}
  4022. begin
  4023. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4024. { movXX reg1, mem1 or movXX mem1, reg1
  4025. movXX mem2, reg1 movXX reg2, mem1}
  4026. begin
  4027. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4028. begin
  4029. { Removes the second statement from
  4030. movXX reg1, mem1/reg2
  4031. movXX mem1/reg2, reg1
  4032. }
  4033. if taicpu(p).oper[0]^.typ=top_reg then
  4034. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4035. { Removes the second statement from
  4036. movXX mem1/reg1, reg2
  4037. movXX reg2, mem1/reg1
  4038. }
  4039. if (taicpu(p).oper[1]^.typ=top_reg) and
  4040. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4041. begin
  4042. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4043. RemoveInstruction(hp1);
  4044. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4045. Result:=true;
  4046. exit;
  4047. end
  4048. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4049. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4050. begin
  4051. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4052. RemoveInstruction(hp1);
  4053. Result:=true;
  4054. exit;
  4055. end;
  4056. end
  4057. end;
  4058. end;
  4059. end;
  4060. end;
  4061. end;
  4062. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4063. var
  4064. hp1 : tai;
  4065. begin
  4066. result:=false;
  4067. { replace
  4068. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4069. MovX %mreg2,%mreg1
  4070. dealloc %mreg2
  4071. by
  4072. <Op>X %mreg2,%mreg1
  4073. ?
  4074. }
  4075. if GetNextInstruction(p,hp1) and
  4076. { we mix single and double opperations here because we assume that the compiler
  4077. generates vmovapd only after double operations and vmovaps only after single operations }
  4078. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4079. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4080. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4081. (taicpu(p).oper[0]^.typ=top_reg) then
  4082. begin
  4083. TransferUsedRegs(TmpUsedRegs);
  4084. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4085. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4086. begin
  4087. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4088. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4089. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4090. RemoveInstruction(hp1);
  4091. result:=true;
  4092. end;
  4093. end;
  4094. end;
  4095. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4096. var
  4097. hp1, p_label, p_dist, hp1_dist: tai;
  4098. JumpLabel, JumpLabel_dist: TAsmLabel;
  4099. FirstValue, SecondValue: TCGInt;
  4100. begin
  4101. Result := False;
  4102. if (taicpu(p).oper[0]^.typ = top_const) and
  4103. (taicpu(p).oper[0]^.val <> -1) then
  4104. begin
  4105. { Convert unsigned maximum constants to -1 to aid optimisation }
  4106. case taicpu(p).opsize of
  4107. S_B:
  4108. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4109. begin
  4110. taicpu(p).oper[0]^.val := -1;
  4111. Result := True;
  4112. Exit;
  4113. end;
  4114. S_W:
  4115. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4116. begin
  4117. taicpu(p).oper[0]^.val := -1;
  4118. Result := True;
  4119. Exit;
  4120. end;
  4121. S_L:
  4122. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4123. begin
  4124. taicpu(p).oper[0]^.val := -1;
  4125. Result := True;
  4126. Exit;
  4127. end;
  4128. {$ifdef x86_64}
  4129. S_Q:
  4130. { Storing anything greater than $7FFFFFFF is not possible so do
  4131. nothing };
  4132. {$endif x86_64}
  4133. else
  4134. InternalError(2021121001);
  4135. end;
  4136. end;
  4137. if GetNextInstruction(p, hp1) and
  4138. TrySwapMovCmp(p, hp1) then
  4139. begin
  4140. Result := True;
  4141. Exit;
  4142. end;
  4143. { Search for:
  4144. test $x,(reg/ref)
  4145. jne @lbl1
  4146. test $y,(reg/ref) (same register or reference)
  4147. jne @lbl1
  4148. Change to:
  4149. test $(x or y),(reg/ref)
  4150. jne @lbl1
  4151. (Note, this doesn't work with je instead of jne)
  4152. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4153. Also search for:
  4154. test $x,(reg/ref)
  4155. je @lbl1
  4156. test $y,(reg/ref)
  4157. je/jne @lbl2
  4158. If (x or y) = x, then the second jump is deterministic
  4159. }
  4160. if (
  4161. (
  4162. (taicpu(p).oper[0]^.typ = top_const) or
  4163. (
  4164. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4165. (taicpu(p).oper[0]^.typ = top_reg) and
  4166. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4167. )
  4168. ) and
  4169. MatchInstruction(hp1, A_JCC, [])
  4170. ) then
  4171. begin
  4172. if (taicpu(p).oper[0]^.typ = top_reg) and
  4173. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4174. FirstValue := -1
  4175. else
  4176. FirstValue := taicpu(p).oper[0]^.val;
  4177. { If we have several test/jne's in a row, it might be the case that
  4178. the second label doesn't go to the same location, but the one
  4179. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4180. so accommodate for this with a while loop.
  4181. }
  4182. hp1_dist := hp1;
  4183. if GetNextInstruction(hp1, p_dist) and
  4184. (p_dist.typ = ait_instruction) and
  4185. (
  4186. (
  4187. (taicpu(p_dist).opcode = A_TEST) and
  4188. (
  4189. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4190. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4191. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4192. )
  4193. ) or
  4194. (
  4195. { cmp 0,%reg = test %reg,%reg }
  4196. (taicpu(p_dist).opcode = A_CMP) and
  4197. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4198. )
  4199. ) and
  4200. { Make sure the destination operands are actually the same }
  4201. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4202. GetNextInstruction(p_dist, hp1_dist) and
  4203. MatchInstruction(hp1_dist, A_JCC, []) then
  4204. begin
  4205. if
  4206. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4207. (
  4208. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4209. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4210. ) then
  4211. SecondValue := -1
  4212. else
  4213. SecondValue := taicpu(p_dist).oper[0]^.val;
  4214. { If both of the TEST constants are identical, delete the second
  4215. TEST that is unnecessary. }
  4216. if (FirstValue = SecondValue) then
  4217. begin
  4218. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4219. RemoveInstruction(p_dist);
  4220. { Don't let the flags register become deallocated and reallocated between the jumps }
  4221. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4222. Result := True;
  4223. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4224. begin
  4225. { Since the second jump's condition is a subset of the first, we
  4226. know it will never branch because the first jump dominates it.
  4227. Get it out of the way now rather than wait for the jump
  4228. optimisations for a speed boost. }
  4229. if IsJumpToLabel(taicpu(hp1_dist)) then
  4230. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4231. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4232. RemoveInstruction(hp1_dist);
  4233. end
  4234. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4235. begin
  4236. { If the inverse of the first condition is a subset of the second,
  4237. the second one will definitely branch if the first one doesn't }
  4238. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4239. MakeUnconditional(taicpu(hp1_dist));
  4240. RemoveDeadCodeAfterJump(hp1_dist);
  4241. end;
  4242. Exit;
  4243. end;
  4244. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4245. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4246. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4247. then the second jump will never branch, so it can also be
  4248. removed regardless of where it goes }
  4249. (
  4250. (FirstValue = -1) or
  4251. (SecondValue = -1) or
  4252. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4253. ) then
  4254. begin
  4255. { Same jump location... can be a register since nothing's changed }
  4256. { If any of the entries are equivalent to test %reg,%reg, then the
  4257. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4258. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4259. if IsJumpToLabel(taicpu(hp1_dist)) then
  4260. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4261. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4262. RemoveInstruction(hp1_dist);
  4263. { Only remove the second test if no jumps or other conditional instructions follow }
  4264. TransferUsedRegs(TmpUsedRegs);
  4265. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4266. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4267. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4268. RemoveInstruction(p_dist);
  4269. Result := True;
  4270. Exit;
  4271. end;
  4272. end;
  4273. end;
  4274. { Search for:
  4275. test %reg,%reg
  4276. j(c1) @lbl1
  4277. ...
  4278. @lbl:
  4279. test %reg,%reg (same register)
  4280. j(c2) @lbl2
  4281. If c2 is a subset of c1, change to:
  4282. test %reg,%reg
  4283. j(c1) @lbl2
  4284. (@lbl1 may become a dead label as a result)
  4285. }
  4286. if (taicpu(p).oper[1]^.typ = top_reg) and
  4287. (taicpu(p).oper[0]^.typ = top_reg) and
  4288. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4289. MatchInstruction(hp1, A_JCC, []) and
  4290. IsJumpToLabel(taicpu(hp1)) then
  4291. begin
  4292. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4293. p_label := nil;
  4294. if Assigned(JumpLabel) then
  4295. p_label := getlabelwithsym(JumpLabel);
  4296. if Assigned(p_label) and
  4297. GetNextInstruction(p_label, p_dist) and
  4298. MatchInstruction(p_dist, A_TEST, []) and
  4299. { It's fine if the second test uses smaller sub-registers }
  4300. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4301. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4302. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4303. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4304. GetNextInstruction(p_dist, hp1_dist) and
  4305. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4306. begin
  4307. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4308. if JumpLabel = JumpLabel_dist then
  4309. { This is an infinite loop }
  4310. Exit;
  4311. { Best optimisation when the first condition is a subset (or equal) of the second }
  4312. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4313. begin
  4314. { Any registers used here will already be allocated }
  4315. if Assigned(JumpLabel_dist) then
  4316. JumpLabel_dist.IncRefs;
  4317. if Assigned(JumpLabel) then
  4318. JumpLabel.DecRefs;
  4319. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4320. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4321. Result := True;
  4322. Exit;
  4323. end;
  4324. end;
  4325. end;
  4326. end;
  4327. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4328. var
  4329. hp1, hp2: tai;
  4330. ActiveReg: TRegister;
  4331. OldOffset: asizeint;
  4332. ThisConst: TCGInt;
  4333. function RegDeallocated: Boolean;
  4334. begin
  4335. TransferUsedRegs(TmpUsedRegs);
  4336. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4337. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4338. end;
  4339. begin
  4340. result:=false;
  4341. hp1 := nil;
  4342. { replace
  4343. addX const,%reg1
  4344. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4345. dealloc %reg1
  4346. by
  4347. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4348. }
  4349. if MatchOpType(taicpu(p),top_const,top_reg) then
  4350. begin
  4351. ActiveReg := taicpu(p).oper[1]^.reg;
  4352. { Ensures the entire register was updated }
  4353. if (taicpu(p).opsize >= S_L) and
  4354. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4355. MatchInstruction(hp1,A_LEA,[]) and
  4356. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4357. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4358. (
  4359. { Cover the case where the register in the reference is also the destination register }
  4360. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4361. (
  4362. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4363. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4364. RegDeallocated
  4365. )
  4366. ) then
  4367. begin
  4368. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4369. {$push}
  4370. {$R-}{$Q-}
  4371. { Explicitly disable overflow checking for these offset calculation
  4372. as those do not matter for the final result }
  4373. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4374. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4375. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4376. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4377. {$pop}
  4378. {$ifdef x86_64}
  4379. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4380. begin
  4381. { Overflow; abort }
  4382. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4383. end
  4384. else
  4385. {$endif x86_64}
  4386. begin
  4387. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4388. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4389. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4390. RemoveCurrentP(p, hp1)
  4391. else
  4392. RemoveCurrentP(p);
  4393. result:=true;
  4394. Exit;
  4395. end;
  4396. end;
  4397. if (
  4398. { Save calling GetNextInstructionUsingReg again }
  4399. Assigned(hp1) or
  4400. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4401. ) and
  4402. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4403. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4404. begin
  4405. if taicpu(hp1).oper[0]^.typ = top_const then
  4406. begin
  4407. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4408. if taicpu(hp1).opcode = A_ADD then
  4409. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4410. else
  4411. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4412. Result := True;
  4413. { Handle any overflows }
  4414. case taicpu(p).opsize of
  4415. S_B:
  4416. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4417. S_W:
  4418. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4419. S_L:
  4420. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4421. {$ifdef x86_64}
  4422. S_Q:
  4423. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4424. { Overflow; abort }
  4425. Result := False
  4426. else
  4427. taicpu(p).oper[0]^.val := ThisConst;
  4428. {$endif x86_64}
  4429. else
  4430. InternalError(2021102610);
  4431. end;
  4432. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4433. if Result then
  4434. begin
  4435. if (taicpu(p).oper[0]^.val < 0) and
  4436. (
  4437. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4438. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4439. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4440. ) then
  4441. begin
  4442. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4443. taicpu(p).opcode := A_SUB;
  4444. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4445. end
  4446. else
  4447. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4448. RemoveInstruction(hp1);
  4449. end;
  4450. end
  4451. else
  4452. begin
  4453. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4454. TransferUsedRegs(TmpUsedRegs);
  4455. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4456. hp2 := p;
  4457. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4458. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4459. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4460. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4461. begin
  4462. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4463. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4464. Asml.Remove(p);
  4465. Asml.InsertAfter(p, hp1);
  4466. p := hp1;
  4467. Result := True;
  4468. end;
  4469. end;
  4470. end;
  4471. end;
  4472. end;
  4473. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4474. var
  4475. hp1: tai;
  4476. ref: Integer;
  4477. saveref: treference;
  4478. TempReg: TRegister;
  4479. Multiple: TCGInt;
  4480. begin
  4481. Result:=false;
  4482. { removes seg register prefixes from LEA operations, as they
  4483. don't do anything}
  4484. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4485. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4486. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4487. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4488. (
  4489. { do not mess with leas accessing the stack pointer
  4490. unless it's a null operation }
  4491. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4492. (
  4493. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4494. (taicpu(p).oper[0]^.ref^.offset = 0)
  4495. )
  4496. ) and
  4497. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4498. begin
  4499. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4500. begin
  4501. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4502. begin
  4503. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4504. taicpu(p).oper[1]^.reg);
  4505. InsertLLItem(p.previous,p.next, hp1);
  4506. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4507. p.free;
  4508. p:=hp1;
  4509. end
  4510. else
  4511. begin
  4512. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4513. RemoveCurrentP(p);
  4514. end;
  4515. Result:=true;
  4516. exit;
  4517. end
  4518. else if (
  4519. { continue to use lea to adjust the stack pointer,
  4520. it is the recommended way, but only if not optimizing for size }
  4521. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4522. (cs_opt_size in current_settings.optimizerswitches)
  4523. ) and
  4524. { If the flags register is in use, don't change the instruction
  4525. to an ADD otherwise this will scramble the flags. [Kit] }
  4526. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4527. ConvertLEA(taicpu(p)) then
  4528. begin
  4529. Result:=true;
  4530. exit;
  4531. end;
  4532. end;
  4533. if GetNextInstruction(p,hp1) and
  4534. (hp1.typ=ait_instruction) then
  4535. begin
  4536. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4537. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4538. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4539. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4540. begin
  4541. TransferUsedRegs(TmpUsedRegs);
  4542. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4543. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4544. begin
  4545. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4546. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4547. RemoveInstruction(hp1);
  4548. result:=true;
  4549. exit;
  4550. end;
  4551. end;
  4552. { changes
  4553. lea <ref1>, reg1
  4554. <op> ...,<ref. with reg1>,...
  4555. to
  4556. <op> ...,<ref1>,... }
  4557. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4558. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4559. not(MatchInstruction(hp1,A_LEA,[])) then
  4560. begin
  4561. { find a reference which uses reg1 }
  4562. 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
  4563. ref:=0
  4564. 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
  4565. ref:=1
  4566. else
  4567. ref:=-1;
  4568. if (ref<>-1) and
  4569. { reg1 must be either the base or the index }
  4570. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4571. begin
  4572. { reg1 can be removed from the reference }
  4573. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4574. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4575. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4576. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4577. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4578. else
  4579. Internalerror(2019111201);
  4580. { check if the can insert all data of the lea into the second instruction }
  4581. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4582. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4583. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4584. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4585. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4586. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4587. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4588. {$ifdef x86_64}
  4589. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4590. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4591. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4592. )
  4593. {$endif x86_64}
  4594. then
  4595. begin
  4596. { reg1 might not used by the second instruction after it is remove from the reference }
  4597. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4598. begin
  4599. TransferUsedRegs(TmpUsedRegs);
  4600. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4601. { reg1 is not updated so it might not be used afterwards }
  4602. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4603. begin
  4604. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4605. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4606. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4607. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4608. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4609. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4610. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4611. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4612. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4613. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4614. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4615. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4616. RemoveCurrentP(p, hp1);
  4617. result:=true;
  4618. exit;
  4619. end
  4620. end;
  4621. end;
  4622. { recover }
  4623. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4624. end;
  4625. end;
  4626. end;
  4627. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4628. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4629. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4630. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4631. begin
  4632. { Check common LEA/LEA conditions }
  4633. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4634. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4635. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4636. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4637. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4638. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4639. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4640. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4641. (
  4642. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4643. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4644. ) and (
  4645. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4646. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4647. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4648. ) then
  4649. begin
  4650. { changes
  4651. lea (regX,scale), reg1
  4652. lea offset(reg1,reg1), reg1
  4653. to
  4654. lea offset(regX,scale*2), reg1
  4655. and
  4656. lea (regX,scale1), reg1
  4657. lea offset(reg1,scale2), reg1
  4658. to
  4659. lea offset(regX,scale1*scale2), reg1
  4660. ... so long as the final scale does not exceed 8
  4661. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4662. }
  4663. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4664. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4665. (
  4666. (
  4667. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4668. ) or (
  4669. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4670. (
  4671. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4672. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4673. )
  4674. )
  4675. ) and (
  4676. (
  4677. { lea (reg1,scale2), reg1 variant }
  4678. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4679. (
  4680. (
  4681. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4682. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4683. ) or (
  4684. { lea (regX,regX), reg1 variant }
  4685. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4686. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4687. )
  4688. )
  4689. ) or (
  4690. { lea (reg1,reg1), reg1 variant }
  4691. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4692. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4693. )
  4694. ) then
  4695. begin
  4696. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4697. { Make everything homogeneous to make calculations easier }
  4698. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4699. begin
  4700. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4701. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4702. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4703. else
  4704. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4705. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4706. end;
  4707. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4708. begin
  4709. { Just to prevent miscalculations }
  4710. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4711. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4712. else
  4713. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4714. end
  4715. else
  4716. begin
  4717. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4718. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4719. end;
  4720. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4721. RemoveCurrentP(p);
  4722. result:=true;
  4723. exit;
  4724. end
  4725. { changes
  4726. lea offset1(regX), reg1
  4727. lea offset2(reg1), reg1
  4728. to
  4729. lea offset1+offset2(regX), reg1 }
  4730. else if
  4731. (
  4732. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4733. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4734. ) or (
  4735. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4736. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4737. (
  4738. (
  4739. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4740. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4741. ) or (
  4742. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4743. (
  4744. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4745. (
  4746. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4747. (
  4748. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4749. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4750. )
  4751. )
  4752. )
  4753. )
  4754. )
  4755. ) then
  4756. begin
  4757. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4758. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4759. begin
  4760. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4761. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4762. { if the register is used as index and base, we have to increase for base as well
  4763. and adapt base }
  4764. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4765. begin
  4766. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4767. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4768. end;
  4769. end
  4770. else
  4771. begin
  4772. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4773. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4774. end;
  4775. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4776. begin
  4777. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4778. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4779. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4780. end;
  4781. RemoveCurrentP(p);
  4782. result:=true;
  4783. exit;
  4784. end;
  4785. end;
  4786. { Change:
  4787. leal/q $x(%reg1),%reg2
  4788. ...
  4789. shll/q $y,%reg2
  4790. To:
  4791. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4792. }
  4793. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4794. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4795. (taicpu(hp1).oper[0]^.val <= 3) then
  4796. begin
  4797. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4798. TransferUsedRegs(TmpUsedRegs);
  4799. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4800. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4801. if
  4802. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4803. (this works even if scalefactor is zero) }
  4804. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4805. { Ensure offset doesn't go out of bounds }
  4806. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4807. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4808. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4809. (
  4810. (
  4811. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4812. (
  4813. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4814. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4815. (
  4816. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4817. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4818. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4819. )
  4820. )
  4821. ) or (
  4822. (
  4823. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4824. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4825. ) and
  4826. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4827. )
  4828. ) then
  4829. begin
  4830. repeat
  4831. with taicpu(p).oper[0]^.ref^ do
  4832. begin
  4833. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4834. if index = base then
  4835. begin
  4836. if Multiple > 4 then
  4837. { Optimisation will no longer work because resultant
  4838. scale factor will exceed 8 }
  4839. Break;
  4840. base := NR_NO;
  4841. scalefactor := 2;
  4842. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4843. end
  4844. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4845. begin
  4846. { Scale factor only works on the index register }
  4847. index := base;
  4848. base := NR_NO;
  4849. end;
  4850. { For safety }
  4851. if scalefactor <= 1 then
  4852. begin
  4853. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4854. scalefactor := Multiple;
  4855. end
  4856. else
  4857. begin
  4858. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4859. scalefactor := scalefactor * Multiple;
  4860. end;
  4861. offset := offset * Multiple;
  4862. end;
  4863. RemoveInstruction(hp1);
  4864. Result := True;
  4865. Exit;
  4866. { This repeat..until loop exists for the benefit of Break }
  4867. until True;
  4868. end;
  4869. end;
  4870. end;
  4871. end;
  4872. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4873. var
  4874. hp1 : tai;
  4875. begin
  4876. DoSubAddOpt := False;
  4877. if taicpu(p).oper[0]^.typ <> top_const then
  4878. { Should have been confirmed before calling }
  4879. InternalError(2021102601);
  4880. if GetLastInstruction(p, hp1) and
  4881. (hp1.typ = ait_instruction) and
  4882. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4883. case taicpu(hp1).opcode Of
  4884. A_DEC:
  4885. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4886. begin
  4887. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4888. RemoveInstruction(hp1);
  4889. end;
  4890. A_SUB:
  4891. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4892. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4893. begin
  4894. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4895. RemoveInstruction(hp1);
  4896. end;
  4897. A_ADD:
  4898. begin
  4899. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4900. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4901. begin
  4902. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4903. RemoveInstruction(hp1);
  4904. if (taicpu(p).oper[0]^.val = 0) then
  4905. begin
  4906. hp1 := tai(p.next);
  4907. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4908. if not GetLastInstruction(hp1, p) then
  4909. p := hp1;
  4910. DoSubAddOpt := True;
  4911. end
  4912. end;
  4913. end;
  4914. else
  4915. ;
  4916. end;
  4917. end;
  4918. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4919. begin
  4920. Result := False;
  4921. if UpdateTmpUsedRegs then
  4922. TransferUsedRegs(TmpUsedRegs);
  4923. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4924. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4925. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4926. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4927. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4928. (
  4929. (
  4930. (taicpu(hp1).opcode = A_TEST)
  4931. ) or (
  4932. (taicpu(hp1).opcode = A_CMP) and
  4933. { A sanity check more than anything }
  4934. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4935. )
  4936. ) then
  4937. begin
  4938. { change
  4939. mov mem, %reg
  4940. cmp/test x, %reg / test %reg,%reg
  4941. (reg deallocated)
  4942. to
  4943. cmp/test x, mem / cmp 0, mem
  4944. }
  4945. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4946. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4947. begin
  4948. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4949. if (taicpu(hp1).opcode = A_TEST) and
  4950. (
  4951. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4952. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4953. ) then
  4954. begin
  4955. taicpu(hp1).opcode := A_CMP;
  4956. taicpu(hp1).loadconst(0, 0);
  4957. end;
  4958. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4959. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4960. RemoveCurrentP(p, hp1);
  4961. Result := True;
  4962. Exit;
  4963. end;
  4964. end;
  4965. end;
  4966. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  4967. var
  4968. hp2, hp3, hp4, hp5, hp6: tai;
  4969. ThisReg: TRegister;
  4970. JumpLoc: TAsmLabel;
  4971. begin
  4972. Result := False;
  4973. {
  4974. Convert:
  4975. j<c> .L1
  4976. .L2:
  4977. mov 1,reg
  4978. jmp .L3 (or ret, although it might not be a RET yet)
  4979. .L1:
  4980. mov 0,reg
  4981. jmp .L3 (or ret)
  4982. ( As long as .L3 <> .L1 or .L2)
  4983. To:
  4984. mov 0,reg
  4985. set<not(c)> reg
  4986. jmp .L3 (or ret)
  4987. .L2:
  4988. mov 1,reg
  4989. jmp .L3 (or ret)
  4990. .L1:
  4991. mov 0,reg
  4992. jmp .L3 (or ret)
  4993. }
  4994. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  4995. Exit;
  4996. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  4997. if GetNextInstruction(hp_label, hp2) and
  4998. MatchInstruction(hp2,A_MOV,[]) and
  4999. (taicpu(hp2).oper[0]^.typ = top_const) and
  5000. (
  5001. (
  5002. (taicpu(hp2).oper[1]^.typ = top_reg)
  5003. {$ifdef i386}
  5004. { Under i386, ESI, EDI, EBP and ESP
  5005. don't have an 8-bit representation }
  5006. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5007. {$endif i386}
  5008. ) or (
  5009. {$ifdef i386}
  5010. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5011. {$endif i386}
  5012. (taicpu(hp2).opsize = S_B)
  5013. )
  5014. ) and
  5015. GetNextInstruction(hp2, hp3) and
  5016. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5017. (
  5018. (taicpu(hp3).opcode=A_RET) or
  5019. (
  5020. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5021. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5022. )
  5023. ) and
  5024. GetNextInstruction(hp3, hp4) and
  5025. SkipAligns(hp4, hp4) and
  5026. (hp4.typ=ait_label) and
  5027. (tai_label(hp4).labsym=JumpLoc) and
  5028. (
  5029. not (cs_opt_size in current_settings.optimizerswitches) or
  5030. { If the initial jump is the label's only reference, then it will
  5031. become a dead label if the other conditions are met and hence
  5032. remove at least 2 instructions, including a jump }
  5033. (JumpLoc.getrefs = 1)
  5034. ) and
  5035. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5036. that will be optimised out }
  5037. GetNextInstruction(hp4, hp5) and
  5038. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5039. (taicpu(hp5).oper[0]^.typ = top_const) and
  5040. (
  5041. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5042. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5043. ) and
  5044. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5045. GetNextInstruction(hp5,hp6) and
  5046. (
  5047. (hp6.typ<>ait_label) or
  5048. SkipLabels(hp6, hp6)
  5049. ) and
  5050. (hp6.typ=ait_instruction) then
  5051. begin
  5052. { First, let's look at the two jumps that are hp3 and hp6 }
  5053. if not
  5054. (
  5055. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5056. (
  5057. (taicpu(hp6).opcode=A_RET) or
  5058. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5059. )
  5060. ) then
  5061. { If condition is False, then the JMP/RET instructions matched conventionally }
  5062. begin
  5063. { See if one of the jumps can be instantly converted into a RET }
  5064. if (taicpu(hp3).opcode=A_JMP) then
  5065. begin
  5066. { Reuse hp5 }
  5067. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5068. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5069. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5070. Exit;
  5071. if MatchInstruction(hp5, A_RET, []) then
  5072. begin
  5073. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5074. ConvertJumpToRET(hp3, hp5);
  5075. Result := True;
  5076. end
  5077. else
  5078. Exit;
  5079. end;
  5080. if (taicpu(hp6).opcode=A_JMP) then
  5081. begin
  5082. { Reuse hp5 }
  5083. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5084. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5085. Exit;
  5086. if MatchInstruction(hp5, A_RET, []) then
  5087. begin
  5088. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5089. ConvertJumpToRET(hp6, hp5);
  5090. Result := True;
  5091. end
  5092. else
  5093. Exit;
  5094. end;
  5095. if not
  5096. (
  5097. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5098. (
  5099. (taicpu(hp6).opcode=A_RET) or
  5100. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5101. )
  5102. ) then
  5103. { Still doesn't match }
  5104. Exit;
  5105. end;
  5106. if (taicpu(hp2).oper[0]^.val = 1) then
  5107. begin
  5108. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5109. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5110. end
  5111. else
  5112. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5113. if taicpu(hp2).opsize=S_B then
  5114. begin
  5115. if taicpu(hp2).oper[1]^.typ = top_reg then
  5116. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5117. else
  5118. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5119. hp2 := p;
  5120. end
  5121. else
  5122. begin
  5123. { Will be a register because the size can't be S_B otherwise }
  5124. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5125. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5126. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5127. { Inserting it right before p will guarantee that the flags are also tracked }
  5128. Asml.InsertBefore(hp2, p);
  5129. end;
  5130. taicpu(hp4).condition:=taicpu(p).condition;
  5131. asml.InsertBefore(hp4, hp2);
  5132. JumpLoc.decrefs;
  5133. if taicpu(hp3).opcode = A_JMP then
  5134. begin
  5135. MakeUnconditional(taicpu(p));
  5136. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5137. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5138. end
  5139. else
  5140. begin
  5141. taicpu(p).condition := C_None;
  5142. taicpu(p).opcode := A_RET;
  5143. taicpu(p).clearop(0);
  5144. taicpu(p).ops := 0;
  5145. end;
  5146. if (JumpLoc.getrefs = 0) then
  5147. RemoveDeadCodeAfterJump(hp3);
  5148. Result:=true;
  5149. exit;
  5150. end;
  5151. end;
  5152. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5153. var
  5154. hp1, hp2: tai;
  5155. ActiveReg: TRegister;
  5156. OldOffset: asizeint;
  5157. ThisConst: TCGInt;
  5158. function RegDeallocated: Boolean;
  5159. begin
  5160. TransferUsedRegs(TmpUsedRegs);
  5161. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5162. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5163. end;
  5164. begin
  5165. Result:=false;
  5166. hp1 := nil;
  5167. { replace
  5168. subX const,%reg1
  5169. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5170. dealloc %reg1
  5171. by
  5172. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5173. }
  5174. if MatchOpType(taicpu(p),top_const,top_reg) then
  5175. begin
  5176. ActiveReg := taicpu(p).oper[1]^.reg;
  5177. { Ensures the entire register was updated }
  5178. if (taicpu(p).opsize >= S_L) and
  5179. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5180. MatchInstruction(hp1,A_LEA,[]) and
  5181. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5182. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5183. (
  5184. { Cover the case where the register in the reference is also the destination register }
  5185. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5186. (
  5187. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5188. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5189. RegDeallocated
  5190. )
  5191. ) then
  5192. begin
  5193. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5194. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5195. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5196. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5197. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5198. {$ifdef x86_64}
  5199. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5200. begin
  5201. { Overflow; abort }
  5202. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5203. end
  5204. else
  5205. {$endif x86_64}
  5206. begin
  5207. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5208. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5209. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5210. RemoveCurrentP(p, hp1)
  5211. else
  5212. RemoveCurrentP(p);
  5213. result:=true;
  5214. Exit;
  5215. end;
  5216. end;
  5217. if (
  5218. { Save calling GetNextInstructionUsingReg again }
  5219. Assigned(hp1) or
  5220. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5221. ) and
  5222. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5223. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5224. begin
  5225. if taicpu(hp1).oper[0]^.typ = top_const then
  5226. begin
  5227. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5228. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5229. Result := True;
  5230. { Handle any overflows }
  5231. case taicpu(p).opsize of
  5232. S_B:
  5233. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5234. S_W:
  5235. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5236. S_L:
  5237. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5238. {$ifdef x86_64}
  5239. S_Q:
  5240. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5241. { Overflow; abort }
  5242. Result := False
  5243. else
  5244. taicpu(p).oper[0]^.val := ThisConst;
  5245. {$endif x86_64}
  5246. else
  5247. InternalError(2021102610);
  5248. end;
  5249. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5250. if Result then
  5251. begin
  5252. if (taicpu(p).oper[0]^.val < 0) and
  5253. (
  5254. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5255. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5256. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5257. ) then
  5258. begin
  5259. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5260. taicpu(p).opcode := A_SUB;
  5261. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5262. end
  5263. else
  5264. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5265. RemoveInstruction(hp1);
  5266. end;
  5267. end
  5268. else
  5269. begin
  5270. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5271. TransferUsedRegs(TmpUsedRegs);
  5272. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5273. hp2 := p;
  5274. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5275. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5276. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5277. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5278. begin
  5279. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5280. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5281. Asml.Remove(p);
  5282. Asml.InsertAfter(p, hp1);
  5283. p := hp1;
  5284. Result := True;
  5285. Exit;
  5286. end;
  5287. end;
  5288. end;
  5289. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5290. { * change "sub/add const1, reg" or "dec reg" followed by
  5291. "sub const2, reg" to one "sub ..., reg" }
  5292. {$ifdef i386}
  5293. if (taicpu(p).oper[0]^.val = 2) and
  5294. (ActiveReg = NR_ESP) and
  5295. { Don't do the sub/push optimization if the sub }
  5296. { comes from setting up the stack frame (JM) }
  5297. (not(GetLastInstruction(p,hp1)) or
  5298. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5299. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5300. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5301. begin
  5302. hp1 := tai(p.next);
  5303. while Assigned(hp1) and
  5304. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5305. not RegReadByInstruction(NR_ESP,hp1) and
  5306. not RegModifiedByInstruction(NR_ESP,hp1) do
  5307. hp1 := tai(hp1.next);
  5308. if Assigned(hp1) and
  5309. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5310. begin
  5311. taicpu(hp1).changeopsize(S_L);
  5312. if taicpu(hp1).oper[0]^.typ=top_reg then
  5313. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5314. hp1 := tai(p.next);
  5315. RemoveCurrentp(p, hp1);
  5316. Result:=true;
  5317. exit;
  5318. end;
  5319. end;
  5320. {$endif i386}
  5321. if DoSubAddOpt(p) then
  5322. Result:=true;
  5323. end;
  5324. end;
  5325. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5326. var
  5327. TmpBool1,TmpBool2 : Boolean;
  5328. tmpref : treference;
  5329. hp1,hp2: tai;
  5330. mask: tcgint;
  5331. begin
  5332. Result:=false;
  5333. { All these optimisations work on "shl/sal const,%reg" }
  5334. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5335. Exit;
  5336. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5337. (taicpu(p).oper[0]^.val <= 3) then
  5338. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5339. begin
  5340. { should we check the next instruction? }
  5341. TmpBool1 := True;
  5342. { have we found an add/sub which could be
  5343. integrated in the lea? }
  5344. TmpBool2 := False;
  5345. reference_reset(tmpref,2,[]);
  5346. TmpRef.index := taicpu(p).oper[1]^.reg;
  5347. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5348. while TmpBool1 and
  5349. GetNextInstruction(p, hp1) and
  5350. (tai(hp1).typ = ait_instruction) and
  5351. ((((taicpu(hp1).opcode = A_ADD) or
  5352. (taicpu(hp1).opcode = A_SUB)) and
  5353. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5354. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5355. (((taicpu(hp1).opcode = A_INC) or
  5356. (taicpu(hp1).opcode = A_DEC)) and
  5357. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5358. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5359. ((taicpu(hp1).opcode = A_LEA) and
  5360. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5361. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5362. (not GetNextInstruction(hp1,hp2) or
  5363. not instrReadsFlags(hp2)) Do
  5364. begin
  5365. TmpBool1 := False;
  5366. if taicpu(hp1).opcode=A_LEA then
  5367. begin
  5368. if (TmpRef.base = NR_NO) and
  5369. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5370. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5371. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5372. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5373. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5374. begin
  5375. TmpBool1 := True;
  5376. TmpBool2 := True;
  5377. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5378. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5379. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5380. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5381. RemoveInstruction(hp1);
  5382. end
  5383. end
  5384. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5385. begin
  5386. TmpBool1 := True;
  5387. TmpBool2 := True;
  5388. case taicpu(hp1).opcode of
  5389. A_ADD:
  5390. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5391. A_SUB:
  5392. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5393. else
  5394. internalerror(2019050536);
  5395. end;
  5396. RemoveInstruction(hp1);
  5397. end
  5398. else
  5399. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5400. (((taicpu(hp1).opcode = A_ADD) and
  5401. (TmpRef.base = NR_NO)) or
  5402. (taicpu(hp1).opcode = A_INC) or
  5403. (taicpu(hp1).opcode = A_DEC)) then
  5404. begin
  5405. TmpBool1 := True;
  5406. TmpBool2 := True;
  5407. case taicpu(hp1).opcode of
  5408. A_ADD:
  5409. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5410. A_INC:
  5411. inc(TmpRef.offset);
  5412. A_DEC:
  5413. dec(TmpRef.offset);
  5414. else
  5415. internalerror(2019050535);
  5416. end;
  5417. RemoveInstruction(hp1);
  5418. end;
  5419. end;
  5420. if TmpBool2
  5421. {$ifndef x86_64}
  5422. or
  5423. ((current_settings.optimizecputype < cpu_Pentium2) and
  5424. (taicpu(p).oper[0]^.val <= 3) and
  5425. not(cs_opt_size in current_settings.optimizerswitches))
  5426. {$endif x86_64}
  5427. then
  5428. begin
  5429. if not(TmpBool2) and
  5430. (taicpu(p).oper[0]^.val=1) then
  5431. begin
  5432. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5433. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5434. end
  5435. else
  5436. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5437. taicpu(p).oper[1]^.reg);
  5438. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5439. InsertLLItem(p.previous, p.next, hp1);
  5440. p.free;
  5441. p := hp1;
  5442. end;
  5443. end
  5444. {$ifndef x86_64}
  5445. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5446. begin
  5447. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5448. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5449. (unlike shl, which is only Tairable in the U pipe) }
  5450. if taicpu(p).oper[0]^.val=1 then
  5451. begin
  5452. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5453. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5454. InsertLLItem(p.previous, p.next, hp1);
  5455. p.free;
  5456. p := hp1;
  5457. end
  5458. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5459. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5460. else if (taicpu(p).opsize = S_L) and
  5461. (taicpu(p).oper[0]^.val<= 3) then
  5462. begin
  5463. reference_reset(tmpref,2,[]);
  5464. TmpRef.index := taicpu(p).oper[1]^.reg;
  5465. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5466. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5467. InsertLLItem(p.previous, p.next, hp1);
  5468. p.free;
  5469. p := hp1;
  5470. end;
  5471. end
  5472. {$endif x86_64}
  5473. else if
  5474. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5475. (
  5476. (
  5477. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5478. SetAndTest(hp1, hp2)
  5479. {$ifdef x86_64}
  5480. ) or
  5481. (
  5482. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5483. GetNextInstruction(hp1, hp2) and
  5484. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5485. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5486. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5487. {$endif x86_64}
  5488. )
  5489. ) and
  5490. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5491. begin
  5492. { Change:
  5493. shl x, %reg1
  5494. mov -(1<<x), %reg2
  5495. and %reg2, %reg1
  5496. Or:
  5497. shl x, %reg1
  5498. and -(1<<x), %reg1
  5499. To just:
  5500. shl x, %reg1
  5501. Since the and operation only zeroes bits that are already zero from the shl operation
  5502. }
  5503. case taicpu(p).oper[0]^.val of
  5504. 8:
  5505. mask:=$FFFFFFFFFFFFFF00;
  5506. 16:
  5507. mask:=$FFFFFFFFFFFF0000;
  5508. 32:
  5509. mask:=$FFFFFFFF00000000;
  5510. 63:
  5511. { Constant pre-calculated to prevent overflow errors with Int64 }
  5512. mask:=$8000000000000000;
  5513. else
  5514. begin
  5515. if taicpu(p).oper[0]^.val >= 64 then
  5516. { Shouldn't happen realistically, since the register
  5517. is guaranteed to be set to zero at this point }
  5518. mask := 0
  5519. else
  5520. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5521. end;
  5522. end;
  5523. if taicpu(hp1).oper[0]^.val = mask then
  5524. begin
  5525. { Everything checks out, perform the optimisation, as long as
  5526. the FLAGS register isn't being used}
  5527. TransferUsedRegs(TmpUsedRegs);
  5528. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5529. {$ifdef x86_64}
  5530. if (hp1 <> hp2) then
  5531. begin
  5532. { "shl/mov/and" version }
  5533. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5534. { Don't do the optimisation if the FLAGS register is in use }
  5535. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5536. begin
  5537. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5538. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5539. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5540. begin
  5541. RemoveInstruction(hp1);
  5542. Result := True;
  5543. end;
  5544. { Only set Result to True if the 'mov' instruction was removed }
  5545. RemoveInstruction(hp2);
  5546. end;
  5547. end
  5548. else
  5549. {$endif x86_64}
  5550. begin
  5551. { "shl/and" version }
  5552. { Don't do the optimisation if the FLAGS register is in use }
  5553. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5554. begin
  5555. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5556. RemoveInstruction(hp1);
  5557. Result := True;
  5558. end;
  5559. end;
  5560. Exit;
  5561. end
  5562. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5563. begin
  5564. { Even if the mask doesn't allow for its removal, we might be
  5565. able to optimise the mask for the "shl/and" version, which
  5566. may permit other peephole optimisations }
  5567. {$ifdef DEBUG_AOPTCPU}
  5568. mask := taicpu(hp1).oper[0]^.val and mask;
  5569. if taicpu(hp1).oper[0]^.val <> mask then
  5570. begin
  5571. DebugMsg(
  5572. SPeepholeOptimization +
  5573. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5574. ' to $' + debug_tostr(mask) +
  5575. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5576. taicpu(hp1).oper[0]^.val := mask;
  5577. end;
  5578. {$else DEBUG_AOPTCPU}
  5579. { If debugging is off, just set the operand even if it's the same }
  5580. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5581. {$endif DEBUG_AOPTCPU}
  5582. end;
  5583. end;
  5584. {
  5585. change
  5586. shl/sal const,reg
  5587. <op> ...(...,reg,1),...
  5588. into
  5589. <op> ...(...,reg,1 shl const),...
  5590. if const in 1..3
  5591. }
  5592. if MatchOpType(taicpu(p), top_const, top_reg) and
  5593. (taicpu(p).oper[0]^.val in [1..3]) and
  5594. GetNextInstruction(p, hp1) and
  5595. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5596. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5597. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5598. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5599. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5600. begin
  5601. TransferUsedRegs(TmpUsedRegs);
  5602. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5603. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5604. begin
  5605. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5606. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5607. RemoveCurrentP(p);
  5608. Result:=true;
  5609. end;
  5610. end;
  5611. end;
  5612. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5613. var
  5614. CurrentRef: TReference;
  5615. FullReg: TRegister;
  5616. hp1, hp2: tai;
  5617. begin
  5618. Result := False;
  5619. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5620. Exit;
  5621. { We assume you've checked if the operand is actually a reference by
  5622. this point. If it isn't, you'll most likely get an access violation }
  5623. CurrentRef := first_mov.oper[1]^.ref^;
  5624. { Memory must be aligned }
  5625. if (CurrentRef.offset mod 4) <> 0 then
  5626. Exit;
  5627. Inc(CurrentRef.offset);
  5628. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5629. if MatchOperand(second_mov.oper[0]^, 0) and
  5630. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5631. GetNextInstruction(second_mov, hp1) and
  5632. (hp1.typ = ait_instruction) and
  5633. (taicpu(hp1).opcode = A_MOV) and
  5634. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5635. (taicpu(hp1).oper[0]^.val = 0) then
  5636. begin
  5637. Inc(CurrentRef.offset);
  5638. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5639. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5640. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5641. begin
  5642. case taicpu(hp1).opsize of
  5643. S_B:
  5644. if GetNextInstruction(hp1, hp2) and
  5645. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5646. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5647. (taicpu(hp2).oper[0]^.val = 0) then
  5648. begin
  5649. Inc(CurrentRef.offset);
  5650. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5651. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5652. (taicpu(hp2).opsize = S_B) then
  5653. begin
  5654. RemoveInstruction(hp1);
  5655. RemoveInstruction(hp2);
  5656. first_mov.opsize := S_L;
  5657. if first_mov.oper[0]^.typ = top_reg then
  5658. begin
  5659. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5660. { Reuse second_mov as a MOVZX instruction }
  5661. second_mov.opcode := A_MOVZX;
  5662. second_mov.opsize := S_BL;
  5663. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5664. second_mov.loadreg(1, FullReg);
  5665. first_mov.oper[0]^.reg := FullReg;
  5666. asml.Remove(second_mov);
  5667. asml.InsertBefore(second_mov, first_mov);
  5668. end
  5669. else
  5670. { It's a value }
  5671. begin
  5672. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5673. RemoveInstruction(second_mov);
  5674. end;
  5675. Result := True;
  5676. Exit;
  5677. end;
  5678. end;
  5679. S_W:
  5680. begin
  5681. RemoveInstruction(hp1);
  5682. first_mov.opsize := S_L;
  5683. if first_mov.oper[0]^.typ = top_reg then
  5684. begin
  5685. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5686. { Reuse second_mov as a MOVZX instruction }
  5687. second_mov.opcode := A_MOVZX;
  5688. second_mov.opsize := S_BL;
  5689. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5690. second_mov.loadreg(1, FullReg);
  5691. first_mov.oper[0]^.reg := FullReg;
  5692. asml.Remove(second_mov);
  5693. asml.InsertBefore(second_mov, first_mov);
  5694. end
  5695. else
  5696. { It's a value }
  5697. begin
  5698. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5699. RemoveInstruction(second_mov);
  5700. end;
  5701. Result := True;
  5702. Exit;
  5703. end;
  5704. else
  5705. ;
  5706. end;
  5707. end;
  5708. end;
  5709. end;
  5710. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5711. { returns true if a "continue" should be done after this optimization }
  5712. var
  5713. hp1, hp2: tai;
  5714. begin
  5715. Result := false;
  5716. if MatchOpType(taicpu(p),top_ref) and
  5717. GetNextInstruction(p, hp1) and
  5718. (hp1.typ = ait_instruction) and
  5719. (((taicpu(hp1).opcode = A_FLD) and
  5720. (taicpu(p).opcode = A_FSTP)) or
  5721. ((taicpu(p).opcode = A_FISTP) and
  5722. (taicpu(hp1).opcode = A_FILD))) and
  5723. MatchOpType(taicpu(hp1),top_ref) and
  5724. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5725. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5726. begin
  5727. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5728. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5729. GetNextInstruction(hp1, hp2) and
  5730. (hp2.typ = ait_instruction) and
  5731. IsExitCode(hp2) and
  5732. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5733. not(assigned(current_procinfo.procdef.funcretsym) and
  5734. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5735. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5736. begin
  5737. RemoveInstruction(hp1);
  5738. RemoveCurrentP(p, hp2);
  5739. RemoveLastDeallocForFuncRes(p);
  5740. Result := true;
  5741. end
  5742. else
  5743. { we can do this only in fast math mode as fstp is rounding ...
  5744. ... still disabled as it breaks the compiler and/or rtl }
  5745. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5746. { ... or if another fstp equal to the first one follows }
  5747. (GetNextInstruction(hp1,hp2) and
  5748. (hp2.typ = ait_instruction) and
  5749. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5750. (taicpu(p).opsize=taicpu(hp2).opsize))
  5751. ) and
  5752. { fst can't store an extended/comp value }
  5753. (taicpu(p).opsize <> S_FX) and
  5754. (taicpu(p).opsize <> S_IQ) then
  5755. begin
  5756. if (taicpu(p).opcode = A_FSTP) then
  5757. taicpu(p).opcode := A_FST
  5758. else
  5759. taicpu(p).opcode := A_FIST;
  5760. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5761. RemoveInstruction(hp1);
  5762. end;
  5763. end;
  5764. end;
  5765. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5766. var
  5767. hp1, hp2: tai;
  5768. begin
  5769. result:=false;
  5770. if MatchOpType(taicpu(p),top_reg) and
  5771. GetNextInstruction(p, hp1) and
  5772. (hp1.typ = Ait_Instruction) and
  5773. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5774. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5775. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5776. { change to
  5777. fld reg fxxx reg,st
  5778. fxxxp st, st1 (hp1)
  5779. Remark: non commutative operations must be reversed!
  5780. }
  5781. begin
  5782. case taicpu(hp1).opcode Of
  5783. A_FMULP,A_FADDP,
  5784. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5785. begin
  5786. case taicpu(hp1).opcode Of
  5787. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5788. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5789. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5790. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5791. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5792. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5793. else
  5794. internalerror(2019050534);
  5795. end;
  5796. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5797. taicpu(hp1).oper[1]^.reg := NR_ST;
  5798. RemoveCurrentP(p, hp1);
  5799. Result:=true;
  5800. exit;
  5801. end;
  5802. else
  5803. ;
  5804. end;
  5805. end
  5806. else
  5807. if MatchOpType(taicpu(p),top_ref) and
  5808. GetNextInstruction(p, hp2) and
  5809. (hp2.typ = Ait_Instruction) and
  5810. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5811. (taicpu(p).opsize in [S_FS, S_FL]) and
  5812. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5813. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5814. if GetLastInstruction(p, hp1) and
  5815. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5816. MatchOpType(taicpu(hp1),top_ref) and
  5817. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5818. if ((taicpu(hp2).opcode = A_FMULP) or
  5819. (taicpu(hp2).opcode = A_FADDP)) then
  5820. { change to
  5821. fld/fst mem1 (hp1) fld/fst mem1
  5822. fld mem1 (p) fadd/
  5823. faddp/ fmul st, st
  5824. fmulp st, st1 (hp2) }
  5825. begin
  5826. RemoveCurrentP(p, hp1);
  5827. if (taicpu(hp2).opcode = A_FADDP) then
  5828. taicpu(hp2).opcode := A_FADD
  5829. else
  5830. taicpu(hp2).opcode := A_FMUL;
  5831. taicpu(hp2).oper[1]^.reg := NR_ST;
  5832. end
  5833. else
  5834. { change to
  5835. fld/fst mem1 (hp1) fld/fst mem1
  5836. fld mem1 (p) fld st}
  5837. begin
  5838. taicpu(p).changeopsize(S_FL);
  5839. taicpu(p).loadreg(0,NR_ST);
  5840. end
  5841. else
  5842. begin
  5843. case taicpu(hp2).opcode Of
  5844. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5845. { change to
  5846. fld/fst mem1 (hp1) fld/fst mem1
  5847. fld mem2 (p) fxxx mem2
  5848. fxxxp st, st1 (hp2) }
  5849. begin
  5850. case taicpu(hp2).opcode Of
  5851. A_FADDP: taicpu(p).opcode := A_FADD;
  5852. A_FMULP: taicpu(p).opcode := A_FMUL;
  5853. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5854. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5855. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5856. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5857. else
  5858. internalerror(2019050533);
  5859. end;
  5860. RemoveInstruction(hp2);
  5861. end
  5862. else
  5863. ;
  5864. end
  5865. end
  5866. end;
  5867. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5868. begin
  5869. Result := condition_in(cond1, cond2) or
  5870. { Not strictly subsets due to the actual flags checked, but because we're
  5871. comparing integers, E is a subset of AE and GE and their aliases }
  5872. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5873. end;
  5874. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5875. var
  5876. v: TCGInt;
  5877. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5878. FirstMatch: Boolean;
  5879. NewReg: TRegister;
  5880. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5881. begin
  5882. Result:=false;
  5883. { All these optimisations need a next instruction }
  5884. if not GetNextInstruction(p, hp1) then
  5885. Exit;
  5886. { Search for:
  5887. cmp ###,###
  5888. j(c1) @lbl1
  5889. ...
  5890. @lbl:
  5891. cmp ###.### (same comparison as above)
  5892. j(c2) @lbl2
  5893. If c1 is a subset of c2, change to:
  5894. cmp ###,###
  5895. j(c2) @lbl2
  5896. (@lbl1 may become a dead label as a result)
  5897. }
  5898. { Also handle cases where there are multiple jumps in a row }
  5899. p_jump := hp1;
  5900. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5901. begin
  5902. if IsJumpToLabel(taicpu(p_jump)) then
  5903. begin
  5904. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5905. p_label := nil;
  5906. if Assigned(JumpLabel) then
  5907. p_label := getlabelwithsym(JumpLabel);
  5908. if Assigned(p_label) and
  5909. GetNextInstruction(p_label, p_dist) and
  5910. MatchInstruction(p_dist, A_CMP, []) and
  5911. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5912. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5913. GetNextInstruction(p_dist, hp1_dist) and
  5914. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5915. begin
  5916. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5917. if JumpLabel = JumpLabel_dist then
  5918. { This is an infinite loop }
  5919. Exit;
  5920. { Best optimisation when the first condition is a subset (or equal) of the second }
  5921. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5922. begin
  5923. { Any registers used here will already be allocated }
  5924. if Assigned(JumpLabel_dist) then
  5925. JumpLabel_dist.IncRefs;
  5926. if Assigned(JumpLabel) then
  5927. JumpLabel.DecRefs;
  5928. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5929. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5930. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5931. Result := True;
  5932. { Don't exit yet. Since p and p_jump haven't actually been
  5933. removed, we can check for more on this iteration }
  5934. end
  5935. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5936. GetNextInstruction(hp1_dist, hp1_label) and
  5937. SkipAligns(hp1_label, hp1_label) and
  5938. (hp1_label.typ = ait_label) then
  5939. begin
  5940. JumpLabel_far := tai_label(hp1_label).labsym;
  5941. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5942. { This is an infinite loop }
  5943. Exit;
  5944. if Assigned(JumpLabel_far) then
  5945. begin
  5946. { In this situation, if the first jump branches, the second one will never,
  5947. branch so change the destination label to after the second jump }
  5948. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5949. if Assigned(JumpLabel) then
  5950. JumpLabel.DecRefs;
  5951. JumpLabel_far.IncRefs;
  5952. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5953. Result := True;
  5954. { Don't exit yet. Since p and p_jump haven't actually been
  5955. removed, we can check for more on this iteration }
  5956. Continue;
  5957. end;
  5958. end;
  5959. end;
  5960. end;
  5961. { Search for:
  5962. cmp ###,###
  5963. j(c1) @lbl1
  5964. cmp ###,### (same as first)
  5965. Remove second cmp
  5966. }
  5967. if GetNextInstruction(p_jump, hp2) and
  5968. (
  5969. (
  5970. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5971. (
  5972. (
  5973. MatchOpType(taicpu(p), top_const, top_reg) and
  5974. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5975. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5976. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5977. ) or (
  5978. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5979. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5980. )
  5981. )
  5982. ) or (
  5983. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5984. MatchOperand(taicpu(p).oper[0]^, 0) and
  5985. (taicpu(p).oper[1]^.typ = top_reg) and
  5986. MatchInstruction(hp2, A_TEST, []) and
  5987. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5988. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5989. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5990. )
  5991. ) then
  5992. begin
  5993. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5994. RemoveInstruction(hp2);
  5995. Result := True;
  5996. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5997. end;
  5998. GetNextInstruction(p_jump, p_jump);
  5999. end;
  6000. {
  6001. Try to optimise the following:
  6002. cmp $x,### ($x and $y can be registers or constants)
  6003. je @lbl1 (only reference)
  6004. cmp $y,### (### are identical)
  6005. @Lbl:
  6006. sete %reg1
  6007. Change to:
  6008. cmp $x,###
  6009. sete %reg2 (allocate new %reg2)
  6010. cmp $y,###
  6011. sete %reg1
  6012. orb %reg2,%reg1
  6013. (dealloc %reg2)
  6014. This adds an instruction (so don't perform under -Os), but it removes
  6015. a conditional branch.
  6016. }
  6017. if not (cs_opt_size in current_settings.optimizerswitches) and
  6018. (
  6019. (hp1 = p_jump) or
  6020. GetNextInstruction(p, hp1)
  6021. ) and
  6022. MatchInstruction(hp1, A_Jcc, []) and
  6023. IsJumpToLabel(taicpu(hp1)) and
  6024. (taicpu(hp1).condition in [C_E, C_Z]) and
  6025. GetNextInstruction(hp1, hp2) and
  6026. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6027. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6028. { The first operand of CMP instructions can only be a register or
  6029. immediate anyway, so no need to check }
  6030. GetNextInstruction(hp2, p_label) and
  6031. (p_label.typ = ait_label) and
  6032. (tai_label(p_label).labsym.getrefs = 1) and
  6033. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6034. GetNextInstruction(p_label, p_dist) and
  6035. MatchInstruction(p_dist, A_SETcc, []) and
  6036. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6037. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6038. begin
  6039. TransferUsedRegs(TmpUsedRegs);
  6040. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6041. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6042. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6043. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6044. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6045. { Get the instruction after the SETcc instruction so we can
  6046. allocate a new register over the entire range }
  6047. GetNextInstruction(p_dist, hp1_dist) then
  6048. begin
  6049. { Register can appear in p if it's not used afterwards, so only
  6050. allocate between hp1 and hp1_dist }
  6051. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6052. if NewReg <> NR_NO then
  6053. begin
  6054. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6055. { Change the jump instruction into a SETcc instruction }
  6056. taicpu(hp1).opcode := A_SETcc;
  6057. taicpu(hp1).opsize := S_B;
  6058. taicpu(hp1).loadreg(0, NewReg);
  6059. { This is now a dead label }
  6060. tai_label(p_label).labsym.decrefs;
  6061. { Prefer adding before the next instruction so the FLAGS
  6062. register is deallicated first }
  6063. AsmL.InsertBefore(
  6064. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6065. hp1_dist
  6066. );
  6067. Result := True;
  6068. { Don't exit yet, as p wasn't changed and hp1, while
  6069. modified, is still intact and might be optimised by the
  6070. SETcc optimisation below }
  6071. end;
  6072. end;
  6073. end;
  6074. if taicpu(p).oper[0]^.typ = top_const then
  6075. begin
  6076. if (taicpu(p).oper[0]^.val = 0) and
  6077. (taicpu(p).oper[1]^.typ = top_reg) and
  6078. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6079. begin
  6080. hp2 := p;
  6081. FirstMatch := True;
  6082. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6083. anything meaningful once it's converted to "test %reg,%reg";
  6084. additionally, some jumps will always (or never) branch, so
  6085. evaluate every jump immediately following the
  6086. comparison, optimising the conditions if possible.
  6087. Similarly with SETcc... those that are always set to 0 or 1
  6088. are changed to MOV instructions }
  6089. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6090. (
  6091. GetNextInstruction(hp2, hp1) and
  6092. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6093. ) do
  6094. begin
  6095. FirstMatch := False;
  6096. case taicpu(hp1).condition of
  6097. C_B, C_C, C_NAE, C_O:
  6098. { For B/NAE:
  6099. Will never branch since an unsigned integer can never be below zero
  6100. For C/O:
  6101. Result cannot overflow because 0 is being subtracted
  6102. }
  6103. begin
  6104. if taicpu(hp1).opcode = A_Jcc then
  6105. begin
  6106. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6107. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6108. RemoveInstruction(hp1);
  6109. { Since hp1 was deleted, hp2 must not be updated }
  6110. Continue;
  6111. end
  6112. else
  6113. begin
  6114. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6115. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6116. taicpu(hp1).opcode := A_MOV;
  6117. taicpu(hp1).ops := 2;
  6118. taicpu(hp1).condition := C_None;
  6119. taicpu(hp1).opsize := S_B;
  6120. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6121. taicpu(hp1).loadconst(0, 0);
  6122. end;
  6123. end;
  6124. C_BE, C_NA:
  6125. begin
  6126. { Will only branch if equal to zero }
  6127. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6128. taicpu(hp1).condition := C_E;
  6129. end;
  6130. C_A, C_NBE:
  6131. begin
  6132. { Will only branch if not equal to zero }
  6133. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6134. taicpu(hp1).condition := C_NE;
  6135. end;
  6136. C_AE, C_NB, C_NC, C_NO:
  6137. begin
  6138. { Will always branch }
  6139. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6140. if taicpu(hp1).opcode = A_Jcc then
  6141. begin
  6142. MakeUnconditional(taicpu(hp1));
  6143. { Any jumps/set that follow will now be dead code }
  6144. RemoveDeadCodeAfterJump(taicpu(hp1));
  6145. Break;
  6146. end
  6147. else
  6148. begin
  6149. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6150. taicpu(hp1).opcode := A_MOV;
  6151. taicpu(hp1).ops := 2;
  6152. taicpu(hp1).condition := C_None;
  6153. taicpu(hp1).opsize := S_B;
  6154. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6155. taicpu(hp1).loadconst(0, 1);
  6156. end;
  6157. end;
  6158. C_None:
  6159. InternalError(2020012201);
  6160. C_P, C_PE, C_NP, C_PO:
  6161. { We can't handle parity checks and they should never be generated
  6162. after a general-purpose CMP (it's used in some floating-point
  6163. comparisons that don't use CMP) }
  6164. InternalError(2020012202);
  6165. else
  6166. { Zero/Equality, Sign, their complements and all of the
  6167. signed comparisons do not need to be converted };
  6168. end;
  6169. hp2 := hp1;
  6170. end;
  6171. { Convert the instruction to a TEST }
  6172. taicpu(p).opcode := A_TEST;
  6173. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6174. Result := True;
  6175. Exit;
  6176. end
  6177. else if (taicpu(p).oper[0]^.val = 1) and
  6178. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6179. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6180. begin
  6181. { Convert; To:
  6182. cmp $1,r/m cmp $0,r/m
  6183. jl @lbl jle @lbl
  6184. }
  6185. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6186. taicpu(p).oper[0]^.val := 0;
  6187. taicpu(hp1).condition := C_LE;
  6188. { If the instruction is now "cmp $0,%reg", convert it to a
  6189. TEST (and effectively do the work of the "cmp $0,%reg" in
  6190. the block above)
  6191. If it's a reference, we can get away with not setting
  6192. Result to True because he haven't evaluated the jump
  6193. in this pass yet.
  6194. }
  6195. if (taicpu(p).oper[1]^.typ = top_reg) then
  6196. begin
  6197. taicpu(p).opcode := A_TEST;
  6198. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6199. Result := True;
  6200. end;
  6201. Exit;
  6202. end
  6203. else if (taicpu(p).oper[1]^.typ = top_reg)
  6204. {$ifdef x86_64}
  6205. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6206. {$endif x86_64}
  6207. then
  6208. begin
  6209. { cmp register,$8000 neg register
  6210. je target --> jo target
  6211. .... only if register is deallocated before jump.}
  6212. case Taicpu(p).opsize of
  6213. S_B: v:=$80;
  6214. S_W: v:=$8000;
  6215. S_L: v:=qword($80000000);
  6216. else
  6217. internalerror(2013112905);
  6218. end;
  6219. if (taicpu(p).oper[0]^.val=v) and
  6220. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6221. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6222. begin
  6223. TransferUsedRegs(TmpUsedRegs);
  6224. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6225. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6226. begin
  6227. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6228. Taicpu(p).opcode:=A_NEG;
  6229. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6230. Taicpu(p).clearop(1);
  6231. Taicpu(p).ops:=1;
  6232. if Taicpu(hp1).condition=C_E then
  6233. Taicpu(hp1).condition:=C_O
  6234. else
  6235. Taicpu(hp1).condition:=C_NO;
  6236. Result:=true;
  6237. exit;
  6238. end;
  6239. end;
  6240. end;
  6241. end;
  6242. if TrySwapMovCmp(p, hp1) then
  6243. begin
  6244. Result := True;
  6245. Exit;
  6246. end;
  6247. end;
  6248. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6249. var
  6250. hp1: tai;
  6251. begin
  6252. {
  6253. remove the second (v)pxor from
  6254. pxor reg,reg
  6255. ...
  6256. pxor reg,reg
  6257. }
  6258. Result:=false;
  6259. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6260. MatchOpType(taicpu(p),top_reg,top_reg) and
  6261. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6262. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6263. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6264. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6265. begin
  6266. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6267. RemoveInstruction(hp1);
  6268. Result:=true;
  6269. Exit;
  6270. end
  6271. {
  6272. replace
  6273. pxor reg1,reg1
  6274. movapd/s reg1,reg2
  6275. dealloc reg1
  6276. by
  6277. pxor reg2,reg2
  6278. }
  6279. else if GetNextInstruction(p,hp1) and
  6280. { we mix single and double opperations here because we assume that the compiler
  6281. generates vmovapd only after double operations and vmovaps only after single operations }
  6282. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6283. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6284. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6285. (taicpu(p).oper[0]^.typ=top_reg) then
  6286. begin
  6287. TransferUsedRegs(TmpUsedRegs);
  6288. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6289. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6290. begin
  6291. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6292. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6293. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6294. RemoveInstruction(hp1);
  6295. result:=true;
  6296. end;
  6297. end;
  6298. end;
  6299. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6300. var
  6301. hp1: tai;
  6302. begin
  6303. {
  6304. remove the second (v)pxor from
  6305. (v)pxor reg,reg
  6306. ...
  6307. (v)pxor reg,reg
  6308. }
  6309. Result:=false;
  6310. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6311. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6312. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6313. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6314. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6315. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6316. begin
  6317. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6318. RemoveInstruction(hp1);
  6319. Result:=true;
  6320. Exit;
  6321. end
  6322. else
  6323. Result:=OptPass1VOP(p);
  6324. end;
  6325. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6326. var
  6327. hp1 : tai;
  6328. begin
  6329. result:=false;
  6330. { replace
  6331. IMul const,%mreg1,%mreg2
  6332. Mov %reg2,%mreg3
  6333. dealloc %mreg3
  6334. by
  6335. Imul const,%mreg1,%mreg23
  6336. }
  6337. if (taicpu(p).ops=3) and
  6338. GetNextInstruction(p,hp1) and
  6339. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6340. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6341. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6342. begin
  6343. TransferUsedRegs(TmpUsedRegs);
  6344. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6345. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6346. begin
  6347. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6348. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6349. RemoveInstruction(hp1);
  6350. result:=true;
  6351. end;
  6352. end;
  6353. end;
  6354. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6355. var
  6356. hp1 : tai;
  6357. begin
  6358. result:=false;
  6359. { replace
  6360. IMul %reg0,%reg1,%reg2
  6361. Mov %reg2,%reg3
  6362. dealloc %reg2
  6363. by
  6364. Imul %reg0,%reg1,%reg3
  6365. }
  6366. if GetNextInstruction(p,hp1) and
  6367. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6368. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6369. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6370. begin
  6371. TransferUsedRegs(TmpUsedRegs);
  6372. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6373. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6374. begin
  6375. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6376. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6377. RemoveInstruction(hp1);
  6378. result:=true;
  6379. end;
  6380. end;
  6381. end;
  6382. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6383. var
  6384. hp1: tai;
  6385. begin
  6386. Result:=false;
  6387. { get rid of
  6388. (v)cvtss2sd reg0,<reg1,>reg2
  6389. (v)cvtss2sd reg2,<reg2,>reg0
  6390. }
  6391. if GetNextInstruction(p,hp1) and
  6392. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6393. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6394. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6395. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6396. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6397. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6398. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6399. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6400. )
  6401. ) then
  6402. begin
  6403. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6404. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6405. begin
  6406. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6407. RemoveCurrentP(p);
  6408. RemoveInstruction(hp1);
  6409. end
  6410. else
  6411. begin
  6412. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6413. if taicpu(hp1).opcode=A_CVTSD2SS then
  6414. begin
  6415. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6416. taicpu(p).opcode:=A_MOVAPS;
  6417. end
  6418. else
  6419. begin
  6420. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6421. taicpu(p).opcode:=A_VMOVAPS;
  6422. end;
  6423. taicpu(p).ops:=2;
  6424. RemoveInstruction(hp1);
  6425. end;
  6426. Result:=true;
  6427. Exit;
  6428. end;
  6429. end;
  6430. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6431. var
  6432. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6433. ThisReg: TRegister;
  6434. begin
  6435. Result := False;
  6436. if not GetNextInstruction(p,hp1) then
  6437. Exit;
  6438. {
  6439. convert
  6440. j<c> .L1
  6441. mov 1,reg
  6442. jmp .L2
  6443. .L1
  6444. mov 0,reg
  6445. .L2
  6446. into
  6447. mov 0,reg
  6448. set<not(c)> reg
  6449. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6450. would destroy the flag contents
  6451. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6452. executed at the same time as a previous comparison.
  6453. set<not(c)> reg
  6454. movzx reg, reg
  6455. }
  6456. if MatchInstruction(hp1,A_MOV,[]) and
  6457. (taicpu(hp1).oper[0]^.typ = top_const) and
  6458. (
  6459. (
  6460. (taicpu(hp1).oper[1]^.typ = top_reg)
  6461. {$ifdef i386}
  6462. { Under i386, ESI, EDI, EBP and ESP
  6463. don't have an 8-bit representation }
  6464. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6465. {$endif i386}
  6466. ) or (
  6467. {$ifdef i386}
  6468. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6469. {$endif i386}
  6470. (taicpu(hp1).opsize = S_B)
  6471. )
  6472. ) and
  6473. GetNextInstruction(hp1,hp2) and
  6474. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6475. GetNextInstruction(hp2,hp3) and
  6476. SkipAligns(hp3, hp3) and
  6477. (hp3.typ=ait_label) and
  6478. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6479. GetNextInstruction(hp3,hp4) and
  6480. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6481. (taicpu(hp4).oper[0]^.typ = top_const) and
  6482. (
  6483. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6484. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6485. ) and
  6486. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6487. GetNextInstruction(hp4,hp5) and
  6488. SkipAligns(hp5, hp5) and
  6489. (hp5.typ=ait_label) and
  6490. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6491. begin
  6492. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6493. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6494. tai_label(hp3).labsym.DecRefs;
  6495. { If this isn't the only reference to the middle label, we can
  6496. still make a saving - only that the first jump and everything
  6497. that follows will remain. }
  6498. if (tai_label(hp3).labsym.getrefs = 0) then
  6499. begin
  6500. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6501. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6502. else
  6503. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6504. { remove jump, first label and second MOV (also catching any aligns) }
  6505. repeat
  6506. if not GetNextInstruction(hp2, hp3) then
  6507. InternalError(2021040810);
  6508. RemoveInstruction(hp2);
  6509. hp2 := hp3;
  6510. until hp2 = hp5;
  6511. { Don't decrement reference count before the removal loop
  6512. above, otherwise GetNextInstruction won't stop on the
  6513. the label }
  6514. tai_label(hp5).labsym.DecRefs;
  6515. end
  6516. else
  6517. begin
  6518. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6519. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6520. else
  6521. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6522. end;
  6523. taicpu(p).opcode:=A_SETcc;
  6524. taicpu(p).opsize:=S_B;
  6525. taicpu(p).is_jmp:=False;
  6526. if taicpu(hp1).opsize=S_B then
  6527. begin
  6528. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6529. if taicpu(hp1).oper[1]^.typ = top_reg then
  6530. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6531. RemoveInstruction(hp1);
  6532. end
  6533. else
  6534. begin
  6535. { Will be a register because the size can't be S_B otherwise }
  6536. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6537. taicpu(p).loadreg(0, ThisReg);
  6538. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6539. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6540. begin
  6541. case taicpu(hp1).opsize of
  6542. S_W:
  6543. taicpu(hp1).opsize := S_BW;
  6544. S_L:
  6545. taicpu(hp1).opsize := S_BL;
  6546. {$ifdef x86_64}
  6547. S_Q:
  6548. begin
  6549. taicpu(hp1).opsize := S_BL;
  6550. { Change the destination register to 32-bit }
  6551. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6552. end;
  6553. {$endif x86_64}
  6554. else
  6555. InternalError(2021040820);
  6556. end;
  6557. taicpu(hp1).opcode := A_MOVZX;
  6558. taicpu(hp1).loadreg(0, ThisReg);
  6559. end
  6560. else
  6561. begin
  6562. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6563. { hp1 is already a MOV instruction with the correct register }
  6564. taicpu(hp1).loadconst(0, 0);
  6565. { Inserting it right before p will guarantee that the flags are also tracked }
  6566. asml.Remove(hp1);
  6567. asml.InsertBefore(hp1, p);
  6568. end;
  6569. end;
  6570. Result:=true;
  6571. exit;
  6572. end
  6573. else if (hp1.typ = ait_label) then
  6574. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6575. end;
  6576. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6577. var
  6578. hp1, hp2, hp3: tai;
  6579. SourceRef, TargetRef: TReference;
  6580. CurrentReg: TRegister;
  6581. begin
  6582. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6583. if not UseAVX then
  6584. InternalError(2021100501);
  6585. Result := False;
  6586. { Look for the following to simplify:
  6587. vmovdqa/u x(mem1), %xmmreg
  6588. vmovdqa/u %xmmreg, y(mem2)
  6589. vmovdqa/u x+16(mem1), %xmmreg
  6590. vmovdqa/u %xmmreg, y+16(mem2)
  6591. Change to:
  6592. vmovdqa/u x(mem1), %ymmreg
  6593. vmovdqa/u %ymmreg, y(mem2)
  6594. vpxor %ymmreg, %ymmreg, %ymmreg
  6595. ( The VPXOR instruction is to zero the upper half, thus removing the
  6596. need to call the potentially expensive VZEROUPPER instruction. Other
  6597. peephole optimisations can remove VPXOR if it's unnecessary )
  6598. }
  6599. TransferUsedRegs(TmpUsedRegs);
  6600. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6601. { NOTE: In the optimisations below, if the references dictate that an
  6602. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6603. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6604. if (taicpu(p).opsize = S_XMM) and
  6605. MatchOpType(taicpu(p), top_ref, top_reg) and
  6606. GetNextInstruction(p, hp1) and
  6607. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6608. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6609. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6610. begin
  6611. SourceRef := taicpu(p).oper[0]^.ref^;
  6612. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6613. if GetNextInstruction(hp1, hp2) and
  6614. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6615. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6616. begin
  6617. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6618. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6619. Inc(SourceRef.offset, 16);
  6620. { Reuse the register in the first block move }
  6621. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6622. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6623. begin
  6624. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6625. Inc(TargetRef.offset, 16);
  6626. if GetNextInstruction(hp2, hp3) and
  6627. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6628. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6629. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6630. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6631. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6632. begin
  6633. { Update the register tracking to the new size }
  6634. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6635. { Remember that the offsets are 16 ahead }
  6636. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6637. if not (
  6638. ((SourceRef.offset mod 32) = 16) and
  6639. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6640. ) then
  6641. taicpu(p).opcode := A_VMOVDQU;
  6642. taicpu(p).opsize := S_YMM;
  6643. taicpu(p).oper[1]^.reg := CurrentReg;
  6644. if not (
  6645. ((TargetRef.offset mod 32) = 16) and
  6646. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6647. ) then
  6648. taicpu(hp1).opcode := A_VMOVDQU;
  6649. taicpu(hp1).opsize := S_YMM;
  6650. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6651. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6652. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6653. if (pi_uses_ymm in current_procinfo.flags) then
  6654. RemoveInstruction(hp2)
  6655. else
  6656. begin
  6657. taicpu(hp2).opcode := A_VPXOR;
  6658. taicpu(hp2).opsize := S_YMM;
  6659. taicpu(hp2).loadreg(0, CurrentReg);
  6660. taicpu(hp2).loadreg(1, CurrentReg);
  6661. taicpu(hp2).loadreg(2, CurrentReg);
  6662. taicpu(hp2).ops := 3;
  6663. end;
  6664. RemoveInstruction(hp3);
  6665. Result := True;
  6666. Exit;
  6667. end;
  6668. end
  6669. else
  6670. begin
  6671. { See if the next references are 16 less rather than 16 greater }
  6672. Dec(SourceRef.offset, 32); { -16 the other way }
  6673. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6674. begin
  6675. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6676. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6677. if GetNextInstruction(hp2, hp3) and
  6678. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6679. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6680. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6681. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6682. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6683. begin
  6684. { Update the register tracking to the new size }
  6685. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6686. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6687. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6688. if not(
  6689. ((SourceRef.offset mod 32) = 0) and
  6690. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6691. ) then
  6692. taicpu(hp2).opcode := A_VMOVDQU;
  6693. taicpu(hp2).opsize := S_YMM;
  6694. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6695. if not (
  6696. ((TargetRef.offset mod 32) = 0) and
  6697. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6698. ) then
  6699. taicpu(hp3).opcode := A_VMOVDQU;
  6700. taicpu(hp3).opsize := S_YMM;
  6701. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6702. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6703. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6704. if (pi_uses_ymm in current_procinfo.flags) then
  6705. RemoveInstruction(hp1)
  6706. else
  6707. begin
  6708. taicpu(hp1).opcode := A_VPXOR;
  6709. taicpu(hp1).opsize := S_YMM;
  6710. taicpu(hp1).loadreg(0, CurrentReg);
  6711. taicpu(hp1).loadreg(1, CurrentReg);
  6712. taicpu(hp1).loadreg(2, CurrentReg);
  6713. taicpu(hp1).ops := 3;
  6714. Asml.Remove(hp1);
  6715. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6716. end;
  6717. RemoveCurrentP(p, hp2);
  6718. Result := True;
  6719. Exit;
  6720. end;
  6721. end;
  6722. end;
  6723. end;
  6724. end;
  6725. end;
  6726. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6727. var
  6728. hp2, hp3, first_assignment: tai;
  6729. IncCount, OperIdx: Integer;
  6730. OrigLabel: TAsmLabel;
  6731. begin
  6732. Count := 0;
  6733. Result := False;
  6734. first_assignment := nil;
  6735. if (LoopCount >= 20) then
  6736. begin
  6737. { Guard against infinite loops }
  6738. Exit;
  6739. end;
  6740. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6741. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6742. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6743. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6744. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6745. Exit;
  6746. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6747. {
  6748. change
  6749. jmp .L1
  6750. ...
  6751. .L1:
  6752. mov ##, ## ( multiple movs possible )
  6753. jmp/ret
  6754. into
  6755. mov ##, ##
  6756. jmp/ret
  6757. }
  6758. if not Assigned(hp1) then
  6759. begin
  6760. hp1 := GetLabelWithSym(OrigLabel);
  6761. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6762. Exit;
  6763. end;
  6764. hp2 := hp1;
  6765. while Assigned(hp2) do
  6766. begin
  6767. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6768. SkipLabels(hp2,hp2);
  6769. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6770. Break;
  6771. case taicpu(hp2).opcode of
  6772. A_MOVSS:
  6773. begin
  6774. if taicpu(hp2).ops = 0 then
  6775. { Wrong MOVSS }
  6776. Break;
  6777. Inc(Count);
  6778. if Count >= 5 then
  6779. { Too many to be worthwhile }
  6780. Break;
  6781. GetNextInstruction(hp2, hp2);
  6782. Continue;
  6783. end;
  6784. A_MOV,
  6785. A_MOVD,
  6786. A_MOVQ,
  6787. A_MOVSX,
  6788. {$ifdef x86_64}
  6789. A_MOVSXD,
  6790. {$endif x86_64}
  6791. A_MOVZX,
  6792. A_MOVAPS,
  6793. A_MOVUPS,
  6794. A_MOVSD,
  6795. A_MOVAPD,
  6796. A_MOVUPD,
  6797. A_MOVDQA,
  6798. A_MOVDQU,
  6799. A_VMOVSS,
  6800. A_VMOVAPS,
  6801. A_VMOVUPS,
  6802. A_VMOVSD,
  6803. A_VMOVAPD,
  6804. A_VMOVUPD,
  6805. A_VMOVDQA,
  6806. A_VMOVDQU:
  6807. begin
  6808. Inc(Count);
  6809. if Count >= 5 then
  6810. { Too many to be worthwhile }
  6811. Break;
  6812. GetNextInstruction(hp2, hp2);
  6813. Continue;
  6814. end;
  6815. A_JMP:
  6816. begin
  6817. { Guard against infinite loops }
  6818. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6819. Exit;
  6820. { Analyse this jump first in case it also duplicates assignments }
  6821. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6822. begin
  6823. { Something did change! }
  6824. Result := True;
  6825. Inc(Count, IncCount);
  6826. if Count >= 5 then
  6827. begin
  6828. { Too many to be worthwhile }
  6829. Exit;
  6830. end;
  6831. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6832. Break;
  6833. end;
  6834. Result := True;
  6835. Break;
  6836. end;
  6837. A_RET:
  6838. begin
  6839. Result := True;
  6840. Break;
  6841. end;
  6842. else
  6843. Break;
  6844. end;
  6845. end;
  6846. if Result then
  6847. begin
  6848. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6849. if Count = 0 then
  6850. begin
  6851. Result := False;
  6852. Exit;
  6853. end;
  6854. hp3 := p;
  6855. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6856. while True do
  6857. begin
  6858. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6859. SkipLabels(hp1,hp1);
  6860. if (hp1.typ <> ait_instruction) then
  6861. InternalError(2021040720);
  6862. case taicpu(hp1).opcode of
  6863. A_JMP:
  6864. begin
  6865. { Change the original jump to the new destination }
  6866. OrigLabel.decrefs;
  6867. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6868. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6869. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6870. if not Assigned(first_assignment) then
  6871. InternalError(2021040810)
  6872. else
  6873. p := first_assignment;
  6874. Exit;
  6875. end;
  6876. A_RET:
  6877. begin
  6878. { Now change the jump into a RET instruction }
  6879. ConvertJumpToRET(p, hp1);
  6880. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6881. if not Assigned(first_assignment) then
  6882. InternalError(2021040811)
  6883. else
  6884. p := first_assignment;
  6885. Exit;
  6886. end;
  6887. else
  6888. begin
  6889. { Duplicate the MOV instruction }
  6890. hp3:=tai(hp1.getcopy);
  6891. if first_assignment = nil then
  6892. first_assignment := hp3;
  6893. asml.InsertBefore(hp3, p);
  6894. { Make sure the compiler knows about any final registers written here }
  6895. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6896. with taicpu(hp3).oper[OperIdx]^ do
  6897. begin
  6898. case typ of
  6899. top_ref:
  6900. begin
  6901. if (ref^.base <> NR_NO) and
  6902. (getsupreg(ref^.base) <> RS_ESP) and
  6903. (getsupreg(ref^.base) <> RS_EBP)
  6904. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6905. then
  6906. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6907. if (ref^.index <> NR_NO) and
  6908. (getsupreg(ref^.index) <> RS_ESP) and
  6909. (getsupreg(ref^.index) <> RS_EBP)
  6910. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6911. (ref^.index <> ref^.base) then
  6912. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6913. end;
  6914. top_reg:
  6915. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6916. else
  6917. ;
  6918. end;
  6919. end;
  6920. end;
  6921. end;
  6922. if not GetNextInstruction(hp1, hp1) then
  6923. { Should have dropped out earlier }
  6924. InternalError(2021040710);
  6925. end;
  6926. end;
  6927. end;
  6928. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6929. var
  6930. hp2: tai;
  6931. X: Integer;
  6932. const
  6933. WriteOp: array[0..3] of set of TInsChange = (
  6934. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6935. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6936. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6937. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6938. RegWriteFlags: array[0..7] of set of TInsChange = (
  6939. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6940. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6941. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6942. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6943. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6944. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6945. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6946. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6947. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6948. begin
  6949. { If we have something like:
  6950. cmp ###,%reg1
  6951. mov 0,%reg2
  6952. And no modified registers are shared, move the instruction to before
  6953. the comparison as this means it can be optimised without worrying
  6954. about the FLAGS register. (CMP/MOV is generated by
  6955. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6956. As long as the second instruction doesn't use the flags or one of the
  6957. registers used by CMP or TEST (also check any references that use the
  6958. registers), then it can be moved prior to the comparison.
  6959. }
  6960. Result := False;
  6961. if (hp1.typ <> ait_instruction) or
  6962. taicpu(hp1).is_jmp or
  6963. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6964. Exit;
  6965. { NOP is a pipeline fence, likely marking the beginning of the function
  6966. epilogue, so drop out. Similarly, drop out if POP or RET are
  6967. encountered }
  6968. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6969. Exit;
  6970. if (taicpu(hp1).opcode = A_MOVSS) and
  6971. (taicpu(hp1).ops = 0) then
  6972. { Wrong MOVSS }
  6973. Exit;
  6974. { Check for writes to specific registers first }
  6975. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6976. for X := 0 to 7 do
  6977. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6978. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6979. Exit;
  6980. for X := 0 to taicpu(hp1).ops - 1 do
  6981. begin
  6982. { Check to see if this operand writes to something }
  6983. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6984. { And matches something in the CMP/TEST instruction }
  6985. (
  6986. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6987. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6988. (
  6989. { If it's a register, make sure the register written to doesn't
  6990. appear in the cmp instruction as part of a reference }
  6991. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6992. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6993. )
  6994. ) then
  6995. Exit;
  6996. end;
  6997. { The instruction can be safely moved }
  6998. asml.Remove(hp1);
  6999. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  7000. if not GetLastInstruction(p, hp2) then
  7001. asml.InsertBefore(hp1, p)
  7002. else
  7003. asml.InsertAfter(hp1, hp2);
  7004. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7005. for X := 0 to taicpu(hp1).ops - 1 do
  7006. case taicpu(hp1).oper[X]^.typ of
  7007. top_reg:
  7008. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7009. top_ref:
  7010. begin
  7011. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7012. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7013. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7014. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7015. end;
  7016. else
  7017. ;
  7018. end;
  7019. if taicpu(hp1).opcode = A_LEA then
  7020. { The flags will be overwritten by the CMP/TEST instruction }
  7021. ConvertLEA(taicpu(hp1));
  7022. Result := True;
  7023. end;
  7024. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7025. function IsXCHGAcceptable: Boolean; inline;
  7026. begin
  7027. { Always accept if optimising for size }
  7028. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7029. (
  7030. {$ifdef x86_64}
  7031. { XCHG takes 3 cycles on AMD Athlon64 }
  7032. (current_settings.optimizecputype >= cpu_core_i)
  7033. {$else x86_64}
  7034. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7035. than 3, so it becomes a saving compared to three MOVs with two of
  7036. them able to execute simultaneously. [Kit] }
  7037. (current_settings.optimizecputype >= cpu_PentiumM)
  7038. {$endif x86_64}
  7039. );
  7040. end;
  7041. var
  7042. NewRef: TReference;
  7043. hp1, hp2, hp3, hp4: Tai;
  7044. {$ifndef x86_64}
  7045. OperIdx: Integer;
  7046. {$endif x86_64}
  7047. NewInstr : Taicpu;
  7048. NewAligh : Tai_align;
  7049. DestLabel: TAsmLabel;
  7050. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7051. var
  7052. NextInstr: tai;
  7053. begin
  7054. Result := False;
  7055. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7056. if not GetNextInstruction(InputInstr, NextInstr) or
  7057. (
  7058. { The FLAGS register isn't always tracked properly, so do not
  7059. perform this optimisation if a conditional statement follows }
  7060. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7061. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7062. ) then
  7063. begin
  7064. reference_reset(NewRef, 1, []);
  7065. NewRef.base := taicpu(p).oper[0]^.reg;
  7066. NewRef.scalefactor := 1;
  7067. if taicpu(InputInstr).opcode = A_ADD then
  7068. begin
  7069. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7070. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7071. end
  7072. else
  7073. begin
  7074. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7075. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7076. end;
  7077. taicpu(p).opcode := A_LEA;
  7078. taicpu(p).loadref(0, NewRef);
  7079. RemoveInstruction(InputInstr);
  7080. Result := True;
  7081. end;
  7082. end;
  7083. begin
  7084. Result:=false;
  7085. { This optimisation adds an instruction, so only do it for speed }
  7086. if not (cs_opt_size in current_settings.optimizerswitches) and
  7087. MatchOpType(taicpu(p), top_const, top_reg) and
  7088. (taicpu(p).oper[0]^.val = 0) then
  7089. begin
  7090. { To avoid compiler warning }
  7091. DestLabel := nil;
  7092. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7093. InternalError(2021040750);
  7094. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7095. Exit;
  7096. case hp1.typ of
  7097. ait_label:
  7098. begin
  7099. { Change:
  7100. mov $0,%reg mov $0,%reg
  7101. @Lbl1: @Lbl1:
  7102. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7103. je @Lbl2 jne @Lbl2
  7104. To: To:
  7105. mov $0,%reg mov $0,%reg
  7106. jmp @Lbl2 jmp @Lbl3
  7107. (align) (align)
  7108. @Lbl1: @Lbl1:
  7109. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7110. je @Lbl2 je @Lbl2
  7111. @Lbl3: <-- Only if label exists
  7112. (Not if it's optimised for size)
  7113. }
  7114. if not GetNextInstruction(hp1, hp2) then
  7115. Exit;
  7116. if not (cs_opt_size in current_settings.optimizerswitches) and
  7117. (hp2.typ = ait_instruction) and
  7118. (
  7119. { Register sizes must exactly match }
  7120. (
  7121. (taicpu(hp2).opcode = A_CMP) and
  7122. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7123. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7124. ) or (
  7125. (taicpu(hp2).opcode = A_TEST) and
  7126. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7127. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7128. )
  7129. ) and GetNextInstruction(hp2, hp3) and
  7130. (hp3.typ = ait_instruction) and
  7131. (taicpu(hp3).opcode = A_JCC) and
  7132. (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
  7133. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7134. begin
  7135. { Check condition of jump }
  7136. { Always true? }
  7137. if condition_in(C_E, taicpu(hp3).condition) then
  7138. begin
  7139. { Copy label symbol and obtain matching label entry for the
  7140. conditional jump, as this will be our destination}
  7141. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7142. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7143. Result := True;
  7144. end
  7145. { Always false? }
  7146. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7147. begin
  7148. { This is only worth it if there's a jump to take }
  7149. case hp2.typ of
  7150. ait_instruction:
  7151. begin
  7152. if taicpu(hp2).opcode = A_JMP then
  7153. begin
  7154. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7155. { An unconditional jump follows the conditional jump which will always be false,
  7156. so use this jump's destination for the new jump }
  7157. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7158. Result := True;
  7159. end
  7160. else if taicpu(hp2).opcode = A_JCC then
  7161. begin
  7162. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7163. if condition_in(C_E, taicpu(hp2).condition) then
  7164. begin
  7165. { A second conditional jump follows the conditional jump which will always be false,
  7166. while the second jump is always True, so use this jump's destination for the new jump }
  7167. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7168. Result := True;
  7169. end;
  7170. { Don't risk it if the jump isn't always true (Result remains False) }
  7171. end;
  7172. end;
  7173. else
  7174. { If anything else don't optimise };
  7175. end;
  7176. end;
  7177. if Result then
  7178. begin
  7179. { Just so we have something to insert as a paremeter}
  7180. reference_reset(NewRef, 1, []);
  7181. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7182. { Now actually load the correct parameter }
  7183. NewInstr.loadsymbol(0, DestLabel, 0);
  7184. { Get instruction before original label (may not be p under -O3) }
  7185. if not GetLastInstruction(hp1, hp2) then
  7186. { Shouldn't fail here }
  7187. InternalError(2021040701);
  7188. DestLabel.increfs;
  7189. AsmL.InsertAfter(NewInstr, hp2);
  7190. { Add new alignment field }
  7191. (* AsmL.InsertAfter(
  7192. cai_align.create_max(
  7193. current_settings.alignment.jumpalign,
  7194. current_settings.alignment.jumpalignskipmax
  7195. ),
  7196. NewInstr
  7197. ); *)
  7198. end;
  7199. Exit;
  7200. end;
  7201. end;
  7202. else
  7203. ;
  7204. end;
  7205. end;
  7206. if not GetNextInstruction(p, hp1) then
  7207. Exit;
  7208. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7209. and DoMovCmpMemOpt(p, hp1, True) then
  7210. begin
  7211. Result := True;
  7212. Exit;
  7213. end
  7214. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7215. begin
  7216. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7217. further, but we can't just put this jump optimisation in pass 1
  7218. because it tends to perform worse when conditional jumps are
  7219. nearby (e.g. when converting CMOV instructions). [Kit] }
  7220. if OptPass2JMP(hp1) then
  7221. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7222. Result := OptPass1MOV(p)
  7223. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7224. returned True and the instruction is still a MOV, thus checking
  7225. the optimisations below }
  7226. { If OptPass2JMP returned False, no optimisations were done to
  7227. the jump and there are no further optimisations that can be done
  7228. to the MOV instruction on this pass }
  7229. end
  7230. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7231. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7232. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7233. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7234. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7235. begin
  7236. { Change:
  7237. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7238. addl/q $x,%reg2 subl/q $x,%reg2
  7239. To:
  7240. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7241. }
  7242. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7243. { be lazy, checking separately for sub would be slightly better }
  7244. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7245. begin
  7246. TransferUsedRegs(TmpUsedRegs);
  7247. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7248. if TryMovArith2Lea(hp1) then
  7249. begin
  7250. Result := True;
  7251. Exit;
  7252. end
  7253. end
  7254. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7255. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7256. { Same as above, but also adds or subtracts to %reg2 in between.
  7257. It's still valid as long as the flags aren't in use }
  7258. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7259. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7260. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7261. { be lazy, checking separately for sub would be slightly better }
  7262. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7263. begin
  7264. TransferUsedRegs(TmpUsedRegs);
  7265. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7266. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7267. if TryMovArith2Lea(hp2) then
  7268. begin
  7269. Result := True;
  7270. Exit;
  7271. end;
  7272. end;
  7273. end
  7274. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7275. {$ifdef x86_64}
  7276. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7277. {$else x86_64}
  7278. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7279. {$endif x86_64}
  7280. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7281. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7282. { mov reg1, reg2 mov reg1, reg2
  7283. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7284. begin
  7285. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7286. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7287. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7288. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7289. TransferUsedRegs(TmpUsedRegs);
  7290. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7291. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7292. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7293. then
  7294. begin
  7295. RemoveCurrentP(p, hp1);
  7296. Result:=true;
  7297. end;
  7298. exit;
  7299. end
  7300. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7301. IsXCHGAcceptable and
  7302. { XCHG doesn't support 8-byte registers }
  7303. (taicpu(p).opsize <> S_B) and
  7304. MatchInstruction(hp1, A_MOV, []) and
  7305. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7306. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7307. GetNextInstruction(hp1, hp2) and
  7308. MatchInstruction(hp2, A_MOV, []) and
  7309. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7310. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7311. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7312. begin
  7313. { mov %reg1,%reg2
  7314. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7315. mov %reg2,%reg3
  7316. (%reg2 not used afterwards)
  7317. Note that xchg takes 3 cycles to execute, and generally mov's take
  7318. only one cycle apiece, but the first two mov's can be executed in
  7319. parallel, only taking 2 cycles overall. Older processors should
  7320. therefore only optimise for size. [Kit]
  7321. }
  7322. TransferUsedRegs(TmpUsedRegs);
  7323. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7324. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7325. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7326. begin
  7327. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7328. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7329. taicpu(hp1).opcode := A_XCHG;
  7330. RemoveCurrentP(p, hp1);
  7331. RemoveInstruction(hp2);
  7332. Result := True;
  7333. Exit;
  7334. end;
  7335. end
  7336. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7337. MatchInstruction(hp1, A_SAR, []) then
  7338. begin
  7339. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7340. begin
  7341. { the use of %edx also covers the opsize being S_L }
  7342. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7343. begin
  7344. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7345. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7346. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7347. begin
  7348. { Change:
  7349. movl %eax,%edx
  7350. sarl $31,%edx
  7351. To:
  7352. cltd
  7353. }
  7354. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7355. RemoveInstruction(hp1);
  7356. taicpu(p).opcode := A_CDQ;
  7357. taicpu(p).opsize := S_NO;
  7358. taicpu(p).clearop(1);
  7359. taicpu(p).clearop(0);
  7360. taicpu(p).ops:=0;
  7361. Result := True;
  7362. end
  7363. else if (cs_opt_size in current_settings.optimizerswitches) and
  7364. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7365. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7366. begin
  7367. { Change:
  7368. movl %edx,%eax
  7369. sarl $31,%edx
  7370. To:
  7371. movl %edx,%eax
  7372. cltd
  7373. Note that this creates a dependency between the two instructions,
  7374. so only perform if optimising for size.
  7375. }
  7376. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7377. taicpu(hp1).opcode := A_CDQ;
  7378. taicpu(hp1).opsize := S_NO;
  7379. taicpu(hp1).clearop(1);
  7380. taicpu(hp1).clearop(0);
  7381. taicpu(hp1).ops:=0;
  7382. end;
  7383. {$ifndef x86_64}
  7384. end
  7385. { Don't bother if CMOV is supported, because a more optimal
  7386. sequence would have been generated for the Abs() intrinsic }
  7387. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7388. { the use of %eax also covers the opsize being S_L }
  7389. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7390. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7391. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7392. GetNextInstruction(hp1, hp2) and
  7393. MatchInstruction(hp2, A_XOR, [S_L]) and
  7394. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7395. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7396. GetNextInstruction(hp2, hp3) and
  7397. MatchInstruction(hp3, A_SUB, [S_L]) and
  7398. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7399. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7400. begin
  7401. { Change:
  7402. movl %eax,%edx
  7403. sarl $31,%eax
  7404. xorl %eax,%edx
  7405. subl %eax,%edx
  7406. (Instruction that uses %edx)
  7407. (%eax deallocated)
  7408. (%edx deallocated)
  7409. To:
  7410. cltd
  7411. xorl %edx,%eax <-- Note the registers have swapped
  7412. subl %edx,%eax
  7413. (Instruction that uses %eax) <-- %eax rather than %edx
  7414. }
  7415. TransferUsedRegs(TmpUsedRegs);
  7416. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7417. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7418. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7419. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7420. begin
  7421. if GetNextInstruction(hp3, hp4) and
  7422. not RegModifiedByInstruction(NR_EDX, hp4) and
  7423. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7424. begin
  7425. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7426. taicpu(p).opcode := A_CDQ;
  7427. taicpu(p).clearop(1);
  7428. taicpu(p).clearop(0);
  7429. taicpu(p).ops:=0;
  7430. RemoveInstruction(hp1);
  7431. taicpu(hp2).loadreg(0, NR_EDX);
  7432. taicpu(hp2).loadreg(1, NR_EAX);
  7433. taicpu(hp3).loadreg(0, NR_EDX);
  7434. taicpu(hp3).loadreg(1, NR_EAX);
  7435. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7436. { Convert references in the following instruction (hp4) from %edx to %eax }
  7437. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7438. with taicpu(hp4).oper[OperIdx]^ do
  7439. case typ of
  7440. top_reg:
  7441. if getsupreg(reg) = RS_EDX then
  7442. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7443. top_ref:
  7444. begin
  7445. if getsupreg(reg) = RS_EDX then
  7446. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7447. if getsupreg(reg) = RS_EDX then
  7448. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7449. end;
  7450. else
  7451. ;
  7452. end;
  7453. end;
  7454. end;
  7455. {$else x86_64}
  7456. end;
  7457. end
  7458. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7459. { the use of %rdx also covers the opsize being S_Q }
  7460. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7461. begin
  7462. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7463. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7464. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7465. begin
  7466. { Change:
  7467. movq %rax,%rdx
  7468. sarq $63,%rdx
  7469. To:
  7470. cqto
  7471. }
  7472. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7473. RemoveInstruction(hp1);
  7474. taicpu(p).opcode := A_CQO;
  7475. taicpu(p).opsize := S_NO;
  7476. taicpu(p).clearop(1);
  7477. taicpu(p).clearop(0);
  7478. taicpu(p).ops:=0;
  7479. Result := True;
  7480. end
  7481. else if (cs_opt_size in current_settings.optimizerswitches) and
  7482. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7483. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7484. begin
  7485. { Change:
  7486. movq %rdx,%rax
  7487. sarq $63,%rdx
  7488. To:
  7489. movq %rdx,%rax
  7490. cqto
  7491. Note that this creates a dependency between the two instructions,
  7492. so only perform if optimising for size.
  7493. }
  7494. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7495. taicpu(hp1).opcode := A_CQO;
  7496. taicpu(hp1).opsize := S_NO;
  7497. taicpu(hp1).clearop(1);
  7498. taicpu(hp1).clearop(0);
  7499. taicpu(hp1).ops:=0;
  7500. {$endif x86_64}
  7501. end;
  7502. end;
  7503. end
  7504. else if MatchInstruction(hp1, A_MOV, []) and
  7505. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7506. { Though "GetNextInstruction" could be factored out, along with
  7507. the instructions that depend on hp2, it is an expensive call that
  7508. should be delayed for as long as possible, hence we do cheaper
  7509. checks first that are likely to be False. [Kit] }
  7510. begin
  7511. if (
  7512. (
  7513. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7514. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7515. (
  7516. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7517. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7518. )
  7519. ) or
  7520. (
  7521. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7522. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7523. (
  7524. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7525. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7526. )
  7527. )
  7528. ) and
  7529. GetNextInstruction(hp1, hp2) and
  7530. MatchInstruction(hp2, A_SAR, []) and
  7531. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7532. begin
  7533. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7534. begin
  7535. { Change:
  7536. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7537. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7538. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7539. To:
  7540. movl r/m,%eax <- Note the change in register
  7541. cltd
  7542. }
  7543. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7544. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7545. taicpu(p).loadreg(1, NR_EAX);
  7546. taicpu(hp1).opcode := A_CDQ;
  7547. taicpu(hp1).clearop(1);
  7548. taicpu(hp1).clearop(0);
  7549. taicpu(hp1).ops:=0;
  7550. RemoveInstruction(hp2);
  7551. (*
  7552. {$ifdef x86_64}
  7553. end
  7554. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7555. { This code sequence does not get generated - however it might become useful
  7556. if and when 128-bit signed integer types make an appearance, so the code
  7557. is kept here for when it is eventually needed. [Kit] }
  7558. (
  7559. (
  7560. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7561. (
  7562. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7563. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7564. )
  7565. ) or
  7566. (
  7567. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7568. (
  7569. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7570. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7571. )
  7572. )
  7573. ) and
  7574. GetNextInstruction(hp1, hp2) and
  7575. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7576. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7577. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7578. begin
  7579. { Change:
  7580. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7581. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7582. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7583. To:
  7584. movq r/m,%rax <- Note the change in register
  7585. cqto
  7586. }
  7587. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7588. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7589. taicpu(p).loadreg(1, NR_RAX);
  7590. taicpu(hp1).opcode := A_CQO;
  7591. taicpu(hp1).clearop(1);
  7592. taicpu(hp1).clearop(0);
  7593. taicpu(hp1).ops:=0;
  7594. RemoveInstruction(hp2);
  7595. {$endif x86_64}
  7596. *)
  7597. end;
  7598. end;
  7599. {$ifdef x86_64}
  7600. end
  7601. else if (taicpu(p).opsize = S_L) and
  7602. (taicpu(p).oper[1]^.typ = top_reg) and
  7603. (
  7604. MatchInstruction(hp1, A_MOV,[]) and
  7605. (taicpu(hp1).opsize = S_L) and
  7606. (taicpu(hp1).oper[1]^.typ = top_reg)
  7607. ) and (
  7608. GetNextInstruction(hp1, hp2) and
  7609. (tai(hp2).typ=ait_instruction) and
  7610. (taicpu(hp2).opsize = S_Q) and
  7611. (
  7612. (
  7613. MatchInstruction(hp2, A_ADD,[]) and
  7614. (taicpu(hp2).opsize = S_Q) and
  7615. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7616. (
  7617. (
  7618. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7619. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7620. ) or (
  7621. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7622. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7623. )
  7624. )
  7625. ) or (
  7626. MatchInstruction(hp2, A_LEA,[]) and
  7627. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7628. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7629. (
  7630. (
  7631. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7632. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7633. ) or (
  7634. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7635. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7636. )
  7637. ) and (
  7638. (
  7639. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7640. ) or (
  7641. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7642. )
  7643. )
  7644. )
  7645. )
  7646. ) and (
  7647. GetNextInstruction(hp2, hp3) and
  7648. MatchInstruction(hp3, A_SHR,[]) and
  7649. (taicpu(hp3).opsize = S_Q) and
  7650. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7651. (taicpu(hp3).oper[0]^.val = 1) and
  7652. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7653. ) then
  7654. begin
  7655. { Change movl x, reg1d movl x, reg1d
  7656. movl y, reg2d movl y, reg2d
  7657. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7658. shrq $1, reg1q shrq $1, reg1q
  7659. ( reg1d and reg2d can be switched around in the first two instructions )
  7660. To movl x, reg1d
  7661. addl y, reg1d
  7662. rcrl $1, reg1d
  7663. This corresponds to the common expression (x + y) shr 1, where
  7664. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7665. smaller code, but won't account for x + y causing an overflow). [Kit]
  7666. }
  7667. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7668. { Change first MOV command to have the same register as the final output }
  7669. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7670. else
  7671. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7672. { Change second MOV command to an ADD command. This is easier than
  7673. converting the existing command because it means we don't have to
  7674. touch 'y', which might be a complicated reference, and also the
  7675. fact that the third command might either be ADD or LEA. [Kit] }
  7676. taicpu(hp1).opcode := A_ADD;
  7677. { Delete old ADD/LEA instruction }
  7678. RemoveInstruction(hp2);
  7679. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7680. taicpu(hp3).opcode := A_RCR;
  7681. taicpu(hp3).changeopsize(S_L);
  7682. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7683. {$endif x86_64}
  7684. end;
  7685. end;
  7686. {$push}
  7687. {$q-}{$r-}
  7688. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7689. var
  7690. ThisReg: TRegister;
  7691. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7692. TargetSubReg: TSubRegister;
  7693. hp1, hp2: tai;
  7694. RegInUse, RegChanged, p_removed: Boolean;
  7695. { Store list of found instructions so we don't have to call
  7696. GetNextInstructionUsingReg multiple times }
  7697. InstrList: array of taicpu;
  7698. InstrMax, Index: Integer;
  7699. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7700. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7701. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7702. WorkingValue: TCgInt;
  7703. PreMessage: string;
  7704. { Data flow analysis }
  7705. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7706. BitwiseOnly, OrXorUsed,
  7707. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7708. function CheckOverflowConditions: Boolean;
  7709. begin
  7710. Result := True;
  7711. if (TestValSignedMax > SignedUpperLimit) then
  7712. UpperSignedOverflow := True;
  7713. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7714. LowerSignedOverflow := True;
  7715. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7716. LowerUnsignedOverflow := True;
  7717. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7718. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7719. begin
  7720. { Absolute overflow }
  7721. Result := False;
  7722. Exit;
  7723. end;
  7724. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7725. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7726. ShiftDownOverflow := True;
  7727. if (TestValMin < 0) or (TestValMax < 0) then
  7728. begin
  7729. LowerUnsignedOverflow := True;
  7730. UpperUnsignedOverflow := True;
  7731. end;
  7732. end;
  7733. function AdjustInitialLoad: Boolean;
  7734. begin
  7735. Result := False;
  7736. if not p_removed then
  7737. begin
  7738. if TargetSize = MinSize then
  7739. begin
  7740. { Convert the input MOVZX to a MOV }
  7741. if (taicpu(p).oper[0]^.typ = top_reg) and
  7742. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7743. begin
  7744. { Or remove it completely! }
  7745. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7746. RemoveCurrentP(p);
  7747. p_removed := True;
  7748. end
  7749. else
  7750. begin
  7751. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7752. taicpu(p).opcode := A_MOV;
  7753. taicpu(p).oper[1]^.reg := ThisReg;
  7754. taicpu(p).opsize := TargetSize;
  7755. end;
  7756. Result := True;
  7757. end
  7758. else if TargetSize <> MaxSize then
  7759. begin
  7760. case MaxSize of
  7761. S_L:
  7762. if TargetSize = S_W then
  7763. begin
  7764. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7765. taicpu(p).opsize := S_BW;
  7766. taicpu(p).oper[1]^.reg := ThisReg;
  7767. Result := True;
  7768. end
  7769. else
  7770. InternalError(2020112341);
  7771. S_W:
  7772. if TargetSize = S_L then
  7773. begin
  7774. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7775. taicpu(p).opsize := S_BL;
  7776. taicpu(p).oper[1]^.reg := ThisReg;
  7777. Result := True;
  7778. end
  7779. else
  7780. InternalError(2020112342);
  7781. else
  7782. ;
  7783. end;
  7784. end;
  7785. end;
  7786. end;
  7787. procedure AdjustFinalLoad;
  7788. begin
  7789. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7790. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7791. begin
  7792. { Convert the output MOVZX to a MOV }
  7793. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7794. begin
  7795. { Or remove it completely! }
  7796. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7797. { Be careful; if p = hp1 and p was also removed, p
  7798. will become a dangling pointer }
  7799. if p = hp1 then
  7800. begin
  7801. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7802. p_removed := True;
  7803. end
  7804. else
  7805. RemoveInstruction(hp1);
  7806. end
  7807. else
  7808. begin
  7809. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7810. taicpu(hp1).opcode := A_MOV;
  7811. taicpu(hp1).oper[0]^.reg := ThisReg;
  7812. taicpu(hp1).opsize := TargetSize;
  7813. end;
  7814. end
  7815. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7816. begin
  7817. { Need to change the size of the output }
  7818. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7819. taicpu(hp1).oper[0]^.reg := ThisReg;
  7820. taicpu(hp1).opsize := S_BL;
  7821. end;
  7822. end;
  7823. function CompressInstructions: Boolean;
  7824. var
  7825. LocalIndex: Integer;
  7826. begin
  7827. Result := False;
  7828. { The objective here is to try to find a combination that
  7829. removes one of the MOV/Z instructions. }
  7830. if (
  7831. (taicpu(p).oper[0]^.typ <> top_reg) or
  7832. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7833. ) and
  7834. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7835. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7836. begin
  7837. { Make a preference to remove the second MOVZX instruction }
  7838. case taicpu(hp1).opsize of
  7839. S_BL, S_WL:
  7840. begin
  7841. TargetSize := S_L;
  7842. TargetSubReg := R_SUBD;
  7843. end;
  7844. S_BW:
  7845. begin
  7846. TargetSize := S_W;
  7847. TargetSubReg := R_SUBW;
  7848. end;
  7849. else
  7850. InternalError(2020112302);
  7851. end;
  7852. end
  7853. else
  7854. begin
  7855. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7856. begin
  7857. { Exceeded lower bound but not upper bound }
  7858. TargetSize := MaxSize;
  7859. end
  7860. else if not LowerUnsignedOverflow then
  7861. begin
  7862. { Size didn't exceed lower bound }
  7863. TargetSize := MinSize;
  7864. end
  7865. else
  7866. Exit;
  7867. end;
  7868. case TargetSize of
  7869. S_B:
  7870. TargetSubReg := R_SUBL;
  7871. S_W:
  7872. TargetSubReg := R_SUBW;
  7873. S_L:
  7874. TargetSubReg := R_SUBD;
  7875. else
  7876. InternalError(2020112350);
  7877. end;
  7878. { Update the register to its new size }
  7879. setsubreg(ThisReg, TargetSubReg);
  7880. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7881. begin
  7882. { Check to see if the active register is used afterwards;
  7883. if not, we can change it and make a saving. }
  7884. RegInUse := False;
  7885. TransferUsedRegs(TmpUsedRegs);
  7886. { The target register may be marked as in use to cross
  7887. a jump to a distant label, so exclude it }
  7888. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7889. hp2 := p;
  7890. repeat
  7891. { Explicitly check for the excluded register (don't include the first
  7892. instruction as it may be reading from here }
  7893. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7894. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7895. begin
  7896. RegInUse := True;
  7897. Break;
  7898. end;
  7899. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7900. if not GetNextInstruction(hp2, hp2) then
  7901. InternalError(2020112340);
  7902. until (hp2 = hp1);
  7903. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7904. { We might still be able to get away with this }
  7905. RegInUse := not
  7906. (
  7907. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7908. (hp2.typ = ait_instruction) and
  7909. (
  7910. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7911. instruction that doesn't actually contain ThisReg }
  7912. (cs_opt_level3 in current_settings.optimizerswitches) or
  7913. RegInInstruction(ThisReg, hp2)
  7914. ) and
  7915. RegLoadedWithNewValue(ThisReg, hp2)
  7916. );
  7917. if not RegInUse then
  7918. begin
  7919. { Force the register size to the same as this instruction so it can be removed}
  7920. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7921. begin
  7922. TargetSize := S_L;
  7923. TargetSubReg := R_SUBD;
  7924. end
  7925. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7926. begin
  7927. TargetSize := S_W;
  7928. TargetSubReg := R_SUBW;
  7929. end;
  7930. ThisReg := taicpu(hp1).oper[1]^.reg;
  7931. setsubreg(ThisReg, TargetSubReg);
  7932. RegChanged := True;
  7933. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7934. TransferUsedRegs(TmpUsedRegs);
  7935. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7936. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7937. if p = hp1 then
  7938. begin
  7939. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7940. p_removed := True;
  7941. end
  7942. else
  7943. RemoveInstruction(hp1);
  7944. { Instruction will become "mov %reg,%reg" }
  7945. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7946. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7947. begin
  7948. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7949. RemoveCurrentP(p);
  7950. p_removed := True;
  7951. end
  7952. else
  7953. taicpu(p).oper[1]^.reg := ThisReg;
  7954. Result := True;
  7955. end
  7956. else
  7957. begin
  7958. if TargetSize <> MaxSize then
  7959. begin
  7960. { Since the register is in use, we have to force it to
  7961. MaxSize otherwise part of it may become undefined later on }
  7962. TargetSize := MaxSize;
  7963. case TargetSize of
  7964. S_B:
  7965. TargetSubReg := R_SUBL;
  7966. S_W:
  7967. TargetSubReg := R_SUBW;
  7968. S_L:
  7969. TargetSubReg := R_SUBD;
  7970. else
  7971. InternalError(2020112351);
  7972. end;
  7973. setsubreg(ThisReg, TargetSubReg);
  7974. end;
  7975. AdjustFinalLoad;
  7976. end;
  7977. end
  7978. else
  7979. AdjustFinalLoad;
  7980. Result := AdjustInitialLoad or Result;
  7981. { Now go through every instruction we found and change the
  7982. size. If TargetSize = MaxSize, then almost no changes are
  7983. needed and Result can remain False if it hasn't been set
  7984. yet.
  7985. If RegChanged is True, then the register requires changing
  7986. and so the point about TargetSize = MaxSize doesn't apply. }
  7987. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7988. begin
  7989. for LocalIndex := 0 to InstrMax do
  7990. begin
  7991. { If p_removed is true, then the original MOV/Z was removed
  7992. and removing the AND instruction may not be safe if it
  7993. appears first }
  7994. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7995. InternalError(2020112310);
  7996. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7997. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7998. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7999. InstrList[LocalIndex].opsize := TargetSize;
  8000. end;
  8001. Result := True;
  8002. end;
  8003. end;
  8004. begin
  8005. Result := False;
  8006. p_removed := False;
  8007. ThisReg := taicpu(p).oper[1]^.reg;
  8008. { Check for:
  8009. movs/z ###,%ecx (or %cx or %rcx)
  8010. ...
  8011. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8012. (dealloc %ecx)
  8013. Change to:
  8014. mov ###,%cl (if ### = %cl, then remove completely)
  8015. ...
  8016. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8017. }
  8018. if (getsupreg(ThisReg) = RS_ECX) and
  8019. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8020. (hp1.typ = ait_instruction) and
  8021. (
  8022. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8023. instruction that doesn't actually contain ECX }
  8024. (cs_opt_level3 in current_settings.optimizerswitches) or
  8025. RegInInstruction(NR_ECX, hp1) or
  8026. (
  8027. { It's common for the shift/rotate's read/write register to be
  8028. initialised in between, so under -O2 and under, search ahead
  8029. one more instruction
  8030. }
  8031. GetNextInstruction(hp1, hp1) and
  8032. (hp1.typ = ait_instruction) and
  8033. RegInInstruction(NR_ECX, hp1)
  8034. )
  8035. ) and
  8036. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8037. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8038. begin
  8039. TransferUsedRegs(TmpUsedRegs);
  8040. hp2 := p;
  8041. repeat
  8042. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8043. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8044. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8045. begin
  8046. case taicpu(p).opsize of
  8047. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8048. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8049. begin
  8050. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8051. RemoveCurrentP(p);
  8052. end
  8053. else
  8054. begin
  8055. taicpu(p).opcode := A_MOV;
  8056. taicpu(p).opsize := S_B;
  8057. taicpu(p).oper[1]^.reg := NR_CL;
  8058. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8059. end;
  8060. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8061. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8062. begin
  8063. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8064. RemoveCurrentP(p);
  8065. end
  8066. else
  8067. begin
  8068. taicpu(p).opcode := A_MOV;
  8069. taicpu(p).opsize := S_W;
  8070. taicpu(p).oper[1]^.reg := NR_CX;
  8071. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8072. end;
  8073. {$ifdef x86_64}
  8074. S_LQ:
  8075. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8076. begin
  8077. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8078. RemoveCurrentP(p);
  8079. end
  8080. else
  8081. begin
  8082. taicpu(p).opcode := A_MOV;
  8083. taicpu(p).opsize := S_L;
  8084. taicpu(p).oper[1]^.reg := NR_ECX;
  8085. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8086. end;
  8087. {$endif x86_64}
  8088. else
  8089. InternalError(2021120401);
  8090. end;
  8091. Result := True;
  8092. Exit;
  8093. end;
  8094. end;
  8095. { This is anything but quick! }
  8096. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8097. Exit;
  8098. SetLength(InstrList, 0);
  8099. InstrMax := -1;
  8100. case taicpu(p).opsize of
  8101. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8102. begin
  8103. {$if defined(i386) or defined(i8086)}
  8104. { If the target size is 8-bit, make sure we can actually encode it }
  8105. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8106. Exit;
  8107. {$endif i386 or i8086}
  8108. LowerLimit := $FF;
  8109. SignedLowerLimit := $7F;
  8110. SignedLowerLimitBottom := -128;
  8111. MinSize := S_B;
  8112. if taicpu(p).opsize = S_BW then
  8113. begin
  8114. MaxSize := S_W;
  8115. UpperLimit := $FFFF;
  8116. SignedUpperLimit := $7FFF;
  8117. SignedUpperLimitBottom := -32768;
  8118. end
  8119. else
  8120. begin
  8121. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8122. MaxSize := S_L;
  8123. UpperLimit := $FFFFFFFF;
  8124. SignedUpperLimit := $7FFFFFFF;
  8125. SignedUpperLimitBottom := -2147483648;
  8126. end;
  8127. end;
  8128. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8129. begin
  8130. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8131. LowerLimit := $FFFF;
  8132. SignedLowerLimit := $7FFF;
  8133. SignedLowerLimitBottom := -32768;
  8134. UpperLimit := $FFFFFFFF;
  8135. SignedUpperLimit := $7FFFFFFF;
  8136. SignedUpperLimitBottom := -2147483648;
  8137. MinSize := S_W;
  8138. MaxSize := S_L;
  8139. end;
  8140. {$ifdef x86_64}
  8141. S_LQ:
  8142. begin
  8143. { Both the lower and upper limits are set to 32-bit. If a limit
  8144. is breached, then optimisation is impossible }
  8145. LowerLimit := $FFFFFFFF;
  8146. SignedLowerLimit := $7FFFFFFF;
  8147. SignedLowerLimitBottom := -2147483648;
  8148. UpperLimit := $FFFFFFFF;
  8149. SignedUpperLimit := $7FFFFFFF;
  8150. SignedUpperLimitBottom := -2147483648;
  8151. MinSize := S_L;
  8152. MaxSize := S_L;
  8153. end;
  8154. {$endif x86_64}
  8155. else
  8156. InternalError(2020112301);
  8157. end;
  8158. TestValMin := 0;
  8159. TestValMax := LowerLimit;
  8160. TestValSignedMax := SignedLowerLimit;
  8161. TryShiftDownLimit := LowerLimit;
  8162. TryShiftDown := S_NO;
  8163. ShiftDownOverflow := False;
  8164. RegChanged := False;
  8165. BitwiseOnly := True;
  8166. OrXorUsed := False;
  8167. UpperSignedOverflow := False;
  8168. LowerSignedOverflow := False;
  8169. UpperUnsignedOverflow := False;
  8170. LowerUnsignedOverflow := False;
  8171. hp1 := p;
  8172. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8173. (hp1.typ = ait_instruction) and
  8174. (
  8175. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8176. instruction that doesn't actually contain ThisReg }
  8177. (cs_opt_level3 in current_settings.optimizerswitches) or
  8178. { This allows this Movx optimisation to work through the SETcc instructions
  8179. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8180. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8181. skip over these SETcc instructions). }
  8182. (taicpu(hp1).opcode = A_SETcc) or
  8183. RegInInstruction(ThisReg, hp1)
  8184. ) do
  8185. begin
  8186. case taicpu(hp1).opcode of
  8187. A_INC,A_DEC:
  8188. begin
  8189. { Has to be an exact match on the register }
  8190. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8191. Break;
  8192. if taicpu(hp1).opcode = A_INC then
  8193. begin
  8194. Inc(TestValMin);
  8195. Inc(TestValMax);
  8196. Inc(TestValSignedMax);
  8197. end
  8198. else
  8199. begin
  8200. Dec(TestValMin);
  8201. Dec(TestValMax);
  8202. Dec(TestValSignedMax);
  8203. end;
  8204. end;
  8205. A_TEST, A_CMP:
  8206. begin
  8207. if (
  8208. { Too high a risk of non-linear behaviour that breaks DFA
  8209. here, unless it's cmp $0,%reg, which is equivalent to
  8210. test %reg,%reg }
  8211. OrXorUsed and
  8212. (taicpu(hp1).opcode = A_CMP) and
  8213. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8214. ) or
  8215. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8216. { Has to be an exact match on the register }
  8217. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8218. (
  8219. { Permit "test %reg,%reg" }
  8220. (taicpu(hp1).opcode = A_TEST) and
  8221. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8222. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8223. ) or
  8224. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8225. { Make sure the comparison value is not smaller than the
  8226. smallest allowed signed value for the minimum size (e.g.
  8227. -128 for 8-bit) }
  8228. not (
  8229. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8230. { Is it in the negative range? }
  8231. (
  8232. (taicpu(hp1).oper[0]^.val < 0) and
  8233. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8234. )
  8235. ) then
  8236. Break;
  8237. { Check to see if the active register is used afterwards }
  8238. TransferUsedRegs(TmpUsedRegs);
  8239. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8240. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8241. begin
  8242. { Make sure the comparison or any previous instructions
  8243. hasn't pushed the test values outside of the range of
  8244. MinSize }
  8245. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8246. begin
  8247. { Exceeded lower bound but not upper bound }
  8248. TargetSize := MaxSize;
  8249. end
  8250. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8251. begin
  8252. { Size didn't exceed lower bound }
  8253. TargetSize := MinSize;
  8254. end
  8255. else
  8256. Break;
  8257. case TargetSize of
  8258. S_B:
  8259. TargetSubReg := R_SUBL;
  8260. S_W:
  8261. TargetSubReg := R_SUBW;
  8262. S_L:
  8263. TargetSubReg := R_SUBD;
  8264. else
  8265. InternalError(2021051002);
  8266. end;
  8267. if TargetSize <> MaxSize then
  8268. begin
  8269. { Update the register to its new size }
  8270. setsubreg(ThisReg, TargetSubReg);
  8271. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8272. taicpu(hp1).oper[1]^.reg := ThisReg;
  8273. taicpu(hp1).opsize := TargetSize;
  8274. { Convert the input MOVZX to a MOV if necessary }
  8275. AdjustInitialLoad;
  8276. if (InstrMax >= 0) then
  8277. begin
  8278. for Index := 0 to InstrMax do
  8279. begin
  8280. { If p_removed is true, then the original MOV/Z was removed
  8281. and removing the AND instruction may not be safe if it
  8282. appears first }
  8283. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8284. InternalError(2020112311);
  8285. if InstrList[Index].oper[0]^.typ = top_reg then
  8286. InstrList[Index].oper[0]^.reg := ThisReg;
  8287. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8288. InstrList[Index].opsize := MinSize;
  8289. end;
  8290. end;
  8291. Result := True;
  8292. end;
  8293. Exit;
  8294. end;
  8295. end;
  8296. A_SETcc:
  8297. begin
  8298. { This allows this Movx optimisation to work through the SETcc instructions
  8299. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8300. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8301. skip over these SETcc instructions). }
  8302. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8303. { Of course, break out if the current register is used }
  8304. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8305. Break
  8306. else
  8307. { We must use Continue so the instruction doesn't get added
  8308. to InstrList }
  8309. Continue;
  8310. end;
  8311. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8312. begin
  8313. if
  8314. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8315. { Has to be an exact match on the register }
  8316. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8317. (
  8318. (
  8319. (taicpu(hp1).oper[0]^.typ = top_const) and
  8320. (
  8321. (
  8322. (taicpu(hp1).opcode = A_SHL) and
  8323. (
  8324. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8325. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8326. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8327. )
  8328. ) or (
  8329. (taicpu(hp1).opcode <> A_SHL) and
  8330. (
  8331. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8332. { Is it in the negative range? }
  8333. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8334. )
  8335. )
  8336. )
  8337. ) or (
  8338. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8339. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8340. )
  8341. ) then
  8342. Break;
  8343. { Only process OR and XOR if there are only bitwise operations,
  8344. since otherwise they can too easily fool the data flow
  8345. analysis (they can cause non-linear behaviour) }
  8346. case taicpu(hp1).opcode of
  8347. A_ADD:
  8348. begin
  8349. if OrXorUsed then
  8350. { Too high a risk of non-linear behaviour that breaks DFA here }
  8351. Break
  8352. else
  8353. BitwiseOnly := False;
  8354. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8355. begin
  8356. TestValMin := TestValMin * 2;
  8357. TestValMax := TestValMax * 2;
  8358. TestValSignedMax := TestValSignedMax * 2;
  8359. end
  8360. else
  8361. begin
  8362. WorkingValue := taicpu(hp1).oper[0]^.val;
  8363. TestValMin := TestValMin + WorkingValue;
  8364. TestValMax := TestValMax + WorkingValue;
  8365. TestValSignedMax := TestValSignedMax + WorkingValue;
  8366. end;
  8367. end;
  8368. A_SUB:
  8369. begin
  8370. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8371. begin
  8372. TestValMin := 0;
  8373. TestValMax := 0;
  8374. TestValSignedMax := 0;
  8375. end
  8376. else
  8377. begin
  8378. if OrXorUsed then
  8379. { Too high a risk of non-linear behaviour that breaks DFA here }
  8380. Break
  8381. else
  8382. BitwiseOnly := False;
  8383. WorkingValue := taicpu(hp1).oper[0]^.val;
  8384. TestValMin := TestValMin - WorkingValue;
  8385. TestValMax := TestValMax - WorkingValue;
  8386. TestValSignedMax := TestValSignedMax - WorkingValue;
  8387. end;
  8388. end;
  8389. A_AND:
  8390. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8391. begin
  8392. { we might be able to go smaller if AND appears first }
  8393. if InstrMax = -1 then
  8394. case MinSize of
  8395. S_B:
  8396. ;
  8397. S_W:
  8398. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8399. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8400. begin
  8401. TryShiftDown := S_B;
  8402. TryShiftDownLimit := $FF;
  8403. end;
  8404. S_L:
  8405. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8406. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8407. begin
  8408. TryShiftDown := S_B;
  8409. TryShiftDownLimit := $FF;
  8410. end
  8411. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8412. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8413. begin
  8414. TryShiftDown := S_W;
  8415. TryShiftDownLimit := $FFFF;
  8416. end;
  8417. else
  8418. InternalError(2020112320);
  8419. end;
  8420. WorkingValue := taicpu(hp1).oper[0]^.val;
  8421. TestValMin := TestValMin and WorkingValue;
  8422. TestValMax := TestValMax and WorkingValue;
  8423. TestValSignedMax := TestValSignedMax and WorkingValue;
  8424. end;
  8425. A_OR:
  8426. begin
  8427. if not BitwiseOnly then
  8428. Break;
  8429. OrXorUsed := True;
  8430. WorkingValue := taicpu(hp1).oper[0]^.val;
  8431. TestValMin := TestValMin or WorkingValue;
  8432. TestValMax := TestValMax or WorkingValue;
  8433. TestValSignedMax := TestValSignedMax or WorkingValue;
  8434. end;
  8435. A_XOR:
  8436. begin
  8437. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8438. begin
  8439. TestValMin := 0;
  8440. TestValMax := 0;
  8441. TestValSignedMax := 0;
  8442. end
  8443. else
  8444. begin
  8445. if not BitwiseOnly then
  8446. Break;
  8447. OrXorUsed := True;
  8448. WorkingValue := taicpu(hp1).oper[0]^.val;
  8449. TestValMin := TestValMin xor WorkingValue;
  8450. TestValMax := TestValMax xor WorkingValue;
  8451. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8452. end;
  8453. end;
  8454. A_SHL:
  8455. begin
  8456. BitwiseOnly := False;
  8457. WorkingValue := taicpu(hp1).oper[0]^.val;
  8458. TestValMin := TestValMin shl WorkingValue;
  8459. TestValMax := TestValMax shl WorkingValue;
  8460. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8461. end;
  8462. A_SHR,
  8463. { The first instruction was MOVZX, so the value won't be negative }
  8464. A_SAR:
  8465. begin
  8466. if InstrMax <> -1 then
  8467. BitwiseOnly := False
  8468. else
  8469. { we might be able to go smaller if SHR appears first }
  8470. case MinSize of
  8471. S_B:
  8472. ;
  8473. S_W:
  8474. if (taicpu(hp1).oper[0]^.val >= 8) then
  8475. begin
  8476. TryShiftDown := S_B;
  8477. TryShiftDownLimit := $FF;
  8478. TryShiftDownSignedLimit := $7F;
  8479. TryShiftDownSignedLimitLower := -128;
  8480. end;
  8481. S_L:
  8482. if (taicpu(hp1).oper[0]^.val >= 24) then
  8483. begin
  8484. TryShiftDown := S_B;
  8485. TryShiftDownLimit := $FF;
  8486. TryShiftDownSignedLimit := $7F;
  8487. TryShiftDownSignedLimitLower := -128;
  8488. end
  8489. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8490. begin
  8491. TryShiftDown := S_W;
  8492. TryShiftDownLimit := $FFFF;
  8493. TryShiftDownSignedLimit := $7FFF;
  8494. TryShiftDownSignedLimitLower := -32768;
  8495. end;
  8496. else
  8497. InternalError(2020112321);
  8498. end;
  8499. WorkingValue := taicpu(hp1).oper[0]^.val;
  8500. if taicpu(hp1).opcode = A_SAR then
  8501. begin
  8502. TestValMin := SarInt64(TestValMin, WorkingValue);
  8503. TestValMax := SarInt64(TestValMax, WorkingValue);
  8504. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8505. end
  8506. else
  8507. begin
  8508. TestValMin := TestValMin shr WorkingValue;
  8509. TestValMax := TestValMax shr WorkingValue;
  8510. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8511. end;
  8512. end;
  8513. else
  8514. InternalError(2020112303);
  8515. end;
  8516. end;
  8517. (*
  8518. A_IMUL:
  8519. case taicpu(hp1).ops of
  8520. 2:
  8521. begin
  8522. if not MatchOpType(hp1, top_reg, top_reg) or
  8523. { Has to be an exact match on the register }
  8524. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8525. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8526. Break;
  8527. TestValMin := TestValMin * TestValMin;
  8528. TestValMax := TestValMax * TestValMax;
  8529. TestValSignedMax := TestValSignedMax * TestValMax;
  8530. end;
  8531. 3:
  8532. begin
  8533. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8534. { Has to be an exact match on the register }
  8535. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8536. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8537. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8538. { Is it in the negative range? }
  8539. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8540. Break;
  8541. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8542. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8543. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8544. end;
  8545. else
  8546. Break;
  8547. end;
  8548. A_IDIV:
  8549. case taicpu(hp1).ops of
  8550. 3:
  8551. begin
  8552. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8553. { Has to be an exact match on the register }
  8554. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8555. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8556. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8557. { Is it in the negative range? }
  8558. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8559. Break;
  8560. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8561. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8562. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8563. end;
  8564. else
  8565. Break;
  8566. end;
  8567. *)
  8568. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8569. begin
  8570. { If there are no instructions in between, then we might be able to make a saving }
  8571. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8572. Break;
  8573. { We have something like:
  8574. movzbw %dl,%dx
  8575. ...
  8576. movswl %dx,%edx
  8577. Change the latter to a zero-extension then enter the
  8578. A_MOVZX case branch.
  8579. }
  8580. {$ifdef x86_64}
  8581. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8582. begin
  8583. { this becomes a zero extension from 32-bit to 64-bit, but
  8584. the upper 32 bits are already zero, so just delete the
  8585. instruction }
  8586. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8587. RemoveInstruction(hp1);
  8588. Result := True;
  8589. Exit;
  8590. end
  8591. else
  8592. {$endif x86_64}
  8593. begin
  8594. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8595. taicpu(hp1).opcode := A_MOVZX;
  8596. {$ifdef x86_64}
  8597. case taicpu(hp1).opsize of
  8598. S_BQ:
  8599. begin
  8600. taicpu(hp1).opsize := S_BL;
  8601. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8602. end;
  8603. S_WQ:
  8604. begin
  8605. taicpu(hp1).opsize := S_WL;
  8606. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8607. end;
  8608. S_LQ:
  8609. begin
  8610. taicpu(hp1).opcode := A_MOV;
  8611. taicpu(hp1).opsize := S_L;
  8612. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8613. { In this instance, we need to break out because the
  8614. instruction is no longer MOVZX or MOVSXD }
  8615. Result := True;
  8616. Exit;
  8617. end;
  8618. else
  8619. ;
  8620. end;
  8621. {$endif x86_64}
  8622. Result := CompressInstructions;
  8623. Exit;
  8624. end;
  8625. end;
  8626. A_MOVZX:
  8627. begin
  8628. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8629. Break;
  8630. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8631. begin
  8632. if (InstrMax = -1) and
  8633. { Will return false if the second parameter isn't ThisReg
  8634. (can happen on -O2 and under) }
  8635. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8636. begin
  8637. { The two MOVZX instructions are adjacent, so remove the first one }
  8638. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8639. RemoveCurrentP(p);
  8640. Result := True;
  8641. Exit;
  8642. end;
  8643. Break;
  8644. end;
  8645. Result := CompressInstructions;
  8646. Exit;
  8647. end;
  8648. else
  8649. { This includes ADC, SBB and IDIV }
  8650. Break;
  8651. end;
  8652. if not CheckOverflowConditions then
  8653. Break;
  8654. { Contains highest index (so instruction count - 1) }
  8655. Inc(InstrMax);
  8656. if InstrMax > High(InstrList) then
  8657. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8658. InstrList[InstrMax] := taicpu(hp1);
  8659. end;
  8660. end;
  8661. {$pop}
  8662. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8663. var
  8664. hp1 : tai;
  8665. begin
  8666. Result:=false;
  8667. if (taicpu(p).ops >= 2) and
  8668. ((taicpu(p).oper[0]^.typ = top_const) or
  8669. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8670. (taicpu(p).oper[1]^.typ = top_reg) and
  8671. ((taicpu(p).ops = 2) or
  8672. ((taicpu(p).oper[2]^.typ = top_reg) and
  8673. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8674. GetLastInstruction(p,hp1) and
  8675. MatchInstruction(hp1,A_MOV,[]) and
  8676. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8677. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8678. begin
  8679. TransferUsedRegs(TmpUsedRegs);
  8680. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8681. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8682. { change
  8683. mov reg1,reg2
  8684. imul y,reg2 to imul y,reg1,reg2 }
  8685. begin
  8686. taicpu(p).ops := 3;
  8687. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8688. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8689. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8690. RemoveInstruction(hp1);
  8691. result:=true;
  8692. end;
  8693. end;
  8694. end;
  8695. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8696. var
  8697. ThisLabel: TAsmLabel;
  8698. begin
  8699. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8700. ThisLabel.decrefs;
  8701. taicpu(p).opcode := A_RET;
  8702. taicpu(p).is_jmp := false;
  8703. taicpu(p).ops := taicpu(ret_p).ops;
  8704. case taicpu(ret_p).ops of
  8705. 0:
  8706. taicpu(p).clearop(0);
  8707. 1:
  8708. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8709. else
  8710. internalerror(2016041301);
  8711. end;
  8712. { If the original label is now dead, it might turn out that the label
  8713. immediately follows p. As a result, everything beyond it, which will
  8714. be just some final register configuration and a RET instruction, is
  8715. now dead code. [Kit] }
  8716. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8717. running RemoveDeadCodeAfterJump for each RET instruction, because
  8718. this optimisation rarely happens and most RETs appear at the end of
  8719. routines where there is nothing that can be stripped. [Kit] }
  8720. if not ThisLabel.is_used then
  8721. RemoveDeadCodeAfterJump(p);
  8722. end;
  8723. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8724. var
  8725. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8726. Unconditional, PotentialModified: Boolean;
  8727. OperPtr: POper;
  8728. NewRef: TReference;
  8729. InstrList: array of taicpu;
  8730. InstrMax, Index: Integer;
  8731. const
  8732. {$ifdef DEBUG_AOPTCPU}
  8733. SNoFlags: shortstring = ' so the flags aren''t modified';
  8734. {$else DEBUG_AOPTCPU}
  8735. SNoFlags = '';
  8736. {$endif DEBUG_AOPTCPU}
  8737. begin
  8738. Result:=false;
  8739. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8740. begin
  8741. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8742. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8743. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8744. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8745. GetNextInstruction(hp1, hp2) and
  8746. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8747. { Change from: To:
  8748. set(C) %reg j(~C) label
  8749. test %reg,%reg/cmp $0,%reg
  8750. je label
  8751. set(C) %reg j(C) label
  8752. test %reg,%reg/cmp $0,%reg
  8753. jne label
  8754. (Also do something similar with sete/setne instead of je/jne)
  8755. }
  8756. begin
  8757. { Before we do anything else, we need to check the instructions
  8758. in between SETcc and TEST to make sure they don't modify the
  8759. FLAGS register - if -O2 or under, there won't be any
  8760. instructions between SET and TEST }
  8761. TransferUsedRegs(TmpUsedRegs);
  8762. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8763. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8764. begin
  8765. next := p;
  8766. SetLength(InstrList, 0);
  8767. InstrMax := -1;
  8768. PotentialModified := False;
  8769. { Make a note of every instruction that modifies the FLAGS
  8770. register }
  8771. while GetNextInstruction(next, next) and (next <> hp1) do
  8772. begin
  8773. if next.typ <> ait_instruction then
  8774. { GetNextInstructionUsingReg should have returned False }
  8775. InternalError(2021051701);
  8776. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8777. begin
  8778. case taicpu(next).opcode of
  8779. A_SETcc,
  8780. A_CMOVcc,
  8781. A_Jcc:
  8782. begin
  8783. if PotentialModified then
  8784. { Not safe because the flags were modified earlier }
  8785. Exit
  8786. else
  8787. { Condition is the same as the initial SETcc, so this is safe
  8788. (don't add to instruction list though) }
  8789. Continue;
  8790. end;
  8791. A_ADD:
  8792. begin
  8793. if (taicpu(next).opsize = S_B) or
  8794. { LEA doesn't support 8-bit operands }
  8795. (taicpu(next).oper[1]^.typ <> top_reg) or
  8796. { Must write to a register }
  8797. (taicpu(next).oper[0]^.typ = top_ref) then
  8798. { Require a constant or a register }
  8799. Exit;
  8800. PotentialModified := True;
  8801. end;
  8802. A_SUB:
  8803. begin
  8804. if (taicpu(next).opsize = S_B) or
  8805. { LEA doesn't support 8-bit operands }
  8806. (taicpu(next).oper[1]^.typ <> top_reg) or
  8807. { Must write to a register }
  8808. (taicpu(next).oper[0]^.typ <> top_const) or
  8809. (taicpu(next).oper[0]^.val = $80000000) then
  8810. { Can't subtract a register with LEA - also
  8811. check that the value isn't -2^31, as this
  8812. can't be negated }
  8813. Exit;
  8814. PotentialModified := True;
  8815. end;
  8816. A_SAL,
  8817. A_SHL:
  8818. begin
  8819. if (taicpu(next).opsize = S_B) or
  8820. { LEA doesn't support 8-bit operands }
  8821. (taicpu(next).oper[1]^.typ <> top_reg) or
  8822. { Must write to a register }
  8823. (taicpu(next).oper[0]^.typ <> top_const) or
  8824. (taicpu(next).oper[0]^.val < 0) or
  8825. (taicpu(next).oper[0]^.val > 3) then
  8826. Exit;
  8827. PotentialModified := True;
  8828. end;
  8829. A_IMUL:
  8830. begin
  8831. if (taicpu(next).ops <> 3) or
  8832. (taicpu(next).oper[1]^.typ <> top_reg) or
  8833. { Must write to a register }
  8834. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8835. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8836. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8837. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8838. Exit
  8839. else
  8840. PotentialModified := True;
  8841. end;
  8842. else
  8843. { Don't know how to change this, so abort }
  8844. Exit;
  8845. end;
  8846. { Contains highest index (so instruction count - 1) }
  8847. Inc(InstrMax);
  8848. if InstrMax > High(InstrList) then
  8849. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8850. InstrList[InstrMax] := taicpu(next);
  8851. end;
  8852. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8853. end;
  8854. if not Assigned(next) or (next <> hp1) then
  8855. { It should be equal to hp1 }
  8856. InternalError(2021051702);
  8857. { Cycle through each instruction and check to see if we can
  8858. change them to versions that don't modify the flags }
  8859. if (InstrMax >= 0) then
  8860. begin
  8861. for Index := 0 to InstrMax do
  8862. case InstrList[Index].opcode of
  8863. A_ADD:
  8864. begin
  8865. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8866. InstrList[Index].opcode := A_LEA;
  8867. reference_reset(NewRef, 1, []);
  8868. NewRef.base := InstrList[Index].oper[1]^.reg;
  8869. if InstrList[Index].oper[0]^.typ = top_reg then
  8870. begin
  8871. NewRef.index := InstrList[Index].oper[0]^.reg;
  8872. NewRef.scalefactor := 1;
  8873. end
  8874. else
  8875. NewRef.offset := InstrList[Index].oper[0]^.val;
  8876. InstrList[Index].loadref(0, NewRef);
  8877. end;
  8878. A_SUB:
  8879. begin
  8880. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8881. InstrList[Index].opcode := A_LEA;
  8882. reference_reset(NewRef, 1, []);
  8883. NewRef.base := InstrList[Index].oper[1]^.reg;
  8884. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8885. InstrList[Index].loadref(0, NewRef);
  8886. end;
  8887. A_SHL,
  8888. A_SAL:
  8889. begin
  8890. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8891. InstrList[Index].opcode := A_LEA;
  8892. reference_reset(NewRef, 1, []);
  8893. NewRef.index := InstrList[Index].oper[1]^.reg;
  8894. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8895. InstrList[Index].loadref(0, NewRef);
  8896. end;
  8897. A_IMUL:
  8898. begin
  8899. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8900. InstrList[Index].opcode := A_LEA;
  8901. reference_reset(NewRef, 1, []);
  8902. NewRef.index := InstrList[Index].oper[1]^.reg;
  8903. case InstrList[Index].oper[0]^.val of
  8904. 2, 4, 8:
  8905. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8906. else {3, 5 and 9}
  8907. begin
  8908. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8909. NewRef.base := InstrList[Index].oper[1]^.reg;
  8910. end;
  8911. end;
  8912. InstrList[Index].loadref(0, NewRef);
  8913. end;
  8914. else
  8915. InternalError(2021051710);
  8916. end;
  8917. end;
  8918. { Mark the FLAGS register as used across this whole block }
  8919. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8920. end;
  8921. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8922. JumpC := taicpu(hp2).condition;
  8923. Unconditional := False;
  8924. if conditions_equal(JumpC, C_E) then
  8925. SetC := inverse_cond(taicpu(p).condition)
  8926. else if conditions_equal(JumpC, C_NE) then
  8927. SetC := taicpu(p).condition
  8928. else
  8929. { We've got something weird here (and inefficent) }
  8930. begin
  8931. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8932. SetC := C_NONE;
  8933. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8934. if condition_in(C_AE, JumpC) then
  8935. Unconditional := True
  8936. else
  8937. { Not sure what to do with this jump - drop out }
  8938. Exit;
  8939. end;
  8940. RemoveInstruction(hp1);
  8941. if Unconditional then
  8942. MakeUnconditional(taicpu(hp2))
  8943. else
  8944. begin
  8945. if SetC = C_NONE then
  8946. InternalError(2018061402);
  8947. taicpu(hp2).SetCondition(SetC);
  8948. end;
  8949. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8950. TmpUsedRegs }
  8951. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8952. begin
  8953. RemoveCurrentp(p, hp2);
  8954. if taicpu(hp2).opcode = A_SETcc then
  8955. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8956. else
  8957. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8958. end
  8959. else
  8960. if taicpu(hp2).opcode = A_SETcc then
  8961. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8962. else
  8963. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8964. Result := True;
  8965. end
  8966. else if
  8967. { Make sure the instructions are adjacent }
  8968. (
  8969. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8970. GetNextInstruction(p, hp1)
  8971. ) and
  8972. MatchInstruction(hp1, A_MOV, [S_B]) and
  8973. { Writing to memory is allowed }
  8974. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8975. begin
  8976. {
  8977. Watch out for sequences such as:
  8978. set(c)b %regb
  8979. movb %regb,(ref)
  8980. movb $0,1(ref)
  8981. movb $0,2(ref)
  8982. movb $0,3(ref)
  8983. Much more efficient to turn it into:
  8984. movl $0,%regl
  8985. set(c)b %regb
  8986. movl %regl,(ref)
  8987. Or:
  8988. set(c)b %regb
  8989. movzbl %regb,%regl
  8990. movl %regl,(ref)
  8991. }
  8992. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8993. GetNextInstruction(hp1, hp2) and
  8994. MatchInstruction(hp2, A_MOV, [S_B]) and
  8995. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8996. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8997. begin
  8998. { Don't do anything else except set Result to True }
  8999. end
  9000. else
  9001. begin
  9002. if taicpu(p).oper[0]^.typ = top_reg then
  9003. begin
  9004. TransferUsedRegs(TmpUsedRegs);
  9005. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9006. end;
  9007. { If it's not a register, it's a memory address }
  9008. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9009. begin
  9010. { Even if the register is still in use, we can minimise the
  9011. pipeline stall by changing the MOV into another SETcc. }
  9012. taicpu(hp1).opcode := A_SETcc;
  9013. taicpu(hp1).condition := taicpu(p).condition;
  9014. if taicpu(hp1).oper[1]^.typ = top_ref then
  9015. begin
  9016. { Swapping the operand pointers like this is probably a
  9017. bit naughty, but it is far faster than using loadoper
  9018. to transfer the reference from oper[1] to oper[0] if
  9019. you take into account the extra procedure calls and
  9020. the memory allocation and deallocation required }
  9021. OperPtr := taicpu(hp1).oper[1];
  9022. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9023. taicpu(hp1).oper[0] := OperPtr;
  9024. end
  9025. else
  9026. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9027. taicpu(hp1).clearop(1);
  9028. taicpu(hp1).ops := 1;
  9029. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9030. end
  9031. else
  9032. begin
  9033. if taicpu(hp1).oper[1]^.typ = top_reg then
  9034. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9035. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9036. RemoveInstruction(hp1);
  9037. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9038. end
  9039. end;
  9040. Result := True;
  9041. end;
  9042. end;
  9043. end;
  9044. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9045. var
  9046. hp1: tai;
  9047. Count: Integer;
  9048. OrigLabel: TAsmLabel;
  9049. begin
  9050. result := False;
  9051. { Sometimes, the optimisations below can permit this }
  9052. RemoveDeadCodeAfterJump(p);
  9053. 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
  9054. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9055. begin
  9056. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9057. { Also a side-effect of optimisations }
  9058. if CollapseZeroDistJump(p, OrigLabel) then
  9059. begin
  9060. Result := True;
  9061. Exit;
  9062. end;
  9063. hp1 := GetLabelWithSym(OrigLabel);
  9064. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9065. begin
  9066. case taicpu(hp1).opcode of
  9067. A_RET:
  9068. {
  9069. change
  9070. jmp .L1
  9071. ...
  9072. .L1:
  9073. ret
  9074. into
  9075. ret
  9076. }
  9077. begin
  9078. ConvertJumpToRET(p, hp1);
  9079. result:=true;
  9080. end;
  9081. { Check any kind of direct assignment instruction }
  9082. A_MOV,
  9083. A_MOVD,
  9084. A_MOVQ,
  9085. A_MOVSX,
  9086. {$ifdef x86_64}
  9087. A_MOVSXD,
  9088. {$endif x86_64}
  9089. A_MOVZX,
  9090. A_MOVAPS,
  9091. A_MOVUPS,
  9092. A_MOVSD,
  9093. A_MOVAPD,
  9094. A_MOVUPD,
  9095. A_MOVDQA,
  9096. A_MOVDQU,
  9097. A_VMOVSS,
  9098. A_VMOVAPS,
  9099. A_VMOVUPS,
  9100. A_VMOVSD,
  9101. A_VMOVAPD,
  9102. A_VMOVUPD,
  9103. A_VMOVDQA,
  9104. A_VMOVDQU:
  9105. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9106. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9107. begin
  9108. Result := True;
  9109. Exit;
  9110. end;
  9111. else
  9112. ;
  9113. end;
  9114. end;
  9115. end;
  9116. end;
  9117. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9118. begin
  9119. CanBeCMOV:=assigned(p) and
  9120. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9121. { we can't use cmov ref,reg because
  9122. ref could be nil and cmov still throws an exception
  9123. if ref=nil but the mov isn't done (FK)
  9124. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9125. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9126. }
  9127. (taicpu(p).oper[1]^.typ = top_reg) and
  9128. (
  9129. (taicpu(p).oper[0]^.typ = top_reg) or
  9130. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9131. it is not expected that this can cause a seg. violation }
  9132. (
  9133. (taicpu(p).oper[0]^.typ = top_ref) and
  9134. IsRefSafe(taicpu(p).oper[0]^.ref)
  9135. )
  9136. );
  9137. end;
  9138. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9139. var
  9140. hp1,hp2: tai;
  9141. {$ifndef i8086}
  9142. hp3,hp4,hpmov2, hp5: tai;
  9143. l : Longint;
  9144. condition : TAsmCond;
  9145. {$endif i8086}
  9146. carryadd_opcode : TAsmOp;
  9147. symbol: TAsmSymbol;
  9148. increg, tmpreg: TRegister;
  9149. begin
  9150. result:=false;
  9151. if GetNextInstruction(p,hp1) then
  9152. begin
  9153. if (hp1.typ=ait_label) then
  9154. begin
  9155. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9156. Exit;
  9157. end
  9158. else if (hp1.typ<>ait_instruction) then
  9159. Exit;
  9160. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9161. if (
  9162. (
  9163. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9164. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9165. (Taicpu(hp1).oper[0]^.val=1)
  9166. ) or
  9167. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9168. ) and
  9169. GetNextInstruction(hp1,hp2) and
  9170. SkipAligns(hp2, hp2) and
  9171. (hp2.typ = ait_label) and
  9172. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9173. { jb @@1 cmc
  9174. inc/dec operand --> adc/sbb operand,0
  9175. @@1:
  9176. ... and ...
  9177. jnb @@1
  9178. inc/dec operand --> adc/sbb operand,0
  9179. @@1: }
  9180. begin
  9181. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9182. begin
  9183. case taicpu(hp1).opcode of
  9184. A_INC,
  9185. A_ADD:
  9186. carryadd_opcode:=A_ADC;
  9187. A_DEC,
  9188. A_SUB:
  9189. carryadd_opcode:=A_SBB;
  9190. else
  9191. InternalError(2021011001);
  9192. end;
  9193. Taicpu(p).clearop(0);
  9194. Taicpu(p).ops:=0;
  9195. Taicpu(p).is_jmp:=false;
  9196. Taicpu(p).opcode:=A_CMC;
  9197. Taicpu(p).condition:=C_NONE;
  9198. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9199. Taicpu(hp1).ops:=2;
  9200. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9201. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9202. else
  9203. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9204. Taicpu(hp1).loadconst(0,0);
  9205. Taicpu(hp1).opcode:=carryadd_opcode;
  9206. result:=true;
  9207. exit;
  9208. end
  9209. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9210. begin
  9211. case taicpu(hp1).opcode of
  9212. A_INC,
  9213. A_ADD:
  9214. carryadd_opcode:=A_ADC;
  9215. A_DEC,
  9216. A_SUB:
  9217. carryadd_opcode:=A_SBB;
  9218. else
  9219. InternalError(2021011002);
  9220. end;
  9221. Taicpu(hp1).ops:=2;
  9222. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9223. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9224. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9225. else
  9226. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9227. Taicpu(hp1).loadconst(0,0);
  9228. Taicpu(hp1).opcode:=carryadd_opcode;
  9229. RemoveCurrentP(p, hp1);
  9230. result:=true;
  9231. exit;
  9232. end
  9233. {
  9234. jcc @@1 setcc tmpreg
  9235. inc/dec/add/sub operand -> (movzx tmpreg)
  9236. @@1: add/sub tmpreg,operand
  9237. While this increases code size slightly, it makes the code much faster if the
  9238. jump is unpredictable
  9239. }
  9240. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9241. begin
  9242. { search for an available register which is volatile }
  9243. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9244. if increg <> NR_NO then
  9245. begin
  9246. { We don't need to check if tmpreg is in hp1 or not, because
  9247. it will be marked as in use at p (if not, this is
  9248. indictive of a compiler bug). }
  9249. TAsmLabel(symbol).decrefs;
  9250. Taicpu(p).clearop(0);
  9251. Taicpu(p).ops:=1;
  9252. Taicpu(p).is_jmp:=false;
  9253. Taicpu(p).opcode:=A_SETcc;
  9254. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9255. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9256. Taicpu(p).loadreg(0,increg);
  9257. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9258. begin
  9259. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9260. R_SUBW:
  9261. begin
  9262. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9263. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9264. end;
  9265. R_SUBD:
  9266. begin
  9267. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9268. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9269. end;
  9270. {$ifdef x86_64}
  9271. R_SUBQ:
  9272. begin
  9273. { MOVZX doesn't have a 64-bit variant, because
  9274. the 32-bit version implicitly zeroes the
  9275. upper 32-bits of the destination register }
  9276. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9277. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9278. setsubreg(tmpreg, R_SUBQ);
  9279. end;
  9280. {$endif x86_64}
  9281. else
  9282. Internalerror(2020030601);
  9283. end;
  9284. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9285. asml.InsertAfter(hp2,p);
  9286. end
  9287. else
  9288. tmpreg := increg;
  9289. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9290. begin
  9291. Taicpu(hp1).ops:=2;
  9292. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9293. end;
  9294. Taicpu(hp1).loadreg(0,tmpreg);
  9295. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9296. Result := True;
  9297. { p is no longer a Jcc instruction, so exit }
  9298. Exit;
  9299. end;
  9300. end;
  9301. end;
  9302. { Detect the following:
  9303. jmp<cond> @Lbl1
  9304. jmp @Lbl2
  9305. ...
  9306. @Lbl1:
  9307. ret
  9308. Change to:
  9309. jmp<inv_cond> @Lbl2
  9310. ret
  9311. }
  9312. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9313. begin
  9314. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9315. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9316. MatchInstruction(hp2,A_RET,[S_NO]) then
  9317. begin
  9318. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9319. { Change label address to that of the unconditional jump }
  9320. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9321. TAsmLabel(symbol).DecRefs;
  9322. taicpu(hp1).opcode := A_RET;
  9323. taicpu(hp1).is_jmp := false;
  9324. taicpu(hp1).ops := taicpu(hp2).ops;
  9325. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9326. case taicpu(hp2).ops of
  9327. 0:
  9328. taicpu(hp1).clearop(0);
  9329. 1:
  9330. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9331. else
  9332. internalerror(2016041302);
  9333. end;
  9334. end;
  9335. {$ifndef i8086}
  9336. end
  9337. {
  9338. convert
  9339. j<c> .L1
  9340. mov 1,reg
  9341. jmp .L2
  9342. .L1
  9343. mov 0,reg
  9344. .L2
  9345. into
  9346. mov 0,reg
  9347. set<not(c)> reg
  9348. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9349. would destroy the flag contents
  9350. }
  9351. else if MatchInstruction(hp1,A_MOV,[]) and
  9352. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9353. {$ifdef i386}
  9354. (
  9355. { Under i386, ESI, EDI, EBP and ESP
  9356. don't have an 8-bit representation }
  9357. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9358. ) and
  9359. {$endif i386}
  9360. (taicpu(hp1).oper[0]^.val=1) and
  9361. GetNextInstruction(hp1,hp2) and
  9362. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9363. GetNextInstruction(hp2,hp3) and
  9364. { skip align }
  9365. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9366. (hp3.typ=ait_label) and
  9367. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9368. (tai_label(hp3).labsym.getrefs=1) and
  9369. GetNextInstruction(hp3,hp4) and
  9370. MatchInstruction(hp4,A_MOV,[]) and
  9371. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9372. (taicpu(hp4).oper[0]^.val=0) and
  9373. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9374. GetNextInstruction(hp4,hp5) and
  9375. (hp5.typ=ait_label) and
  9376. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9377. (tai_label(hp5).labsym.getrefs=1) then
  9378. begin
  9379. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9380. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9381. { remove last label }
  9382. RemoveInstruction(hp5);
  9383. { remove second label }
  9384. RemoveInstruction(hp3);
  9385. { if align is present remove it }
  9386. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9387. RemoveInstruction(hp3);
  9388. { remove jmp }
  9389. RemoveInstruction(hp2);
  9390. if taicpu(hp1).opsize=S_B then
  9391. RemoveInstruction(hp1)
  9392. else
  9393. taicpu(hp1).loadconst(0,0);
  9394. taicpu(hp4).opcode:=A_SETcc;
  9395. taicpu(hp4).opsize:=S_B;
  9396. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9397. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9398. taicpu(hp4).opercnt:=1;
  9399. taicpu(hp4).ops:=1;
  9400. taicpu(hp4).freeop(1);
  9401. RemoveCurrentP(p);
  9402. Result:=true;
  9403. exit;
  9404. end
  9405. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9406. begin
  9407. { check for
  9408. jCC xxx
  9409. <several movs>
  9410. xxx:
  9411. }
  9412. l:=0;
  9413. while assigned(hp1) and
  9414. CanBeCMOV(hp1) and
  9415. { stop on labels }
  9416. not(hp1.typ=ait_label) do
  9417. begin
  9418. inc(l);
  9419. hp5 := hp1;
  9420. GetNextInstruction(hp1,hp1);
  9421. end;
  9422. if assigned(hp1) then
  9423. begin
  9424. TransferUsedRegs(TmpUsedRegs);
  9425. if FindLabel(tasmlabel(symbol),hp1) then
  9426. begin
  9427. if (l<=4) and (l>0) then
  9428. begin
  9429. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9430. condition:=inverse_cond(taicpu(p).condition);
  9431. UpdateUsedRegs(tai(p.next));
  9432. GetNextInstruction(p,hp1);
  9433. repeat
  9434. if not Assigned(hp1) then
  9435. InternalError(2018062900);
  9436. taicpu(hp1).opcode:=A_CMOVcc;
  9437. taicpu(hp1).condition:=condition;
  9438. UpdateUsedRegs(tai(hp1.next));
  9439. GetNextInstruction(hp1,hp1);
  9440. until not(CanBeCMOV(hp1));
  9441. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9442. hp2 := hp1;
  9443. repeat
  9444. if not Assigned(hp2) then
  9445. InternalError(2018062910);
  9446. case hp2.typ of
  9447. ait_label:
  9448. { What we expected - break out of the loop (it won't be a dead label at the top of
  9449. a cluster because that was optimised at an earlier stage) }
  9450. Break;
  9451. ait_align:
  9452. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9453. begin
  9454. hp2 := tai(hp2.Next);
  9455. Continue;
  9456. end;
  9457. else
  9458. begin
  9459. { Might be a comment or temporary allocation entry }
  9460. if not (hp2.typ in SkipInstr) then
  9461. InternalError(2018062911);
  9462. hp2 := tai(hp2.Next);
  9463. Continue;
  9464. end;
  9465. end;
  9466. until False;
  9467. { Now we can safely decrement the reference count }
  9468. tasmlabel(symbol).decrefs;
  9469. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9470. { Remove the original jump }
  9471. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9472. UpdateUsedRegs(tai(hp2.next));
  9473. GetNextInstruction(hp2, p); { Instruction after the label }
  9474. { Remove the label if this is its final reference }
  9475. if (tasmlabel(symbol).getrefs=0) then
  9476. StripLabelFast(hp1);
  9477. if Assigned(p) then
  9478. result:=true;
  9479. exit;
  9480. end;
  9481. end
  9482. else
  9483. begin
  9484. { check further for
  9485. jCC xxx
  9486. <several movs 1>
  9487. jmp yyy
  9488. xxx:
  9489. <several movs 2>
  9490. yyy:
  9491. }
  9492. { hp2 points to jmp yyy }
  9493. hp2:=hp1;
  9494. { skip hp1 to xxx (or an align right before it) }
  9495. GetNextInstruction(hp1, hp1);
  9496. if assigned(hp2) and
  9497. assigned(hp1) and
  9498. (l<=3) and
  9499. (hp2.typ=ait_instruction) and
  9500. (taicpu(hp2).is_jmp) and
  9501. (taicpu(hp2).condition=C_None) and
  9502. { real label and jump, no further references to the
  9503. label are allowed }
  9504. (tasmlabel(symbol).getrefs=1) and
  9505. FindLabel(tasmlabel(symbol),hp1) then
  9506. begin
  9507. l:=0;
  9508. { skip hp1 to <several moves 2> }
  9509. if (hp1.typ = ait_align) then
  9510. GetNextInstruction(hp1, hp1);
  9511. GetNextInstruction(hp1, hpmov2);
  9512. hp1 := hpmov2;
  9513. while assigned(hp1) and
  9514. CanBeCMOV(hp1) do
  9515. begin
  9516. inc(l);
  9517. hp5 := hp1;
  9518. GetNextInstruction(hp1, hp1);
  9519. end;
  9520. { hp1 points to yyy (or an align right before it) }
  9521. hp3 := hp1;
  9522. if assigned(hp1) and
  9523. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9524. begin
  9525. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9526. condition:=inverse_cond(taicpu(p).condition);
  9527. UpdateUsedRegs(tai(p.next));
  9528. GetNextInstruction(p,hp1);
  9529. repeat
  9530. taicpu(hp1).opcode:=A_CMOVcc;
  9531. taicpu(hp1).condition:=condition;
  9532. UpdateUsedRegs(tai(hp1.next));
  9533. GetNextInstruction(hp1,hp1);
  9534. until not(assigned(hp1)) or
  9535. not(CanBeCMOV(hp1));
  9536. condition:=inverse_cond(condition);
  9537. if GetLastInstruction(hpmov2,hp1) then
  9538. UpdateUsedRegs(tai(hp1.next));
  9539. hp1 := hpmov2;
  9540. { hp1 is now at <several movs 2> }
  9541. while Assigned(hp1) and CanBeCMOV(hp1) do
  9542. begin
  9543. taicpu(hp1).opcode:=A_CMOVcc;
  9544. taicpu(hp1).condition:=condition;
  9545. UpdateUsedRegs(tai(hp1.next));
  9546. GetNextInstruction(hp1,hp1);
  9547. end;
  9548. hp1 := p;
  9549. { Get first instruction after label }
  9550. UpdateUsedRegs(tai(hp3.next));
  9551. GetNextInstruction(hp3, p);
  9552. if assigned(p) and (hp3.typ = ait_align) then
  9553. GetNextInstruction(p, p);
  9554. { Don't dereference yet, as doing so will cause
  9555. GetNextInstruction to skip the label and
  9556. optional align marker. [Kit] }
  9557. GetNextInstruction(hp2, hp4);
  9558. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9559. { remove jCC }
  9560. RemoveInstruction(hp1);
  9561. { Now we can safely decrement it }
  9562. tasmlabel(symbol).decrefs;
  9563. { Remove label xxx (it will have a ref of zero due to the initial check }
  9564. StripLabelFast(hp4);
  9565. { remove jmp }
  9566. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9567. RemoveInstruction(hp2);
  9568. { As before, now we can safely decrement it }
  9569. tasmlabel(symbol).decrefs;
  9570. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9571. if tasmlabel(symbol).getrefs = 0 then
  9572. StripLabelFast(hp3);
  9573. if Assigned(p) then
  9574. result:=true;
  9575. exit;
  9576. end;
  9577. end;
  9578. end;
  9579. end;
  9580. {$endif i8086}
  9581. end;
  9582. end;
  9583. end;
  9584. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9585. var
  9586. hp1,hp2,hp3: tai;
  9587. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9588. NewSize: TOpSize;
  9589. NewRegSize: TSubRegister;
  9590. Limit: TCgInt;
  9591. SwapOper: POper;
  9592. begin
  9593. result:=false;
  9594. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9595. GetNextInstruction(p,hp1) and
  9596. (hp1.typ = ait_instruction);
  9597. if reg_and_hp1_is_instr and
  9598. (
  9599. (taicpu(hp1).opcode <> A_LEA) or
  9600. { If the LEA instruction can be converted into an arithmetic instruction,
  9601. it may be possible to then fold it. }
  9602. (
  9603. { If the flags register is in use, don't change the instruction
  9604. to an ADD otherwise this will scramble the flags. [Kit] }
  9605. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9606. ConvertLEA(taicpu(hp1))
  9607. )
  9608. ) and
  9609. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9610. GetNextInstruction(hp1,hp2) and
  9611. MatchInstruction(hp2,A_MOV,[]) and
  9612. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9613. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9614. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9615. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9616. {$ifdef i386}
  9617. { not all registers have byte size sub registers on i386 }
  9618. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9619. {$endif i386}
  9620. (((taicpu(hp1).ops=2) and
  9621. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9622. ((taicpu(hp1).ops=1) and
  9623. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9624. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9625. begin
  9626. { change movsX/movzX reg/ref, reg2
  9627. add/sub/or/... reg3/$const, reg2
  9628. mov reg2 reg/ref
  9629. to add/sub/or/... reg3/$const, reg/ref }
  9630. { by example:
  9631. movswl %si,%eax movswl %si,%eax p
  9632. decl %eax addl %edx,%eax hp1
  9633. movw %ax,%si movw %ax,%si hp2
  9634. ->
  9635. movswl %si,%eax movswl %si,%eax p
  9636. decw %eax addw %edx,%eax hp1
  9637. movw %ax,%si movw %ax,%si hp2
  9638. }
  9639. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9640. {
  9641. ->
  9642. movswl %si,%eax movswl %si,%eax p
  9643. decw %si addw %dx,%si hp1
  9644. movw %ax,%si movw %ax,%si hp2
  9645. }
  9646. case taicpu(hp1).ops of
  9647. 1:
  9648. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9649. 2:
  9650. begin
  9651. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9652. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9653. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9654. end;
  9655. else
  9656. internalerror(2008042702);
  9657. end;
  9658. {
  9659. ->
  9660. decw %si addw %dx,%si p
  9661. }
  9662. DebugMsg(SPeepholeOptimization + 'var3',p);
  9663. RemoveCurrentP(p, hp1);
  9664. RemoveInstruction(hp2);
  9665. Result := True;
  9666. Exit;
  9667. end;
  9668. if reg_and_hp1_is_instr and
  9669. (taicpu(hp1).opcode = A_MOV) and
  9670. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9671. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9672. {$ifdef x86_64}
  9673. { check for implicit extension to 64 bit }
  9674. or
  9675. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9676. (taicpu(hp1).opsize=S_Q) and
  9677. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9678. )
  9679. {$endif x86_64}
  9680. )
  9681. then
  9682. begin
  9683. { change
  9684. movx %reg1,%reg2
  9685. mov %reg2,%reg3
  9686. dealloc %reg2
  9687. into
  9688. movx %reg,%reg3
  9689. }
  9690. TransferUsedRegs(TmpUsedRegs);
  9691. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9692. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9693. begin
  9694. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9695. {$ifdef x86_64}
  9696. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9697. (taicpu(hp1).opsize=S_Q) then
  9698. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9699. else
  9700. {$endif x86_64}
  9701. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9702. RemoveInstruction(hp1);
  9703. Result := True;
  9704. Exit;
  9705. end;
  9706. end;
  9707. if reg_and_hp1_is_instr and
  9708. ((taicpu(hp1).opcode=A_MOV) or
  9709. (taicpu(hp1).opcode=A_ADD) or
  9710. (taicpu(hp1).opcode=A_SUB) or
  9711. (taicpu(hp1).opcode=A_CMP) or
  9712. (taicpu(hp1).opcode=A_OR) or
  9713. (taicpu(hp1).opcode=A_XOR) or
  9714. (taicpu(hp1).opcode=A_AND)
  9715. ) and
  9716. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9717. begin
  9718. AndTest := (taicpu(hp1).opcode=A_AND) and
  9719. GetNextInstruction(hp1, hp2) and
  9720. (hp2.typ = ait_instruction) and
  9721. (
  9722. (
  9723. (taicpu(hp2).opcode=A_TEST) and
  9724. (
  9725. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9726. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9727. (
  9728. { If the AND and TEST instructions share a constant, this is also valid }
  9729. (taicpu(hp1).oper[0]^.typ = top_const) and
  9730. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9731. )
  9732. ) and
  9733. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9734. ) or
  9735. (
  9736. (taicpu(hp2).opcode=A_CMP) and
  9737. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9738. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9739. )
  9740. );
  9741. { change
  9742. movx (oper),%reg2
  9743. and $x,%reg2
  9744. test %reg2,%reg2
  9745. dealloc %reg2
  9746. into
  9747. op %reg1,%reg3
  9748. if the second op accesses only the bits stored in reg1
  9749. }
  9750. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9751. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9752. (taicpu(hp1).oper[0]^.typ = top_const) and
  9753. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9754. AndTest then
  9755. begin
  9756. { Check if the AND constant is in range }
  9757. case taicpu(p).opsize of
  9758. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9759. begin
  9760. NewSize := S_B;
  9761. Limit := $FF;
  9762. end;
  9763. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9764. begin
  9765. NewSize := S_W;
  9766. Limit := $FFFF;
  9767. end;
  9768. {$ifdef x86_64}
  9769. S_LQ:
  9770. begin
  9771. NewSize := S_L;
  9772. Limit := $FFFFFFFF;
  9773. end;
  9774. {$endif x86_64}
  9775. else
  9776. InternalError(2021120303);
  9777. end;
  9778. if (
  9779. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9780. { Check for negative operands }
  9781. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9782. ) and
  9783. GetNextInstruction(hp2,hp3) and
  9784. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9785. (taicpu(hp3).condition in [C_E,C_NE]) then
  9786. begin
  9787. TransferUsedRegs(TmpUsedRegs);
  9788. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9789. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9790. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9791. begin
  9792. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9793. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9794. taicpu(hp1).opcode := A_TEST;
  9795. taicpu(hp1).opsize := NewSize;
  9796. RemoveInstruction(hp2);
  9797. RemoveCurrentP(p, hp1);
  9798. Result:=true;
  9799. exit;
  9800. end;
  9801. end;
  9802. end;
  9803. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9804. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9805. (taicpu(hp1).opsize=S_B)) or
  9806. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9807. (taicpu(hp1).opsize=S_W))
  9808. {$ifdef x86_64}
  9809. or ((taicpu(p).opsize=S_LQ) and
  9810. (taicpu(hp1).opsize=S_L))
  9811. {$endif x86_64}
  9812. ) and
  9813. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9814. begin
  9815. { change
  9816. movx %reg1,%reg2
  9817. op %reg2,%reg3
  9818. dealloc %reg2
  9819. into
  9820. op %reg1,%reg3
  9821. if the second op accesses only the bits stored in reg1
  9822. }
  9823. TransferUsedRegs(TmpUsedRegs);
  9824. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9825. if AndTest then
  9826. begin
  9827. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9828. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9829. end
  9830. else
  9831. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9832. if not RegUsed then
  9833. begin
  9834. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9835. if taicpu(p).oper[0]^.typ=top_reg then
  9836. begin
  9837. case taicpu(hp1).opsize of
  9838. S_B:
  9839. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9840. S_W:
  9841. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9842. S_L:
  9843. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9844. else
  9845. Internalerror(2020102301);
  9846. end;
  9847. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9848. end
  9849. else
  9850. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9851. RemoveCurrentP(p);
  9852. if AndTest then
  9853. RemoveInstruction(hp2);
  9854. result:=true;
  9855. exit;
  9856. end;
  9857. end
  9858. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9859. (
  9860. { Bitwise operations only }
  9861. (taicpu(hp1).opcode=A_AND) or
  9862. (taicpu(hp1).opcode=A_TEST) or
  9863. (
  9864. (taicpu(hp1).oper[0]^.typ = top_const) and
  9865. (
  9866. (taicpu(hp1).opcode=A_OR) or
  9867. (taicpu(hp1).opcode=A_XOR)
  9868. )
  9869. )
  9870. ) and
  9871. (
  9872. (taicpu(hp1).oper[0]^.typ = top_const) or
  9873. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9874. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9875. ) then
  9876. begin
  9877. { change
  9878. movx %reg2,%reg2
  9879. op const,%reg2
  9880. into
  9881. op const,%reg2 (smaller version)
  9882. movx %reg2,%reg2
  9883. also change
  9884. movx %reg1,%reg2
  9885. and/test (oper),%reg2
  9886. dealloc %reg2
  9887. into
  9888. and/test (oper),%reg1
  9889. }
  9890. case taicpu(p).opsize of
  9891. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9892. begin
  9893. NewSize := S_B;
  9894. NewRegSize := R_SUBL;
  9895. Limit := $FF;
  9896. end;
  9897. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9898. begin
  9899. NewSize := S_W;
  9900. NewRegSize := R_SUBW;
  9901. Limit := $FFFF;
  9902. end;
  9903. {$ifdef x86_64}
  9904. S_LQ:
  9905. begin
  9906. NewSize := S_L;
  9907. NewRegSize := R_SUBD;
  9908. Limit := $FFFFFFFF;
  9909. end;
  9910. {$endif x86_64}
  9911. else
  9912. Internalerror(2021120302);
  9913. end;
  9914. TransferUsedRegs(TmpUsedRegs);
  9915. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9916. if AndTest then
  9917. begin
  9918. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9919. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9920. end
  9921. else
  9922. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9923. if
  9924. (
  9925. (taicpu(p).opcode = A_MOVZX) and
  9926. (
  9927. (taicpu(hp1).opcode=A_AND) or
  9928. (taicpu(hp1).opcode=A_TEST)
  9929. ) and
  9930. not (
  9931. { If both are references, then the final instruction will have
  9932. both operands as references, which is not allowed }
  9933. (taicpu(p).oper[0]^.typ = top_ref) and
  9934. (taicpu(hp1).oper[0]^.typ = top_ref)
  9935. ) and
  9936. not RegUsed
  9937. ) or
  9938. (
  9939. (
  9940. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9941. not RegUsed
  9942. ) and
  9943. (taicpu(p).oper[0]^.typ = top_reg) and
  9944. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9945. (taicpu(hp1).oper[0]^.typ = top_const) and
  9946. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9947. ) then
  9948. begin
  9949. {$if defined(i386) or defined(i8086)}
  9950. { If the target size is 8-bit, make sure we can actually encode it }
  9951. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9952. Exit;
  9953. {$endif i386 or i8086}
  9954. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9955. taicpu(hp1).opsize := NewSize;
  9956. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9957. if AndTest then
  9958. begin
  9959. RemoveInstruction(hp2);
  9960. if not RegUsed then
  9961. begin
  9962. taicpu(hp1).opcode := A_TEST;
  9963. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  9964. begin
  9965. { Make sure the reference is the second operand }
  9966. SwapOper := taicpu(hp1).oper[0];
  9967. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9968. taicpu(hp1).oper[1] := SwapOper;
  9969. end;
  9970. end;
  9971. end;
  9972. case taicpu(hp1).oper[0]^.typ of
  9973. top_reg:
  9974. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9975. top_const:
  9976. { For the AND/TEST case }
  9977. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9978. else
  9979. ;
  9980. end;
  9981. if RegUsed then
  9982. begin
  9983. AsmL.Remove(p);
  9984. AsmL.InsertAfter(p, hp1);
  9985. p := hp1;
  9986. end
  9987. else
  9988. RemoveCurrentP(p, hp1);
  9989. result:=true;
  9990. exit;
  9991. end;
  9992. end;
  9993. end;
  9994. if reg_and_hp1_is_instr and
  9995. (taicpu(p).oper[0]^.typ = top_reg) and
  9996. (
  9997. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9998. ) and
  9999. (taicpu(hp1).oper[0]^.typ = top_const) and
  10000. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10001. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10002. { Minimum shift value allowed is the bit difference between the sizes }
  10003. (taicpu(hp1).oper[0]^.val >=
  10004. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10005. 8 * (
  10006. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10007. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10008. )
  10009. ) then
  10010. begin
  10011. { For:
  10012. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10013. shl/sal ##, %reg1
  10014. Remove the movsx/movzx instruction if the shift overwrites the
  10015. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10016. }
  10017. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10018. RemoveCurrentP(p, hp1);
  10019. Result := True;
  10020. Exit;
  10021. end
  10022. else if reg_and_hp1_is_instr and
  10023. (taicpu(p).oper[0]^.typ = top_reg) and
  10024. (
  10025. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10026. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10027. ) and
  10028. (taicpu(hp1).oper[0]^.typ = top_const) and
  10029. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10030. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10031. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10032. (taicpu(hp1).oper[0]^.val <
  10033. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10034. 8 * (
  10035. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10036. )
  10037. ) then
  10038. begin
  10039. { For:
  10040. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10041. sar ##, %reg1 shr ##, %reg1
  10042. Move the shift to before the movx instruction if the shift value
  10043. is not too large.
  10044. }
  10045. asml.Remove(hp1);
  10046. asml.InsertBefore(hp1, p);
  10047. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10048. case taicpu(p).opsize of
  10049. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10050. taicpu(hp1).opsize := S_B;
  10051. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10052. taicpu(hp1).opsize := S_W;
  10053. {$ifdef x86_64}
  10054. S_LQ:
  10055. taicpu(hp1).opsize := S_L;
  10056. {$endif}
  10057. else
  10058. InternalError(2020112401);
  10059. end;
  10060. if (taicpu(hp1).opcode = A_SHR) then
  10061. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10062. else
  10063. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10064. Result := True;
  10065. end;
  10066. if reg_and_hp1_is_instr and
  10067. (taicpu(p).oper[0]^.typ = top_reg) and
  10068. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10069. (
  10070. (taicpu(hp1).opcode = taicpu(p).opcode)
  10071. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10072. {$ifdef x86_64}
  10073. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10074. {$endif x86_64}
  10075. ) then
  10076. begin
  10077. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10078. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10079. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10080. begin
  10081. {
  10082. For example:
  10083. movzbw %al,%ax
  10084. movzwl %ax,%eax
  10085. Compress into:
  10086. movzbl %al,%eax
  10087. }
  10088. RegUsed := False;
  10089. case taicpu(p).opsize of
  10090. S_BW:
  10091. case taicpu(hp1).opsize of
  10092. S_WL:
  10093. begin
  10094. taicpu(p).opsize := S_BL;
  10095. RegUsed := True;
  10096. end;
  10097. {$ifdef x86_64}
  10098. S_WQ:
  10099. begin
  10100. if taicpu(p).opcode = A_MOVZX then
  10101. begin
  10102. taicpu(p).opsize := S_BL;
  10103. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10104. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10105. end
  10106. else
  10107. taicpu(p).opsize := S_BQ;
  10108. RegUsed := True;
  10109. end;
  10110. {$endif x86_64}
  10111. else
  10112. ;
  10113. end;
  10114. {$ifdef x86_64}
  10115. S_BL:
  10116. case taicpu(hp1).opsize of
  10117. S_LQ:
  10118. begin
  10119. if taicpu(p).opcode = A_MOVZX then
  10120. begin
  10121. taicpu(p).opsize := S_BL;
  10122. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10123. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10124. end
  10125. else
  10126. taicpu(p).opsize := S_BQ;
  10127. RegUsed := True;
  10128. end;
  10129. else
  10130. ;
  10131. end;
  10132. S_WL:
  10133. case taicpu(hp1).opsize of
  10134. S_LQ:
  10135. begin
  10136. if taicpu(p).opcode = A_MOVZX then
  10137. begin
  10138. taicpu(p).opsize := S_WL;
  10139. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10140. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10141. end
  10142. else
  10143. taicpu(p).opsize := S_WQ;
  10144. RegUsed := True;
  10145. end;
  10146. else
  10147. ;
  10148. end;
  10149. {$endif x86_64}
  10150. else
  10151. ;
  10152. end;
  10153. if RegUsed then
  10154. begin
  10155. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10156. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10157. RemoveInstruction(hp1);
  10158. Result := True;
  10159. Exit;
  10160. end;
  10161. end;
  10162. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10163. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10164. GetNextInstruction(hp1, hp2) and
  10165. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10166. (
  10167. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10168. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10169. {$ifdef x86_64}
  10170. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10171. {$endif x86_64}
  10172. ) and
  10173. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10174. (
  10175. (
  10176. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10177. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10178. ) or
  10179. (
  10180. { Only allow the operands in reverse order for TEST instructions }
  10181. (taicpu(hp2).opcode = A_TEST) and
  10182. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10183. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10184. )
  10185. ) then
  10186. begin
  10187. {
  10188. For example:
  10189. movzbl %al,%eax
  10190. movzbl (ref),%edx
  10191. andl %edx,%eax
  10192. (%edx deallocated)
  10193. Change to:
  10194. andb (ref),%al
  10195. movzbl %al,%eax
  10196. Rules are:
  10197. - First two instructions have the same opcode and opsize
  10198. - First instruction's operands are the same super-register
  10199. - Second instruction operates on a different register
  10200. - Third instruction is AND, OR, XOR or TEST
  10201. - Third instruction's operands are the destination registers of the first two instructions
  10202. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10203. - Second instruction's destination register is deallocated afterwards
  10204. }
  10205. TransferUsedRegs(TmpUsedRegs);
  10206. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10207. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10208. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10209. begin
  10210. case taicpu(p).opsize of
  10211. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10212. NewSize := S_B;
  10213. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10214. NewSize := S_W;
  10215. {$ifdef x86_64}
  10216. S_LQ:
  10217. NewSize := S_L;
  10218. {$endif x86_64}
  10219. else
  10220. InternalError(2021120301);
  10221. end;
  10222. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10223. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10224. taicpu(hp2).opsize := NewSize;
  10225. RemoveInstruction(hp1);
  10226. { With TEST, it's best to keep the MOVX instruction at the top }
  10227. if (taicpu(hp2).opcode <> A_TEST) then
  10228. begin
  10229. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10230. asml.Remove(p);
  10231. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10232. asml.InsertAfter(p, hp2);
  10233. p := hp2;
  10234. end
  10235. else
  10236. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10237. Result := True;
  10238. Exit;
  10239. end;
  10240. end;
  10241. end;
  10242. if taicpu(p).opcode=A_MOVZX then
  10243. begin
  10244. { removes superfluous And's after movzx's }
  10245. if reg_and_hp1_is_instr and
  10246. (taicpu(hp1).opcode = A_AND) and
  10247. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10248. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10249. {$ifdef x86_64}
  10250. { check for implicit extension to 64 bit }
  10251. or
  10252. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10253. (taicpu(hp1).opsize=S_Q) and
  10254. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10255. )
  10256. {$endif x86_64}
  10257. )
  10258. then
  10259. begin
  10260. case taicpu(p).opsize Of
  10261. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10262. if (taicpu(hp1).oper[0]^.val = $ff) then
  10263. begin
  10264. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10265. RemoveInstruction(hp1);
  10266. Result:=true;
  10267. exit;
  10268. end;
  10269. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10270. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10271. begin
  10272. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10273. RemoveInstruction(hp1);
  10274. Result:=true;
  10275. exit;
  10276. end;
  10277. {$ifdef x86_64}
  10278. S_LQ:
  10279. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10280. begin
  10281. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10282. RemoveInstruction(hp1);
  10283. Result:=true;
  10284. exit;
  10285. end;
  10286. {$endif x86_64}
  10287. else
  10288. ;
  10289. end;
  10290. { we cannot get rid of the and, but can we get rid of the movz ?}
  10291. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10292. begin
  10293. case taicpu(p).opsize Of
  10294. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10295. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10296. begin
  10297. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10298. RemoveCurrentP(p,hp1);
  10299. Result:=true;
  10300. exit;
  10301. end;
  10302. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10303. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10304. begin
  10305. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10306. RemoveCurrentP(p,hp1);
  10307. Result:=true;
  10308. exit;
  10309. end;
  10310. {$ifdef x86_64}
  10311. S_LQ:
  10312. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10313. begin
  10314. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10315. RemoveCurrentP(p,hp1);
  10316. Result:=true;
  10317. exit;
  10318. end;
  10319. {$endif x86_64}
  10320. else
  10321. ;
  10322. end;
  10323. end;
  10324. end;
  10325. { changes some movzx constructs to faster synonyms (all examples
  10326. are given with eax/ax, but are also valid for other registers)}
  10327. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10328. begin
  10329. case taicpu(p).opsize of
  10330. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10331. (the machine code is equivalent to movzbl %al,%eax), but the
  10332. code generator still generates that assembler instruction and
  10333. it is silently converted. This should probably be checked.
  10334. [Kit] }
  10335. S_BW:
  10336. begin
  10337. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10338. (
  10339. not IsMOVZXAcceptable
  10340. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10341. or (
  10342. (cs_opt_size in current_settings.optimizerswitches) and
  10343. (taicpu(p).oper[1]^.reg = NR_AX)
  10344. )
  10345. ) then
  10346. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10347. begin
  10348. DebugMsg(SPeepholeOptimization + 'var7',p);
  10349. taicpu(p).opcode := A_AND;
  10350. taicpu(p).changeopsize(S_W);
  10351. taicpu(p).loadConst(0,$ff);
  10352. Result := True;
  10353. end
  10354. else if not IsMOVZXAcceptable and
  10355. GetNextInstruction(p, hp1) and
  10356. (tai(hp1).typ = ait_instruction) and
  10357. (taicpu(hp1).opcode = A_AND) and
  10358. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10359. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10360. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10361. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10362. begin
  10363. DebugMsg(SPeepholeOptimization + 'var8',p);
  10364. taicpu(p).opcode := A_MOV;
  10365. taicpu(p).changeopsize(S_W);
  10366. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10367. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10368. Result := True;
  10369. end;
  10370. end;
  10371. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10372. S_BL:
  10373. begin
  10374. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10375. (
  10376. not IsMOVZXAcceptable
  10377. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10378. or (
  10379. (cs_opt_size in current_settings.optimizerswitches) and
  10380. (taicpu(p).oper[1]^.reg = NR_EAX)
  10381. )
  10382. ) then
  10383. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10384. begin
  10385. DebugMsg(SPeepholeOptimization + 'var9',p);
  10386. taicpu(p).opcode := A_AND;
  10387. taicpu(p).changeopsize(S_L);
  10388. taicpu(p).loadConst(0,$ff);
  10389. Result := True;
  10390. end
  10391. else if not IsMOVZXAcceptable and
  10392. GetNextInstruction(p, hp1) and
  10393. (tai(hp1).typ = ait_instruction) and
  10394. (taicpu(hp1).opcode = A_AND) and
  10395. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10396. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10397. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10398. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10399. begin
  10400. DebugMsg(SPeepholeOptimization + 'var10',p);
  10401. taicpu(p).opcode := A_MOV;
  10402. taicpu(p).changeopsize(S_L);
  10403. { do not use R_SUBWHOLE
  10404. as movl %rdx,%eax
  10405. is invalid in assembler PM }
  10406. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10407. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10408. Result := True;
  10409. end;
  10410. end;
  10411. {$endif i8086}
  10412. S_WL:
  10413. if not IsMOVZXAcceptable then
  10414. begin
  10415. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10416. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10417. begin
  10418. DebugMsg(SPeepholeOptimization + 'var11',p);
  10419. taicpu(p).opcode := A_AND;
  10420. taicpu(p).changeopsize(S_L);
  10421. taicpu(p).loadConst(0,$ffff);
  10422. Result := True;
  10423. end
  10424. else if GetNextInstruction(p, hp1) and
  10425. (tai(hp1).typ = ait_instruction) and
  10426. (taicpu(hp1).opcode = A_AND) and
  10427. (taicpu(hp1).oper[0]^.typ = top_const) and
  10428. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10429. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10430. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10431. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10432. begin
  10433. DebugMsg(SPeepholeOptimization + 'var12',p);
  10434. taicpu(p).opcode := A_MOV;
  10435. taicpu(p).changeopsize(S_L);
  10436. { do not use R_SUBWHOLE
  10437. as movl %rdx,%eax
  10438. is invalid in assembler PM }
  10439. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10440. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10441. Result := True;
  10442. end;
  10443. end;
  10444. else
  10445. InternalError(2017050705);
  10446. end;
  10447. end
  10448. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10449. begin
  10450. if GetNextInstruction(p, hp1) and
  10451. (tai(hp1).typ = ait_instruction) and
  10452. (taicpu(hp1).opcode = A_AND) and
  10453. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10454. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10455. begin
  10456. //taicpu(p).opcode := A_MOV;
  10457. case taicpu(p).opsize Of
  10458. S_BL:
  10459. begin
  10460. DebugMsg(SPeepholeOptimization + 'var13',p);
  10461. taicpu(hp1).changeopsize(S_L);
  10462. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10463. end;
  10464. S_WL:
  10465. begin
  10466. DebugMsg(SPeepholeOptimization + 'var14',p);
  10467. taicpu(hp1).changeopsize(S_L);
  10468. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10469. end;
  10470. S_BW:
  10471. begin
  10472. DebugMsg(SPeepholeOptimization + 'var15',p);
  10473. taicpu(hp1).changeopsize(S_W);
  10474. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10475. end;
  10476. else
  10477. Internalerror(2017050704)
  10478. end;
  10479. Result := True;
  10480. end;
  10481. end;
  10482. end;
  10483. end;
  10484. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10485. var
  10486. hp1, hp2 : tai;
  10487. MaskLength : Cardinal;
  10488. MaskedBits : TCgInt;
  10489. ActiveReg : TRegister;
  10490. begin
  10491. Result:=false;
  10492. { There are no optimisations for reference targets }
  10493. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10494. Exit;
  10495. while GetNextInstruction(p, hp1) and
  10496. (hp1.typ = ait_instruction) do
  10497. begin
  10498. if (taicpu(p).oper[0]^.typ = top_const) then
  10499. begin
  10500. case taicpu(hp1).opcode of
  10501. A_AND:
  10502. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10503. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10504. { the second register must contain the first one, so compare their subreg types }
  10505. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10506. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10507. { change
  10508. and const1, reg
  10509. and const2, reg
  10510. to
  10511. and (const1 and const2), reg
  10512. }
  10513. begin
  10514. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10515. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10516. RemoveCurrentP(p, hp1);
  10517. Result:=true;
  10518. exit;
  10519. end;
  10520. A_CMP:
  10521. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10522. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10523. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10524. { Just check that the condition on the next instruction is compatible }
  10525. GetNextInstruction(hp1, hp2) and
  10526. (hp2.typ = ait_instruction) and
  10527. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10528. then
  10529. { change
  10530. and 2^n, reg
  10531. cmp 2^n, reg
  10532. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10533. to
  10534. and 2^n, reg
  10535. test reg, reg
  10536. j(~c) / set(~c) / cmov(~c)
  10537. }
  10538. begin
  10539. { Keep TEST instruction in, rather than remove it, because
  10540. it may trigger other optimisations such as MovAndTest2Test }
  10541. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10542. taicpu(hp1).opcode := A_TEST;
  10543. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10544. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10545. Result := True;
  10546. Exit;
  10547. end;
  10548. A_MOVZX:
  10549. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10550. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10551. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10552. (
  10553. (
  10554. (taicpu(p).opsize=S_W) and
  10555. (taicpu(hp1).opsize=S_BW)
  10556. ) or
  10557. (
  10558. (taicpu(p).opsize=S_L) and
  10559. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10560. )
  10561. {$ifdef x86_64}
  10562. or
  10563. (
  10564. (taicpu(p).opsize=S_Q) and
  10565. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10566. )
  10567. {$endif x86_64}
  10568. ) then
  10569. begin
  10570. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10571. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10572. ) or
  10573. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10574. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10575. then
  10576. begin
  10577. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10578. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10579. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10580. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10581. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10582. }
  10583. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10584. RemoveInstruction(hp1);
  10585. { See if there are other optimisations possible }
  10586. Continue;
  10587. end;
  10588. end;
  10589. A_SHL:
  10590. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10591. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10592. begin
  10593. {$ifopt R+}
  10594. {$define RANGE_WAS_ON}
  10595. {$R-}
  10596. {$endif}
  10597. { get length of potential and mask }
  10598. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10599. { really a mask? }
  10600. {$ifdef RANGE_WAS_ON}
  10601. {$R+}
  10602. {$endif}
  10603. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10604. { unmasked part shifted out? }
  10605. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10606. begin
  10607. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10608. RemoveCurrentP(p, hp1);
  10609. Result:=true;
  10610. exit;
  10611. end;
  10612. end;
  10613. A_SHR:
  10614. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10615. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10616. (taicpu(hp1).oper[0]^.val <= 63) then
  10617. begin
  10618. { Does SHR combined with the AND cover all the bits?
  10619. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10620. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10621. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10622. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10623. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10624. begin
  10625. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10626. RemoveCurrentP(p, hp1);
  10627. Result := True;
  10628. Exit;
  10629. end;
  10630. end;
  10631. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10632. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10633. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10634. begin
  10635. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10636. (
  10637. (
  10638. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10639. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10640. ) or (
  10641. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10642. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10643. {$ifdef x86_64}
  10644. ) or (
  10645. (taicpu(hp1).opsize = S_LQ) and
  10646. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10647. {$endif x86_64}
  10648. )
  10649. ) then
  10650. begin
  10651. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10652. begin
  10653. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10654. RemoveInstruction(hp1);
  10655. { See if there are other optimisations possible }
  10656. Continue;
  10657. end;
  10658. { The super-registers are the same though.
  10659. Note that this change by itself doesn't improve
  10660. code speed, but it opens up other optimisations. }
  10661. {$ifdef x86_64}
  10662. { Convert 64-bit register to 32-bit }
  10663. case taicpu(hp1).opsize of
  10664. S_BQ:
  10665. begin
  10666. taicpu(hp1).opsize := S_BL;
  10667. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10668. end;
  10669. S_WQ:
  10670. begin
  10671. taicpu(hp1).opsize := S_WL;
  10672. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10673. end
  10674. else
  10675. ;
  10676. end;
  10677. {$endif x86_64}
  10678. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10679. taicpu(hp1).opcode := A_MOVZX;
  10680. { See if there are other optimisations possible }
  10681. Continue;
  10682. end;
  10683. end;
  10684. else
  10685. ;
  10686. end;
  10687. end
  10688. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10689. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10690. begin
  10691. {$ifdef x86_64}
  10692. if (taicpu(p).opsize = S_Q) then
  10693. begin
  10694. { Never necessary }
  10695. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10696. RemoveCurrentP(p, hp1);
  10697. Result := True;
  10698. Exit;
  10699. end;
  10700. {$endif x86_64}
  10701. { Forward check to determine necessity of and %reg,%reg }
  10702. TransferUsedRegs(TmpUsedRegs);
  10703. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10704. { Saves on a bunch of dereferences }
  10705. ActiveReg := taicpu(p).oper[1]^.reg;
  10706. case taicpu(hp1).opcode of
  10707. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10708. if (
  10709. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10710. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10711. ) and
  10712. (
  10713. (taicpu(hp1).opcode <> A_MOV) or
  10714. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10715. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10716. ) and
  10717. not (
  10718. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10719. (taicpu(hp1).opcode = A_MOV) and
  10720. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10721. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10722. ) and
  10723. (
  10724. (
  10725. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10726. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10727. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10728. ) or
  10729. (
  10730. {$ifdef x86_64}
  10731. (
  10732. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10733. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10734. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10735. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10736. ) and
  10737. {$endif x86_64}
  10738. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10739. )
  10740. ) then
  10741. begin
  10742. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10743. RemoveCurrentP(p, hp1);
  10744. Result := True;
  10745. Exit;
  10746. end;
  10747. A_ADD,
  10748. A_AND,
  10749. A_BSF,
  10750. A_BSR,
  10751. A_BTC,
  10752. A_BTR,
  10753. A_BTS,
  10754. A_OR,
  10755. A_SUB,
  10756. A_XOR:
  10757. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10758. if (
  10759. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10760. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10761. ) and
  10762. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10763. begin
  10764. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10765. RemoveCurrentP(p, hp1);
  10766. Result := True;
  10767. Exit;
  10768. end;
  10769. A_CMP,
  10770. A_TEST:
  10771. if (
  10772. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10773. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10774. ) and
  10775. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10776. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10777. begin
  10778. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10779. RemoveCurrentP(p, hp1);
  10780. Result := True;
  10781. Exit;
  10782. end;
  10783. A_BSWAP,
  10784. A_NEG,
  10785. A_NOT:
  10786. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10787. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10788. begin
  10789. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10790. RemoveCurrentP(p, hp1);
  10791. Result := True;
  10792. Exit;
  10793. end;
  10794. else
  10795. ;
  10796. end;
  10797. end;
  10798. if (taicpu(hp1).is_jmp) and
  10799. (taicpu(hp1).opcode<>A_JMP) and
  10800. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10801. begin
  10802. { change
  10803. and x, reg
  10804. jxx
  10805. to
  10806. test x, reg
  10807. jxx
  10808. if reg is deallocated before the
  10809. jump, but only if it's a conditional jump (PFV)
  10810. }
  10811. taicpu(p).opcode := A_TEST;
  10812. Exit;
  10813. end;
  10814. Break;
  10815. end;
  10816. { Lone AND tests }
  10817. if (taicpu(p).oper[0]^.typ = top_const) then
  10818. begin
  10819. {
  10820. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10821. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10822. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10823. }
  10824. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10825. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10826. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10827. begin
  10828. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10829. if taicpu(p).opsize = S_L then
  10830. begin
  10831. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10832. Result := True;
  10833. end;
  10834. end;
  10835. end;
  10836. { Backward check to determine necessity of and %reg,%reg }
  10837. if (taicpu(p).oper[0]^.typ = top_reg) and
  10838. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10839. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10840. GetLastInstruction(p, hp2) and
  10841. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10842. { Check size of adjacent instruction to determine if the AND is
  10843. effectively a null operation }
  10844. (
  10845. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10846. { Note: Don't include S_Q }
  10847. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10848. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10849. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10850. ) then
  10851. begin
  10852. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10853. { If GetNextInstruction returned False, hp1 will be nil }
  10854. RemoveCurrentP(p, hp1);
  10855. Result := True;
  10856. Exit;
  10857. end;
  10858. end;
  10859. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10860. var
  10861. hp1: tai; NewRef: TReference;
  10862. { This entire nested function is used in an if-statement below, but we
  10863. want to avoid all the used reg transfers and GetNextInstruction calls
  10864. until we really have to check }
  10865. function MemRegisterNotUsedLater: Boolean; inline;
  10866. var
  10867. hp2: tai;
  10868. begin
  10869. TransferUsedRegs(TmpUsedRegs);
  10870. hp2 := p;
  10871. repeat
  10872. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10873. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10874. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10875. end;
  10876. begin
  10877. Result := False;
  10878. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10879. Exit;
  10880. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10881. begin
  10882. { Change:
  10883. add %reg2,%reg1
  10884. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10885. To:
  10886. mov/s/z #(%reg1,%reg2),%reg1
  10887. }
  10888. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10889. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10890. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10891. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10892. (
  10893. (
  10894. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10895. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10896. { r/esp cannot be an index }
  10897. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10898. ) or (
  10899. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10900. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10901. )
  10902. ) and (
  10903. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10904. (
  10905. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10906. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10907. MemRegisterNotUsedLater
  10908. )
  10909. ) then
  10910. begin
  10911. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10912. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10913. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10914. RemoveCurrentp(p, hp1);
  10915. Result := True;
  10916. Exit;
  10917. end;
  10918. { Change:
  10919. addl/q $x,%reg1
  10920. movl/q %reg1,%reg2
  10921. To:
  10922. leal/q $x(%reg1),%reg2
  10923. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10924. Breaks the dependency chain.
  10925. }
  10926. if MatchOpType(taicpu(p),top_const,top_reg) and
  10927. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10928. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10929. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10930. (
  10931. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10932. not (cs_opt_size in current_settings.optimizerswitches) or
  10933. (
  10934. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10935. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10936. )
  10937. ) then
  10938. begin
  10939. { Change the MOV instruction to a LEA instruction, and update the
  10940. first operand }
  10941. reference_reset(NewRef, 1, []);
  10942. NewRef.base := taicpu(p).oper[1]^.reg;
  10943. NewRef.scalefactor := 1;
  10944. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10945. taicpu(hp1).opcode := A_LEA;
  10946. taicpu(hp1).loadref(0, NewRef);
  10947. TransferUsedRegs(TmpUsedRegs);
  10948. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10949. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10950. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10951. begin
  10952. { Move what is now the LEA instruction to before the SUB instruction }
  10953. Asml.Remove(hp1);
  10954. Asml.InsertBefore(hp1, p);
  10955. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10956. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10957. p := hp1;
  10958. end
  10959. else
  10960. begin
  10961. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10962. RemoveCurrentP(p, hp1);
  10963. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10964. end;
  10965. Result := True;
  10966. end;
  10967. end;
  10968. end;
  10969. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10970. var
  10971. SubReg: TSubRegister;
  10972. begin
  10973. Result:=false;
  10974. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10975. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10976. with taicpu(p).oper[0]^.ref^ do
  10977. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10978. begin
  10979. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10980. begin
  10981. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10982. taicpu(p).opcode := A_ADD;
  10983. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10984. Result := True;
  10985. end
  10986. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10987. begin
  10988. if (base <> NR_NO) then
  10989. begin
  10990. if (scalefactor <= 1) then
  10991. begin
  10992. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10993. taicpu(p).opcode := A_ADD;
  10994. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10995. Result := True;
  10996. end;
  10997. end
  10998. else
  10999. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11000. if (scalefactor in [2, 4, 8]) then
  11001. begin
  11002. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11003. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11004. taicpu(p).opcode := A_SHL;
  11005. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11006. Result := True;
  11007. end;
  11008. end;
  11009. end;
  11010. end;
  11011. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11012. var
  11013. hp1: tai; NewRef: TReference;
  11014. begin
  11015. { Change:
  11016. subl/q $x,%reg1
  11017. movl/q %reg1,%reg2
  11018. To:
  11019. leal/q $-x(%reg1),%reg2
  11020. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11021. Breaks the dependency chain and potentially permits the removal of
  11022. a CMP instruction if one follows.
  11023. }
  11024. Result := False;
  11025. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11026. MatchOpType(taicpu(p),top_const,top_reg) and
  11027. GetNextInstruction(p, hp1) and
  11028. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11029. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11030. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11031. (
  11032. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11033. not (cs_opt_size in current_settings.optimizerswitches) or
  11034. (
  11035. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11036. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11037. )
  11038. ) then
  11039. begin
  11040. { Change the MOV instruction to a LEA instruction, and update the
  11041. first operand }
  11042. reference_reset(NewRef, 1, []);
  11043. NewRef.base := taicpu(p).oper[1]^.reg;
  11044. NewRef.scalefactor := 1;
  11045. NewRef.offset := -taicpu(p).oper[0]^.val;
  11046. taicpu(hp1).opcode := A_LEA;
  11047. taicpu(hp1).loadref(0, NewRef);
  11048. TransferUsedRegs(TmpUsedRegs);
  11049. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11050. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11051. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11052. begin
  11053. { Move what is now the LEA instruction to before the SUB instruction }
  11054. Asml.Remove(hp1);
  11055. Asml.InsertBefore(hp1, p);
  11056. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11057. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11058. p := hp1;
  11059. end
  11060. else
  11061. begin
  11062. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11063. RemoveCurrentP(p, hp1);
  11064. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11065. end;
  11066. Result := True;
  11067. end;
  11068. end;
  11069. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11070. begin
  11071. { we can skip all instructions not messing with the stack pointer }
  11072. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11073. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11074. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11075. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11076. ({(taicpu(hp1).ops=0) or }
  11077. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11078. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11079. ) and }
  11080. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11081. )
  11082. ) do
  11083. GetNextInstruction(hp1,hp1);
  11084. Result:=assigned(hp1);
  11085. end;
  11086. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11087. var
  11088. hp1, hp2, hp3, hp4, hp5: tai;
  11089. begin
  11090. Result:=false;
  11091. hp5:=nil;
  11092. { replace
  11093. leal(q) x(<stackpointer>),<stackpointer>
  11094. call procname
  11095. leal(q) -x(<stackpointer>),<stackpointer>
  11096. ret
  11097. by
  11098. jmp procname
  11099. but do it only on level 4 because it destroys stack back traces
  11100. }
  11101. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11102. MatchOpType(taicpu(p),top_ref,top_reg) and
  11103. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11104. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11105. { the -8 or -24 are not required, but bail out early if possible,
  11106. higher values are unlikely }
  11107. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11108. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11109. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11110. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11111. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  11112. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11113. GetNextInstruction(p, hp1) and
  11114. { Take a copy of hp1 }
  11115. SetAndTest(hp1, hp4) and
  11116. { trick to skip label }
  11117. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11118. SkipSimpleInstructions(hp1) and
  11119. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11120. GetNextInstruction(hp1, hp2) and
  11121. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11122. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11123. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11124. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11125. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11126. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11127. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11128. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  11129. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11130. GetNextInstruction(hp2, hp3) and
  11131. { trick to skip label }
  11132. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11133. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11134. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11135. SetAndTest(hp3,hp5) and
  11136. GetNextInstruction(hp3,hp3) and
  11137. MatchInstruction(hp3,A_RET,[S_NO])
  11138. )
  11139. ) and
  11140. (taicpu(hp3).ops=0) then
  11141. begin
  11142. taicpu(hp1).opcode := A_JMP;
  11143. taicpu(hp1).is_jmp := true;
  11144. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11145. RemoveCurrentP(p, hp4);
  11146. RemoveInstruction(hp2);
  11147. RemoveInstruction(hp3);
  11148. if Assigned(hp5) then
  11149. begin
  11150. AsmL.Remove(hp5);
  11151. ASmL.InsertBefore(hp5,hp1)
  11152. end;
  11153. Result:=true;
  11154. end;
  11155. end;
  11156. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11157. {$ifdef x86_64}
  11158. var
  11159. hp1, hp2, hp3, hp4, hp5: tai;
  11160. {$endif x86_64}
  11161. begin
  11162. Result:=false;
  11163. {$ifdef x86_64}
  11164. hp5:=nil;
  11165. { replace
  11166. push %rax
  11167. call procname
  11168. pop %rcx
  11169. ret
  11170. by
  11171. jmp procname
  11172. but do it only on level 4 because it destroys stack back traces
  11173. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11174. for all supported calling conventions
  11175. }
  11176. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11177. MatchOpType(taicpu(p),top_reg) and
  11178. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11179. GetNextInstruction(p, hp1) and
  11180. { Take a copy of hp1 }
  11181. SetAndTest(hp1, hp4) and
  11182. { trick to skip label }
  11183. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11184. SkipSimpleInstructions(hp1) and
  11185. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11186. GetNextInstruction(hp1, hp2) and
  11187. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11188. MatchOpType(taicpu(hp2),top_reg) and
  11189. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11190. GetNextInstruction(hp2, hp3) and
  11191. { trick to skip label }
  11192. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11193. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11194. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11195. SetAndTest(hp3,hp5) and
  11196. GetNextInstruction(hp3,hp3) and
  11197. MatchInstruction(hp3,A_RET,[S_NO])
  11198. )
  11199. ) and
  11200. (taicpu(hp3).ops=0) then
  11201. begin
  11202. taicpu(hp1).opcode := A_JMP;
  11203. taicpu(hp1).is_jmp := true;
  11204. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11205. RemoveCurrentP(p, hp4);
  11206. RemoveInstruction(hp2);
  11207. RemoveInstruction(hp3);
  11208. if Assigned(hp5) then
  11209. begin
  11210. AsmL.Remove(hp5);
  11211. ASmL.InsertBefore(hp5,hp1)
  11212. end;
  11213. Result:=true;
  11214. end;
  11215. {$endif x86_64}
  11216. end;
  11217. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11218. var
  11219. Value, RegName: string;
  11220. begin
  11221. Result:=false;
  11222. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11223. begin
  11224. case taicpu(p).oper[0]^.val of
  11225. 0:
  11226. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11227. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11228. begin
  11229. { change "mov $0,%reg" into "xor %reg,%reg" }
  11230. taicpu(p).opcode := A_XOR;
  11231. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11232. Result := True;
  11233. {$ifdef x86_64}
  11234. end
  11235. else if (taicpu(p).opsize = S_Q) then
  11236. begin
  11237. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11238. { The actual optimization }
  11239. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11240. taicpu(p).changeopsize(S_L);
  11241. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11242. Result := True;
  11243. end;
  11244. $1..$FFFFFFFF:
  11245. begin
  11246. { Code size reduction by J. Gareth "Kit" Moreton }
  11247. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11248. case taicpu(p).opsize of
  11249. S_Q:
  11250. begin
  11251. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11252. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11253. { The actual optimization }
  11254. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11255. taicpu(p).changeopsize(S_L);
  11256. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11257. Result := True;
  11258. end;
  11259. else
  11260. { Do nothing };
  11261. end;
  11262. {$endif x86_64}
  11263. end;
  11264. -1:
  11265. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11266. if (cs_opt_size in current_settings.optimizerswitches) and
  11267. (taicpu(p).opsize <> S_B) and
  11268. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11269. begin
  11270. { change "mov $-1,%reg" into "or $-1,%reg" }
  11271. { NOTES:
  11272. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11273. - This operation creates a false dependency on the register, so only do it when optimising for size
  11274. - 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
  11275. }
  11276. taicpu(p).opcode := A_OR;
  11277. Result := True;
  11278. end;
  11279. else
  11280. { Do nothing };
  11281. end;
  11282. end;
  11283. end;
  11284. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11285. var
  11286. hp1: tai;
  11287. begin
  11288. { Detect:
  11289. andw x, %ax (0 <= x < $8000)
  11290. ...
  11291. movzwl %ax,%eax
  11292. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11293. }
  11294. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11295. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11296. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11297. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11298. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11299. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11300. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11301. begin
  11302. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11303. taicpu(hp1).opcode := A_CWDE;
  11304. taicpu(hp1).clearop(0);
  11305. taicpu(hp1).clearop(1);
  11306. taicpu(hp1).ops := 0;
  11307. { A change was made, but not with p, so move forward 1 }
  11308. p := tai(p.Next);
  11309. Result := True;
  11310. end;
  11311. end;
  11312. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11313. begin
  11314. Result := False;
  11315. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11316. Exit;
  11317. { Convert:
  11318. movswl %ax,%eax -> cwtl
  11319. movslq %eax,%rax -> cdqe
  11320. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11321. refer to the same opcode and depends only on the assembler's
  11322. current operand-size attribute. [Kit]
  11323. }
  11324. with taicpu(p) do
  11325. case opsize of
  11326. S_WL:
  11327. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11328. begin
  11329. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11330. opcode := A_CWDE;
  11331. clearop(0);
  11332. clearop(1);
  11333. ops := 0;
  11334. Result := True;
  11335. end;
  11336. {$ifdef x86_64}
  11337. S_LQ:
  11338. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11339. begin
  11340. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11341. opcode := A_CDQE;
  11342. clearop(0);
  11343. clearop(1);
  11344. ops := 0;
  11345. Result := True;
  11346. end;
  11347. {$endif x86_64}
  11348. else
  11349. ;
  11350. end;
  11351. end;
  11352. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11353. var
  11354. hp1: tai;
  11355. begin
  11356. { Detect:
  11357. shr x, %ax (x > 0)
  11358. ...
  11359. movzwl %ax,%eax
  11360. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11361. }
  11362. Result := False;
  11363. if MatchOpType(taicpu(p), top_const, top_reg) and
  11364. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11365. (taicpu(p).oper[0]^.val > 0) and
  11366. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11367. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11368. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11369. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11370. begin
  11371. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11372. taicpu(hp1).opcode := A_CWDE;
  11373. taicpu(hp1).clearop(0);
  11374. taicpu(hp1).clearop(1);
  11375. taicpu(hp1).ops := 0;
  11376. { A change was made, but not with p, so move forward 1 }
  11377. p := tai(p.Next);
  11378. Result := True;
  11379. end;
  11380. end;
  11381. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11382. var
  11383. hp1, hp2: tai;
  11384. Opposite, SecondOpposite: TAsmOp;
  11385. NewCond: TAsmCond;
  11386. begin
  11387. Result := False;
  11388. { Change:
  11389. add/sub 128,(dest)
  11390. To:
  11391. sub/add -128,(dest)
  11392. This generaally takes fewer bytes to encode because -128 can be stored
  11393. in a signed byte, whereas +128 cannot.
  11394. }
  11395. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11396. begin
  11397. if taicpu(p).opcode = A_ADD then
  11398. Opposite := A_SUB
  11399. else
  11400. Opposite := A_ADD;
  11401. { Be careful if the flags are in use, because the CF flag inverts
  11402. when changing from ADD to SUB and vice versa }
  11403. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11404. GetNextInstruction(p, hp1) then
  11405. begin
  11406. TransferUsedRegs(TmpUsedRegs);
  11407. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11408. hp2 := hp1;
  11409. { Scan ahead to check if everything's safe }
  11410. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11411. begin
  11412. if (hp1.typ <> ait_instruction) then
  11413. { Probably unsafe since the flags are still in use }
  11414. Exit;
  11415. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11416. { Stop searching at an unconditional jump }
  11417. Break;
  11418. if not
  11419. (
  11420. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11421. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11422. ) and
  11423. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11424. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11425. Exit;
  11426. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11427. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11428. { Move to the next instruction }
  11429. GetNextInstruction(hp1, hp1);
  11430. end;
  11431. while Assigned(hp2) and (hp2 <> hp1) do
  11432. begin
  11433. NewCond := C_None;
  11434. case taicpu(hp2).condition of
  11435. C_A, C_NBE:
  11436. NewCond := C_BE;
  11437. C_B, C_C, C_NAE:
  11438. NewCond := C_AE;
  11439. C_AE, C_NB, C_NC:
  11440. NewCond := C_B;
  11441. C_BE, C_NA:
  11442. NewCond := C_A;
  11443. else
  11444. { No change needed };
  11445. end;
  11446. if NewCond <> C_None then
  11447. begin
  11448. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11449. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11450. taicpu(hp2).condition := NewCond;
  11451. end
  11452. else
  11453. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11454. begin
  11455. { Because of the flipping of the carry bit, to ensure
  11456. the operation remains equivalent, ADC becomes SBB
  11457. and vice versa, and the constant is not-inverted.
  11458. If multiple ADCs or SBBs appear in a row, each one
  11459. changed causes the carry bit to invert, so they all
  11460. need to be flipped }
  11461. if taicpu(hp2).opcode = A_ADC then
  11462. SecondOpposite := A_SBB
  11463. else
  11464. SecondOpposite := A_ADC;
  11465. if taicpu(hp2).oper[0]^.typ <> top_const then
  11466. { Should have broken out of this optimisation already }
  11467. InternalError(2021112901);
  11468. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  11469. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  11470. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11471. taicpu(hp2).opcode := SecondOpposite;
  11472. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11473. end;
  11474. { Move to the next instruction }
  11475. GetNextInstruction(hp2, hp2);
  11476. end;
  11477. if (hp2 <> hp1) then
  11478. InternalError(2021111501);
  11479. end;
  11480. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11481. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11482. taicpu(p).opcode := Opposite;
  11483. taicpu(p).oper[0]^.val := -128;
  11484. { No further optimisations can be made on this instruction, so move
  11485. onto the next one to save time }
  11486. p := tai(p.Next);
  11487. UpdateUsedRegs(p);
  11488. Result := True;
  11489. Exit;
  11490. end;
  11491. { Detect:
  11492. add/sub %reg2,(dest)
  11493. add/sub x, (dest)
  11494. (dest can be a register or a reference)
  11495. Swap the instructions to minimise a pipeline stall. This reverses the
  11496. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11497. optimisations could be made.
  11498. }
  11499. if (taicpu(p).oper[0]^.typ = top_reg) and
  11500. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11501. (
  11502. (
  11503. (taicpu(p).oper[1]^.typ = top_reg) and
  11504. { We can try searching further ahead if we're writing to a register }
  11505. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11506. ) or
  11507. (
  11508. (taicpu(p).oper[1]^.typ = top_ref) and
  11509. GetNextInstruction(p, hp1)
  11510. )
  11511. ) and
  11512. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11513. (taicpu(hp1).oper[0]^.typ = top_const) and
  11514. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11515. begin
  11516. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11517. TransferUsedRegs(TmpUsedRegs);
  11518. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11519. hp2 := p;
  11520. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11521. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11522. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11523. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11524. begin
  11525. asml.remove(hp1);
  11526. asml.InsertBefore(hp1, p);
  11527. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11528. Result := True;
  11529. end;
  11530. end;
  11531. end;
  11532. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11533. begin
  11534. Result:=false;
  11535. { change "cmp $0, %reg" to "test %reg, %reg" }
  11536. if MatchOpType(taicpu(p),top_const,top_reg) and
  11537. (taicpu(p).oper[0]^.val = 0) then
  11538. begin
  11539. taicpu(p).opcode := A_TEST;
  11540. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11541. Result:=true;
  11542. end;
  11543. end;
  11544. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11545. var
  11546. IsTestConstX : Boolean;
  11547. hp1,hp2 : tai;
  11548. begin
  11549. Result:=false;
  11550. { removes the line marked with (x) from the sequence
  11551. and/or/xor/add/sub/... $x, %y
  11552. test/or %y, %y | test $-1, %y (x)
  11553. j(n)z _Label
  11554. as the first instruction already adjusts the ZF
  11555. %y operand may also be a reference }
  11556. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11557. MatchOperand(taicpu(p).oper[0]^,-1);
  11558. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11559. GetLastInstruction(p, hp1) and
  11560. (tai(hp1).typ = ait_instruction) and
  11561. GetNextInstruction(p,hp2) and
  11562. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11563. case taicpu(hp1).opcode Of
  11564. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11565. { These two instructions set the zero flag if the result is zero }
  11566. A_POPCNT, A_LZCNT:
  11567. begin
  11568. if (
  11569. { With POPCNT, an input of zero will set the zero flag
  11570. because the population count of zero is zero }
  11571. (taicpu(hp1).opcode = A_POPCNT) and
  11572. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11573. (
  11574. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11575. { Faster than going through the second half of the 'or'
  11576. condition below }
  11577. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11578. )
  11579. ) or (
  11580. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11581. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11582. { and in case of carry for A(E)/B(E)/C/NC }
  11583. (
  11584. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11585. (
  11586. (taicpu(hp1).opcode <> A_ADD) and
  11587. (taicpu(hp1).opcode <> A_SUB) and
  11588. (taicpu(hp1).opcode <> A_LZCNT)
  11589. )
  11590. )
  11591. ) then
  11592. begin
  11593. RemoveCurrentP(p, hp2);
  11594. Result:=true;
  11595. Exit;
  11596. end;
  11597. end;
  11598. A_SHL, A_SAL, A_SHR, A_SAR:
  11599. begin
  11600. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11601. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11602. { therefore, it's only safe to do this optimization for }
  11603. { shifts by a (nonzero) constant }
  11604. (taicpu(hp1).oper[0]^.typ = top_const) and
  11605. (taicpu(hp1).oper[0]^.val <> 0) and
  11606. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11607. { and in case of carry for A(E)/B(E)/C/NC }
  11608. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11609. begin
  11610. RemoveCurrentP(p, hp2);
  11611. Result:=true;
  11612. Exit;
  11613. end;
  11614. end;
  11615. A_DEC, A_INC, A_NEG:
  11616. begin
  11617. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11618. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11619. { and in case of carry for A(E)/B(E)/C/NC }
  11620. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11621. begin
  11622. RemoveCurrentP(p, hp2);
  11623. Result:=true;
  11624. Exit;
  11625. end;
  11626. end
  11627. else
  11628. ;
  11629. end; { case }
  11630. { change "test $-1,%reg" into "test %reg,%reg" }
  11631. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11632. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11633. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11634. if MatchInstruction(p, A_OR, []) and
  11635. { Can only match if they're both registers }
  11636. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11637. begin
  11638. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11639. taicpu(p).opcode := A_TEST;
  11640. { No need to set Result to True, as we've done all the optimisations we can }
  11641. end;
  11642. end;
  11643. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11644. var
  11645. hp1,hp3 : tai;
  11646. {$ifndef x86_64}
  11647. hp2 : taicpu;
  11648. {$endif x86_64}
  11649. begin
  11650. Result:=false;
  11651. hp3:=nil;
  11652. {$ifndef x86_64}
  11653. { don't do this on modern CPUs, this really hurts them due to
  11654. broken call/ret pairing }
  11655. if (current_settings.optimizecputype < cpu_Pentium2) and
  11656. not(cs_create_pic in current_settings.moduleswitches) and
  11657. GetNextInstruction(p, hp1) and
  11658. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11659. MatchOpType(taicpu(hp1),top_ref) and
  11660. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11661. begin
  11662. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11663. InsertLLItem(p.previous, p, hp2);
  11664. taicpu(p).opcode := A_JMP;
  11665. taicpu(p).is_jmp := true;
  11666. RemoveInstruction(hp1);
  11667. Result:=true;
  11668. end
  11669. else
  11670. {$endif x86_64}
  11671. { replace
  11672. call procname
  11673. ret
  11674. by
  11675. jmp procname
  11676. but do it only on level 4 because it destroys stack back traces
  11677. else if the subroutine is marked as no return, remove the ret
  11678. }
  11679. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11680. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11681. GetNextInstruction(p, hp1) and
  11682. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11683. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11684. SetAndTest(hp1,hp3) and
  11685. GetNextInstruction(hp1,hp1) and
  11686. MatchInstruction(hp1,A_RET,[S_NO])
  11687. )
  11688. ) and
  11689. (taicpu(hp1).ops=0) then
  11690. begin
  11691. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11692. { we might destroy stack alignment here if we do not do a call }
  11693. (target_info.stackalign<=sizeof(SizeUInt)) then
  11694. begin
  11695. taicpu(p).opcode := A_JMP;
  11696. taicpu(p).is_jmp := true;
  11697. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11698. end
  11699. else
  11700. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11701. RemoveInstruction(hp1);
  11702. if Assigned(hp3) then
  11703. begin
  11704. AsmL.Remove(hp3);
  11705. AsmL.InsertBefore(hp3,p)
  11706. end;
  11707. Result:=true;
  11708. end;
  11709. end;
  11710. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11711. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11712. begin
  11713. case OpSize of
  11714. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11715. Result := (Val <= $FF) and (Val >= -128);
  11716. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11717. Result := (Val <= $FFFF) and (Val >= -32768);
  11718. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11719. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11720. else
  11721. Result := True;
  11722. end;
  11723. end;
  11724. var
  11725. hp1, hp2 : tai;
  11726. SizeChange: Boolean;
  11727. PreMessage: string;
  11728. begin
  11729. Result := False;
  11730. if (taicpu(p).oper[0]^.typ = top_reg) and
  11731. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11732. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11733. begin
  11734. { Change (using movzbl %al,%eax as an example):
  11735. movzbl %al, %eax movzbl %al, %eax
  11736. cmpl x, %eax testl %eax,%eax
  11737. To:
  11738. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11739. movzbl %al, %eax movzbl %al, %eax
  11740. Smaller instruction and minimises pipeline stall as the CPU
  11741. doesn't have to wait for the register to get zero-extended. [Kit]
  11742. Also allow if the smaller of the two registers is being checked,
  11743. as this still removes the false dependency.
  11744. }
  11745. if
  11746. (
  11747. (
  11748. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11749. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11750. ) or (
  11751. { If MatchOperand returns True, they must both be registers }
  11752. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11753. )
  11754. ) and
  11755. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11756. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11757. begin
  11758. 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);
  11759. asml.Remove(hp1);
  11760. asml.InsertBefore(hp1, p);
  11761. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11762. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11763. begin
  11764. taicpu(hp1).opcode := A_TEST;
  11765. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11766. end;
  11767. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11768. case taicpu(p).opsize of
  11769. S_BW, S_BL:
  11770. begin
  11771. SizeChange := taicpu(hp1).opsize <> S_B;
  11772. taicpu(hp1).changeopsize(S_B);
  11773. end;
  11774. S_WL:
  11775. begin
  11776. SizeChange := taicpu(hp1).opsize <> S_W;
  11777. taicpu(hp1).changeopsize(S_W);
  11778. end
  11779. else
  11780. InternalError(2020112701);
  11781. end;
  11782. UpdateUsedRegs(tai(p.Next));
  11783. { Check if the register is used aferwards - if not, we can
  11784. remove the movzx instruction completely }
  11785. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11786. begin
  11787. { Hp1 is a better position than p for debugging purposes }
  11788. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11789. RemoveCurrentp(p, hp1);
  11790. Result := True;
  11791. end;
  11792. if SizeChange then
  11793. DebugMsg(SPeepholeOptimization + PreMessage +
  11794. 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)
  11795. else
  11796. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11797. Exit;
  11798. end;
  11799. { Change (using movzwl %ax,%eax as an example):
  11800. movzwl %ax, %eax
  11801. movb %al, (dest) (Register is smaller than read register in movz)
  11802. To:
  11803. movb %al, (dest) (Move one back to avoid a false dependency)
  11804. movzwl %ax, %eax
  11805. }
  11806. if (taicpu(hp1).opcode = A_MOV) and
  11807. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11808. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11809. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11810. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11811. begin
  11812. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11813. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11814. asml.Remove(hp1);
  11815. asml.InsertBefore(hp1, p);
  11816. if taicpu(hp1).oper[1]^.typ = top_reg then
  11817. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11818. { Check if the register is used aferwards - if not, we can
  11819. remove the movzx instruction completely }
  11820. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11821. begin
  11822. { Hp1 is a better position than p for debugging purposes }
  11823. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11824. RemoveCurrentp(p, hp1);
  11825. Result := True;
  11826. end;
  11827. Exit;
  11828. end;
  11829. end;
  11830. end;
  11831. {$ifdef x86_64}
  11832. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11833. var
  11834. PreMessage, RegName: string;
  11835. begin
  11836. { Code size reduction by J. Gareth "Kit" Moreton }
  11837. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11838. as this removes the REX prefix }
  11839. Result := False;
  11840. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11841. Exit;
  11842. if taicpu(p).oper[0]^.typ <> top_reg then
  11843. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11844. InternalError(2018011500);
  11845. case taicpu(p).opsize of
  11846. S_Q:
  11847. begin
  11848. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11849. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11850. { The actual optimization }
  11851. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11852. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11853. taicpu(p).changeopsize(S_L);
  11854. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11855. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11856. end;
  11857. else
  11858. ;
  11859. end;
  11860. end;
  11861. {$endif}
  11862. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11863. var
  11864. XReg: TRegister;
  11865. begin
  11866. Result := False;
  11867. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11868. Smaller encoding and slightly faster on some platforms (also works for
  11869. ZMM-sized registers) }
  11870. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11871. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11872. begin
  11873. XReg := taicpu(p).oper[0]^.reg;
  11874. if (taicpu(p).oper[1]^.reg = XReg) then
  11875. begin
  11876. taicpu(p).changeopsize(S_XMM);
  11877. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11878. if (cs_opt_size in current_settings.optimizerswitches) then
  11879. begin
  11880. { Change input registers to %xmm0 to reduce size. Note that
  11881. there's a risk of a false dependency doing this, so only
  11882. optimise for size here }
  11883. XReg := NR_XMM0;
  11884. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11885. end
  11886. else
  11887. begin
  11888. setsubreg(XReg, R_SUBMMX);
  11889. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11890. end;
  11891. taicpu(p).oper[0]^.reg := XReg;
  11892. taicpu(p).oper[1]^.reg := XReg;
  11893. Result := True;
  11894. end;
  11895. end;
  11896. end;
  11897. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11898. var
  11899. OperIdx: Integer;
  11900. begin
  11901. for OperIdx := 0 to p.ops - 1 do
  11902. if p.oper[OperIdx]^.typ = top_ref then
  11903. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11904. end;
  11905. end.