aoptx86.pas 563 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  108. function PrePeepholeOptSxx(var p : tai) : boolean;
  109. function PrePeepholeOptIMUL(var p : tai) : boolean;
  110. function PrePeepholeOptAND(var p : tai) : boolean;
  111. function OptPass1Test(var p: tai): boolean;
  112. function OptPass1Add(var p: tai): boolean;
  113. function OptPass1AND(var p : tai) : boolean;
  114. function OptPass1_V_MOVAP(var p : tai) : boolean;
  115. function OptPass1VOP(var p : tai) : boolean;
  116. function OptPass1MOV(var p : tai) : boolean;
  117. function OptPass1Movx(var p : tai) : boolean;
  118. function OptPass1MOVXX(var p : tai) : boolean;
  119. function OptPass1OP(var p : tai) : boolean;
  120. function OptPass1LEA(var p : tai) : boolean;
  121. function OptPass1Sub(var p : tai) : boolean;
  122. function OptPass1SHLSAL(var p : tai) : boolean;
  123. function OptPass1FSTP(var p : tai) : boolean;
  124. function OptPass1FLD(var p : tai) : boolean;
  125. function OptPass1Cmp(var p : tai) : boolean;
  126. function OptPass1PXor(var p : tai) : boolean;
  127. function OptPass1VPXor(var p: tai): boolean;
  128. function OptPass1Imul(var p : tai) : boolean;
  129. function OptPass1Jcc(var p : tai) : boolean;
  130. function OptPass1SHXX(var p: tai): boolean;
  131. function OptPass1VMOVDQ(var p: tai): Boolean;
  132. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  133. function OptPass2Movx(var p : tai): Boolean;
  134. function OptPass2MOV(var p : tai) : boolean;
  135. function OptPass2Imul(var p : tai) : boolean;
  136. function OptPass2Jmp(var p : tai) : boolean;
  137. function OptPass2Jcc(var p : tai) : boolean;
  138. function OptPass2Lea(var p: tai): Boolean;
  139. function OptPass2SUB(var p: tai): Boolean;
  140. function OptPass2ADD(var p : tai): Boolean;
  141. function OptPass2SETcc(var p : tai) : boolean;
  142. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  143. function PostPeepholeOptMov(var p : tai) : Boolean;
  144. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  145. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  146. function PostPeepholeOptXor(var p : tai) : Boolean;
  147. {$endif x86_64}
  148. function PostPeepholeOptAnd(var p : tai) : boolean;
  149. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  150. function PostPeepholeOptCmp(var p : tai) : Boolean;
  151. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  152. function PostPeepholeOptCall(var p : tai) : Boolean;
  153. function PostPeepholeOptLea(var p : tai) : Boolean;
  154. function PostPeepholeOptPush(var p: tai): Boolean;
  155. function PostPeepholeOptShr(var p : tai) : boolean;
  156. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  157. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  158. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  159. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  160. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  161. { Processor-dependent reference optimisation }
  162. class procedure OptimizeRefs(var p: taicpu); static;
  163. end;
  164. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  168. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  169. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  170. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  171. {$if max_operands>2}
  172. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  173. {$endif max_operands>2}
  174. function RefsEqual(const r1, r2: treference): boolean;
  175. { Note that Result is set to True if the references COULD overlap but the
  176. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  177. might still overlap because %reg2 could be equal to %reg1-4 }
  178. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  179. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  180. { returns true, if ref is a reference using only the registers passed as base and index
  181. and having an offset }
  182. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  183. implementation
  184. uses
  185. cutils,verbose,
  186. systems,
  187. globals,
  188. cpuinfo,
  189. procinfo,
  190. paramgr,
  191. aasmbase,
  192. aoptbase,aoptutils,
  193. symconst,symsym,
  194. cgx86,
  195. itcpugas;
  196. {$ifdef DEBUG_AOPTCPU}
  197. const
  198. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  199. {$else DEBUG_AOPTCPU}
  200. { Empty strings help the optimizer to remove string concatenations that won't
  201. ever appear to the user on release builds. [Kit] }
  202. const
  203. SPeepholeOptimization = '';
  204. {$endif DEBUG_AOPTCPU}
  205. LIST_STEP_SIZE = 4;
  206. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  207. begin
  208. result :=
  209. (instr.typ = ait_instruction) and
  210. (taicpu(instr).opcode = op) and
  211. ((opsize = []) or (taicpu(instr).opsize in opsize));
  212. end;
  213. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  214. begin
  215. result :=
  216. (instr.typ = ait_instruction) and
  217. ((taicpu(instr).opcode = op1) or
  218. (taicpu(instr).opcode = op2)
  219. ) and
  220. ((opsize = []) or (taicpu(instr).opsize in opsize));
  221. end;
  222. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  223. begin
  224. result :=
  225. (instr.typ = ait_instruction) and
  226. ((taicpu(instr).opcode = op1) or
  227. (taicpu(instr).opcode = op2) or
  228. (taicpu(instr).opcode = op3)
  229. ) and
  230. ((opsize = []) or (taicpu(instr).opsize in opsize));
  231. end;
  232. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  233. const opsize : topsizes) : boolean;
  234. var
  235. op : TAsmOp;
  236. begin
  237. result:=false;
  238. if (instr.typ <> ait_instruction) or
  239. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  240. exit;
  241. for op in ops do
  242. begin
  243. if taicpu(instr).opcode = op then
  244. begin
  245. result:=true;
  246. exit;
  247. end;
  248. end;
  249. end;
  250. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  251. begin
  252. result := (oper.typ = top_reg) and (oper.reg = reg);
  253. end;
  254. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  255. begin
  256. result := (oper.typ = top_const) and (oper.val = a);
  257. end;
  258. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  259. begin
  260. result := oper1.typ = oper2.typ;
  261. if result then
  262. case oper1.typ of
  263. top_const:
  264. Result:=oper1.val = oper2.val;
  265. top_reg:
  266. Result:=oper1.reg = oper2.reg;
  267. top_ref:
  268. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  269. else
  270. internalerror(2013102801);
  271. end
  272. end;
  273. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  274. begin
  275. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  276. if result then
  277. case oper1.typ of
  278. top_const:
  279. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  280. top_reg:
  281. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  282. top_ref:
  283. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  284. else
  285. internalerror(2020052401);
  286. end
  287. end;
  288. function RefsEqual(const r1, r2: treference): boolean;
  289. begin
  290. RefsEqual :=
  291. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  292. (r1.relsymbol = r2.relsymbol) and
  293. (r1.segment = r2.segment) and (r1.base = r2.base) and
  294. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  295. (r1.offset = r2.offset) and
  296. (r1.volatility + r2.volatility = []);
  297. end;
  298. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  299. begin
  300. if (r1.symbol<>r2.symbol) then
  301. { If the index registers are different, there's a chance one could
  302. be set so it equals the other symbol }
  303. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  304. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  305. (r1.relsymbol = r2.relsymbol) and
  306. (r1.segment = r2.segment) and (r1.base = r2.base) and
  307. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  308. (r1.volatility + r2.volatility = []) then
  309. { In this case, it all depends on the offsets }
  310. Exit(abs(r1.offset - r2.offset) < Range);
  311. { There's a chance things MIGHT overlap, so take no chances }
  312. Result := True;
  313. end;
  314. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  315. begin
  316. Result:=(ref.offset=0) and
  317. (ref.scalefactor in [0,1]) and
  318. (ref.segment=NR_NO) and
  319. (ref.symbol=nil) and
  320. (ref.relsymbol=nil) and
  321. ((base=NR_INVALID) or
  322. (ref.base=base)) and
  323. ((index=NR_INVALID) or
  324. (ref.index=index)) and
  325. (ref.volatility=[]);
  326. end;
  327. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  328. begin
  329. Result:=(ref.scalefactor in [0,1]) and
  330. (ref.segment=NR_NO) and
  331. (ref.symbol=nil) and
  332. (ref.relsymbol=nil) and
  333. ((base=NR_INVALID) or
  334. (ref.base=base)) and
  335. ((index=NR_INVALID) or
  336. (ref.index=index)) and
  337. (ref.volatility=[]);
  338. end;
  339. function InstrReadsFlags(p: tai): boolean;
  340. begin
  341. InstrReadsFlags := true;
  342. case p.typ of
  343. ait_instruction:
  344. if InsProp[taicpu(p).opcode].Ch*
  345. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  346. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  347. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  348. exit;
  349. ait_label:
  350. exit;
  351. else
  352. ;
  353. end;
  354. InstrReadsFlags := false;
  355. end;
  356. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  357. begin
  358. Next:=Current;
  359. repeat
  360. Result:=GetNextInstruction(Next,Next);
  361. until not (Result) or
  362. not(cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ<>ait_instruction) or
  364. RegInInstruction(reg,Next) or
  365. is_calljmp(taicpu(Next).opcode);
  366. end;
  367. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  368. begin
  369. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  370. Next := Current;
  371. repeat
  372. Result := GetNextInstruction(Next,Next);
  373. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  374. if is_calljmpuncondret(taicpu(Next).opcode) then
  375. begin
  376. Result := False;
  377. Exit;
  378. end
  379. else
  380. CrossJump := True;
  381. until not Result or
  382. not (cs_opt_level3 in current_settings.optimizerswitches) or
  383. (Next.typ <> ait_instruction) or
  384. RegInInstruction(reg,Next);
  385. end;
  386. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  387. begin
  388. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  389. begin
  390. Result:=GetNextInstruction(Current,Next);
  391. exit;
  392. end;
  393. Next:=tai(Current.Next);
  394. Result:=false;
  395. while assigned(Next) do
  396. begin
  397. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  398. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  399. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  400. exit
  401. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  402. begin
  403. Result:=true;
  404. exit;
  405. end;
  406. Next:=tai(Next.Next);
  407. end;
  408. end;
  409. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  410. begin
  411. Result:=RegReadByInstruction(reg,hp);
  412. end;
  413. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  414. var
  415. p: taicpu;
  416. opcount: longint;
  417. begin
  418. RegReadByInstruction := false;
  419. if hp.typ <> ait_instruction then
  420. exit;
  421. p := taicpu(hp);
  422. case p.opcode of
  423. A_CALL:
  424. regreadbyinstruction := true;
  425. A_IMUL:
  426. case p.ops of
  427. 1:
  428. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  429. (
  430. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  431. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  432. );
  433. 2,3:
  434. regReadByInstruction :=
  435. reginop(reg,p.oper[0]^) or
  436. reginop(reg,p.oper[1]^);
  437. else
  438. InternalError(2019112801);
  439. end;
  440. A_MUL:
  441. begin
  442. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  443. (
  444. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  445. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  446. );
  447. end;
  448. A_IDIV,A_DIV:
  449. begin
  450. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  451. (
  452. (getregtype(reg)=R_INTREGISTER) and
  453. (
  454. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  455. )
  456. );
  457. end;
  458. else
  459. begin
  460. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  461. begin
  462. RegReadByInstruction := false;
  463. exit;
  464. end;
  465. for opcount := 0 to p.ops-1 do
  466. if (p.oper[opCount]^.typ = top_ref) and
  467. RegInRef(reg,p.oper[opcount]^.ref^) then
  468. begin
  469. RegReadByInstruction := true;
  470. exit
  471. end;
  472. { special handling for SSE MOVSD }
  473. if (p.opcode=A_MOVSD) and (p.ops>0) then
  474. begin
  475. if p.ops<>2 then
  476. internalerror(2017042702);
  477. regReadByInstruction := reginop(reg,p.oper[0]^) or
  478. (
  479. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  480. );
  481. exit;
  482. end;
  483. with insprop[p.opcode] do
  484. begin
  485. case getregtype(reg) of
  486. R_INTREGISTER:
  487. begin
  488. case getsupreg(reg) of
  489. RS_EAX:
  490. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  491. begin
  492. RegReadByInstruction := true;
  493. exit
  494. end;
  495. RS_ECX:
  496. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  497. begin
  498. RegReadByInstruction := true;
  499. exit
  500. end;
  501. RS_EDX:
  502. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  503. begin
  504. RegReadByInstruction := true;
  505. exit
  506. end;
  507. RS_EBX:
  508. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  509. begin
  510. RegReadByInstruction := true;
  511. exit
  512. end;
  513. RS_ESP:
  514. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  515. begin
  516. RegReadByInstruction := true;
  517. exit
  518. end;
  519. RS_EBP:
  520. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  521. begin
  522. RegReadByInstruction := true;
  523. exit
  524. end;
  525. RS_ESI:
  526. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  527. begin
  528. RegReadByInstruction := true;
  529. exit
  530. end;
  531. RS_EDI:
  532. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  533. begin
  534. RegReadByInstruction := true;
  535. exit
  536. end;
  537. end;
  538. end;
  539. R_MMREGISTER:
  540. begin
  541. case getsupreg(reg) of
  542. RS_XMM0:
  543. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  544. begin
  545. RegReadByInstruction := true;
  546. exit
  547. end;
  548. end;
  549. end;
  550. else
  551. ;
  552. end;
  553. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  554. begin
  555. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  556. begin
  557. case p.condition of
  558. C_A,C_NBE, { CF=0 and ZF=0 }
  559. C_BE,C_NA: { CF=1 or ZF=1 }
  560. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  561. C_AE,C_NB,C_NC, { CF=0 }
  562. C_B,C_NAE,C_C: { CF=1 }
  563. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  564. C_NE,C_NZ, { ZF=0 }
  565. C_E,C_Z: { ZF=1 }
  566. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  567. C_G,C_NLE, { ZF=0 and SF=OF }
  568. C_LE,C_NG: { ZF=1 or SF<>OF }
  569. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  570. C_GE,C_NL, { SF=OF }
  571. C_L,C_NGE: { SF<>OF }
  572. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  573. C_NO, { OF=0 }
  574. C_O: { OF=1 }
  575. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  576. C_NP,C_PO, { PF=0 }
  577. C_P,C_PE: { PF=1 }
  578. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  579. C_NS, { SF=0 }
  580. C_S: { SF=1 }
  581. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  582. else
  583. internalerror(2017042701);
  584. end;
  585. if RegReadByInstruction then
  586. exit;
  587. end;
  588. case getsubreg(reg) of
  589. R_SUBW,R_SUBD,R_SUBQ:
  590. RegReadByInstruction :=
  591. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  592. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  593. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  594. R_SUBFLAGCARRY:
  595. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  596. R_SUBFLAGPARITY:
  597. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  598. R_SUBFLAGAUXILIARY:
  599. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  600. R_SUBFLAGZERO:
  601. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  602. R_SUBFLAGSIGN:
  603. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  604. R_SUBFLAGOVERFLOW:
  605. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  606. R_SUBFLAGINTERRUPT:
  607. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  608. R_SUBFLAGDIRECTION:
  609. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  610. else
  611. internalerror(2017042601);
  612. end;
  613. exit;
  614. end;
  615. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  616. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  617. (p.oper[0]^.reg=p.oper[1]^.reg) then
  618. exit;
  619. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  620. begin
  621. RegReadByInstruction := true;
  622. exit
  623. end;
  624. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  625. begin
  626. RegReadByInstruction := true;
  627. exit
  628. end;
  629. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  630. begin
  631. RegReadByInstruction := true;
  632. exit
  633. end;
  634. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  635. begin
  636. RegReadByInstruction := true;
  637. exit
  638. end;
  639. end;
  640. end;
  641. end;
  642. end;
  643. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  644. begin
  645. result:=false;
  646. if p1.typ<>ait_instruction then
  647. exit;
  648. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  649. exit(true);
  650. if (getregtype(reg)=R_INTREGISTER) and
  651. { change information for xmm movsd are not correct }
  652. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  653. begin
  654. case getsupreg(reg) of
  655. { RS_EAX = RS_RAX on x86-64 }
  656. RS_EAX:
  657. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  658. RS_ECX:
  659. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  660. RS_EDX:
  661. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  662. RS_EBX:
  663. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  664. RS_ESP:
  665. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  666. RS_EBP:
  667. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  668. RS_ESI:
  669. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  670. RS_EDI:
  671. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  672. else
  673. ;
  674. end;
  675. if result then
  676. exit;
  677. end
  678. else if getregtype(reg)=R_MMREGISTER then
  679. begin
  680. case getsupreg(reg) of
  681. RS_XMM0:
  682. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. else
  684. ;
  685. end;
  686. if result then
  687. exit;
  688. end
  689. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  690. begin
  691. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  692. exit(true);
  693. case getsubreg(reg) of
  694. R_SUBFLAGCARRY:
  695. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  696. R_SUBFLAGPARITY:
  697. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  698. R_SUBFLAGAUXILIARY:
  699. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. R_SUBFLAGZERO:
  701. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  702. R_SUBFLAGSIGN:
  703. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  704. R_SUBFLAGOVERFLOW:
  705. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  706. R_SUBFLAGINTERRUPT:
  707. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  708. R_SUBFLAGDIRECTION:
  709. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  710. R_SUBW,R_SUBD,R_SUBQ:
  711. { Everything except the direction bits }
  712. Result:=
  713. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  714. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  715. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  716. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  717. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  718. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  719. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  720. else
  721. ;
  722. end;
  723. if result then
  724. exit;
  725. end
  726. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  727. exit(true);
  728. Result:=inherited RegInInstruction(Reg, p1);
  729. end;
  730. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  731. const
  732. WriteOps: array[0..3] of set of TInsChange =
  733. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  734. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  735. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  736. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  737. var
  738. OperIdx: Integer;
  739. begin
  740. Result := False;
  741. if p1.typ <> ait_instruction then
  742. exit;
  743. with insprop[taicpu(p1).opcode] do
  744. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  745. begin
  746. case getsubreg(reg) of
  747. R_SUBW,R_SUBD,R_SUBQ:
  748. Result :=
  749. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  750. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  751. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  752. R_SUBFLAGCARRY:
  753. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  754. R_SUBFLAGPARITY:
  755. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  756. R_SUBFLAGAUXILIARY:
  757. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  758. R_SUBFLAGZERO:
  759. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  760. R_SUBFLAGSIGN:
  761. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  762. R_SUBFLAGOVERFLOW:
  763. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  764. R_SUBFLAGINTERRUPT:
  765. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  766. R_SUBFLAGDIRECTION:
  767. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  768. else
  769. internalerror(2017042602);
  770. end;
  771. exit;
  772. end;
  773. case taicpu(p1).opcode of
  774. A_CALL:
  775. { We could potentially set Result to False if the register in
  776. question is non-volatile for the subroutine's calling convention,
  777. but this would require detecting the calling convention in use and
  778. also assuming that the routine doesn't contain malformed assembly
  779. language, for example... so it could only be done under -O4 as it
  780. would be considered a side-effect. [Kit] }
  781. Result := True;
  782. A_MOVSD:
  783. { special handling for SSE MOVSD }
  784. if (taicpu(p1).ops>0) then
  785. begin
  786. if taicpu(p1).ops<>2 then
  787. internalerror(2017042703);
  788. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  789. end;
  790. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  791. so fix it here (FK)
  792. }
  793. A_VMOVSS,
  794. A_VMOVSD:
  795. begin
  796. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  797. exit;
  798. end;
  799. A_IMUL:
  800. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  801. else
  802. ;
  803. end;
  804. if Result then
  805. exit;
  806. with insprop[taicpu(p1).opcode] do
  807. begin
  808. if getregtype(reg)=R_INTREGISTER then
  809. begin
  810. case getsupreg(reg) of
  811. RS_EAX:
  812. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  813. begin
  814. Result := True;
  815. exit
  816. end;
  817. RS_ECX:
  818. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  819. begin
  820. Result := True;
  821. exit
  822. end;
  823. RS_EDX:
  824. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  825. begin
  826. Result := True;
  827. exit
  828. end;
  829. RS_EBX:
  830. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  831. begin
  832. Result := True;
  833. exit
  834. end;
  835. RS_ESP:
  836. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  837. begin
  838. Result := True;
  839. exit
  840. end;
  841. RS_EBP:
  842. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  843. begin
  844. Result := True;
  845. exit
  846. end;
  847. RS_ESI:
  848. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  849. begin
  850. Result := True;
  851. exit
  852. end;
  853. RS_EDI:
  854. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  855. begin
  856. Result := True;
  857. exit
  858. end;
  859. end;
  860. end;
  861. for OperIdx := 0 to taicpu(p1).ops - 1 do
  862. if (WriteOps[OperIdx]*Ch<>[]) and
  863. { The register doesn't get modified inside a reference }
  864. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  865. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  866. begin
  867. Result := true;
  868. exit
  869. end;
  870. end;
  871. end;
  872. {$ifdef DEBUG_AOPTCPU}
  873. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  874. begin
  875. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  876. end;
  877. function debug_tostr(i: tcgint): string; inline;
  878. begin
  879. Result := tostr(i);
  880. end;
  881. function debug_regname(r: TRegister): string; inline;
  882. begin
  883. Result := '%' + std_regname(r);
  884. end;
  885. { Debug output function - creates a string representation of an operator }
  886. function debug_operstr(oper: TOper): string;
  887. begin
  888. case oper.typ of
  889. top_const:
  890. Result := '$' + debug_tostr(oper.val);
  891. top_reg:
  892. Result := debug_regname(oper.reg);
  893. top_ref:
  894. begin
  895. if oper.ref^.offset <> 0 then
  896. Result := debug_tostr(oper.ref^.offset) + '('
  897. else
  898. Result := '(';
  899. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  900. begin
  901. Result := Result + debug_regname(oper.ref^.base);
  902. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  903. Result := Result + ',' + debug_regname(oper.ref^.index);
  904. end
  905. else
  906. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  907. Result := Result + debug_regname(oper.ref^.index);
  908. if (oper.ref^.scalefactor > 1) then
  909. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  910. else
  911. Result := Result + ')';
  912. end;
  913. else
  914. Result := '[UNKNOWN]';
  915. end;
  916. end;
  917. function debug_op2str(opcode: tasmop): string; inline;
  918. begin
  919. Result := std_op2str[opcode];
  920. end;
  921. function debug_opsize2str(opsize: topsize): string; inline;
  922. begin
  923. Result := gas_opsize2str[opsize];
  924. end;
  925. {$else DEBUG_AOPTCPU}
  926. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  927. begin
  928. end;
  929. function debug_tostr(i: tcgint): string; inline;
  930. begin
  931. Result := '';
  932. end;
  933. function debug_regname(r: TRegister): string; inline;
  934. begin
  935. Result := '';
  936. end;
  937. function debug_operstr(oper: TOper): string; inline;
  938. begin
  939. Result := '';
  940. end;
  941. function debug_op2str(opcode: tasmop): string; inline;
  942. begin
  943. Result := '';
  944. end;
  945. function debug_opsize2str(opsize: topsize): string; inline;
  946. begin
  947. Result := '';
  948. end;
  949. {$endif DEBUG_AOPTCPU}
  950. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  951. begin
  952. {$ifdef x86_64}
  953. { Always fine on x86-64 }
  954. Result := True;
  955. {$else x86_64}
  956. Result :=
  957. {$ifdef i8086}
  958. (current_settings.cputype >= cpu_386) and
  959. {$endif i8086}
  960. (
  961. { Always accept if optimising for size }
  962. (cs_opt_size in current_settings.optimizerswitches) or
  963. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  964. (current_settings.optimizecputype >= cpu_Pentium2)
  965. );
  966. {$endif x86_64}
  967. end;
  968. { Attempts to allocate a volatile integer register for use between p and hp,
  969. using AUsedRegs for the current register usage information. Returns NR_NO
  970. if no free register could be found }
  971. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  972. var
  973. RegSet: TCPURegisterSet;
  974. CurrentSuperReg: Integer;
  975. CurrentReg: TRegister;
  976. Currentp: tai;
  977. Breakout: Boolean;
  978. begin
  979. Result := NR_NO;
  980. RegSet :=
  981. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  982. current_procinfo.saved_regs_int;
  983. for CurrentSuperReg in RegSet do
  984. begin
  985. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  986. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  987. {$if defined(i386) or defined(i8086)}
  988. { If the target size is 8-bit, make sure we can actually encode it }
  989. and (
  990. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  991. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  992. )
  993. {$endif i386 or i8086}
  994. then
  995. begin
  996. Currentp := p;
  997. Breakout := False;
  998. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  999. begin
  1000. case Currentp.typ of
  1001. ait_instruction:
  1002. begin
  1003. if RegInInstruction(CurrentReg, Currentp) then
  1004. begin
  1005. Breakout := True;
  1006. Break;
  1007. end;
  1008. { Cannot allocate across an unconditional jump }
  1009. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1010. Exit;
  1011. end;
  1012. ait_marker:
  1013. { Don't try anything more if a marker is hit }
  1014. Exit;
  1015. ait_regalloc:
  1016. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1017. begin
  1018. Breakout := True;
  1019. Break;
  1020. end;
  1021. else
  1022. ;
  1023. end;
  1024. end;
  1025. if Breakout then
  1026. { Try the next register }
  1027. Continue;
  1028. { We have a free register available }
  1029. Result := CurrentReg;
  1030. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1031. Exit;
  1032. end;
  1033. end;
  1034. end;
  1035. { Attempts to allocate a volatile MM register for use between p and hp,
  1036. using AUsedRegs for the current register usage information. Returns NR_NO
  1037. if no free register could be found }
  1038. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1039. var
  1040. RegSet: TCPURegisterSet;
  1041. CurrentSuperReg: Integer;
  1042. CurrentReg: TRegister;
  1043. Currentp: tai;
  1044. Breakout: Boolean;
  1045. begin
  1046. Result := NR_NO;
  1047. RegSet :=
  1048. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1049. current_procinfo.saved_regs_mm;
  1050. for CurrentSuperReg in RegSet do
  1051. begin
  1052. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1053. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1054. begin
  1055. Currentp := p;
  1056. Breakout := False;
  1057. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1058. begin
  1059. case Currentp.typ of
  1060. ait_instruction:
  1061. begin
  1062. if RegInInstruction(CurrentReg, Currentp) then
  1063. begin
  1064. Breakout := True;
  1065. Break;
  1066. end;
  1067. { Cannot allocate across an unconditional jump }
  1068. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1069. Exit;
  1070. end;
  1071. ait_marker:
  1072. { Don't try anything more if a marker is hit }
  1073. Exit;
  1074. ait_regalloc:
  1075. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1076. begin
  1077. Breakout := True;
  1078. Break;
  1079. end;
  1080. else
  1081. ;
  1082. end;
  1083. end;
  1084. if Breakout then
  1085. { Try the next register }
  1086. Continue;
  1087. { We have a free register available }
  1088. Result := CurrentReg;
  1089. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1090. Exit;
  1091. end;
  1092. end;
  1093. end;
  1094. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1095. begin
  1096. if not SuperRegistersEqual(reg1,reg2) then
  1097. exit(false);
  1098. if getregtype(reg1)<>R_INTREGISTER then
  1099. exit(true); {because SuperRegisterEqual is true}
  1100. case getsubreg(reg1) of
  1101. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1102. higher, it preserves the high bits, so the new value depends on
  1103. reg2's previous value. In other words, it is equivalent to doing:
  1104. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1105. R_SUBL:
  1106. exit(getsubreg(reg2)=R_SUBL);
  1107. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1108. higher, it actually does a:
  1109. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1110. R_SUBH:
  1111. exit(getsubreg(reg2)=R_SUBH);
  1112. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1113. bits of reg2:
  1114. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1115. R_SUBW:
  1116. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1117. { a write to R_SUBD always overwrites every other subregister,
  1118. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1119. R_SUBD,
  1120. R_SUBQ:
  1121. exit(true);
  1122. else
  1123. internalerror(2017042801);
  1124. end;
  1125. end;
  1126. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1127. begin
  1128. if not SuperRegistersEqual(reg1,reg2) then
  1129. exit(false);
  1130. if getregtype(reg1)<>R_INTREGISTER then
  1131. exit(true); {because SuperRegisterEqual is true}
  1132. case getsubreg(reg1) of
  1133. R_SUBL:
  1134. exit(getsubreg(reg2)<>R_SUBH);
  1135. R_SUBH:
  1136. exit(getsubreg(reg2)<>R_SUBL);
  1137. R_SUBW,
  1138. R_SUBD,
  1139. R_SUBQ:
  1140. exit(true);
  1141. else
  1142. internalerror(2017042802);
  1143. end;
  1144. end;
  1145. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1146. var
  1147. hp1 : tai;
  1148. l : TCGInt;
  1149. begin
  1150. result:=false;
  1151. { changes the code sequence
  1152. shr/sar const1, x
  1153. shl const2, x
  1154. to
  1155. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1156. if GetNextInstruction(p, hp1) and
  1157. MatchInstruction(hp1,A_SHL,[]) and
  1158. (taicpu(p).oper[0]^.typ = top_const) and
  1159. (taicpu(hp1).oper[0]^.typ = top_const) and
  1160. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1161. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1162. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1163. begin
  1164. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1165. not(cs_opt_size in current_settings.optimizerswitches) then
  1166. begin
  1167. { shr/sar const1, %reg
  1168. shl const2, %reg
  1169. with const1 > const2 }
  1170. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1171. taicpu(hp1).opcode := A_AND;
  1172. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1173. case taicpu(p).opsize Of
  1174. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1175. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1176. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1177. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1178. else
  1179. Internalerror(2017050703)
  1180. end;
  1181. end
  1182. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1183. not(cs_opt_size in current_settings.optimizerswitches) then
  1184. begin
  1185. { shr/sar const1, %reg
  1186. shl const2, %reg
  1187. with const1 < const2 }
  1188. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1189. taicpu(p).opcode := A_AND;
  1190. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1191. case taicpu(p).opsize Of
  1192. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1193. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1194. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1195. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1196. else
  1197. Internalerror(2017050702)
  1198. end;
  1199. end
  1200. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1201. begin
  1202. { shr/sar const1, %reg
  1203. shl const2, %reg
  1204. with const1 = const2 }
  1205. taicpu(p).opcode := A_AND;
  1206. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1207. case taicpu(p).opsize Of
  1208. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1209. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1210. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1211. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1212. else
  1213. Internalerror(2017050701)
  1214. end;
  1215. RemoveInstruction(hp1);
  1216. end;
  1217. end;
  1218. end;
  1219. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1220. var
  1221. opsize : topsize;
  1222. hp1 : tai;
  1223. tmpref : treference;
  1224. ShiftValue : Cardinal;
  1225. BaseValue : TCGInt;
  1226. begin
  1227. result:=false;
  1228. opsize:=taicpu(p).opsize;
  1229. { changes certain "imul const, %reg"'s to lea sequences }
  1230. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1231. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1232. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1233. if (taicpu(p).oper[0]^.val = 1) then
  1234. if (taicpu(p).ops = 2) then
  1235. { remove "imul $1, reg" }
  1236. begin
  1237. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1238. Result := RemoveCurrentP(p);
  1239. end
  1240. else
  1241. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1242. begin
  1243. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1244. InsertLLItem(p.previous, p.next, hp1);
  1245. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1246. p.free;
  1247. p := hp1;
  1248. end
  1249. else if ((taicpu(p).ops <= 2) or
  1250. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1251. not(cs_opt_size in current_settings.optimizerswitches) and
  1252. (not(GetNextInstruction(p, hp1)) or
  1253. not((tai(hp1).typ = ait_instruction) and
  1254. ((taicpu(hp1).opcode=A_Jcc) and
  1255. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1256. begin
  1257. {
  1258. imul X, reg1, reg2 to
  1259. lea (reg1,reg1,Y), reg2
  1260. shl ZZ,reg2
  1261. imul XX, reg1 to
  1262. lea (reg1,reg1,YY), reg1
  1263. shl ZZ,reg2
  1264. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1265. it does not exist as a separate optimization target in FPC though.
  1266. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1267. at most two zeros
  1268. }
  1269. reference_reset(tmpref,1,[]);
  1270. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1271. begin
  1272. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1273. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1274. TmpRef.base := taicpu(p).oper[1]^.reg;
  1275. TmpRef.index := taicpu(p).oper[1]^.reg;
  1276. if not(BaseValue in [3,5,9]) then
  1277. Internalerror(2018110101);
  1278. TmpRef.ScaleFactor := BaseValue-1;
  1279. if (taicpu(p).ops = 2) then
  1280. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1281. else
  1282. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1283. AsmL.InsertAfter(hp1,p);
  1284. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1285. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1286. RemoveCurrentP(p, hp1);
  1287. if ShiftValue>0 then
  1288. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1289. end;
  1290. end;
  1291. end;
  1292. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1293. begin
  1294. Result := False;
  1295. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1296. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1297. begin
  1298. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1299. taicpu(p).opcode := A_MOV;
  1300. Result := True;
  1301. end;
  1302. end;
  1303. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1304. var
  1305. p: taicpu absolute hp; { Implicit typecast }
  1306. i: Integer;
  1307. begin
  1308. Result := False;
  1309. if not assigned(hp) or
  1310. (hp.typ <> ait_instruction) then
  1311. Exit;
  1312. Prefetch(insprop[p.opcode]);
  1313. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1314. with insprop[p.opcode] do
  1315. begin
  1316. case getsubreg(reg) of
  1317. R_SUBW,R_SUBD,R_SUBQ:
  1318. Result:=
  1319. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1320. uncommon flags are checked first }
  1321. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1322. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1323. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1324. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1325. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1326. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1327. R_SUBFLAGCARRY:
  1328. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1329. R_SUBFLAGPARITY:
  1330. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1331. R_SUBFLAGAUXILIARY:
  1332. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1333. R_SUBFLAGZERO:
  1334. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1335. R_SUBFLAGSIGN:
  1336. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1337. R_SUBFLAGOVERFLOW:
  1338. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1339. R_SUBFLAGINTERRUPT:
  1340. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1341. R_SUBFLAGDIRECTION:
  1342. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1343. else
  1344. internalerror(2017050501);
  1345. end;
  1346. exit;
  1347. end;
  1348. { Handle special cases first }
  1349. case p.opcode of
  1350. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1351. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1352. begin
  1353. Result :=
  1354. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1355. (p.oper[1]^.typ = top_reg) and
  1356. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1357. (
  1358. (p.oper[0]^.typ = top_const) or
  1359. (
  1360. (p.oper[0]^.typ = top_reg) and
  1361. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1362. ) or (
  1363. (p.oper[0]^.typ = top_ref) and
  1364. not RegInRef(reg,p.oper[0]^.ref^)
  1365. )
  1366. );
  1367. end;
  1368. A_MUL, A_IMUL:
  1369. Result :=
  1370. (
  1371. (p.ops=3) and { IMUL only }
  1372. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1373. (
  1374. (
  1375. (p.oper[1]^.typ=top_reg) and
  1376. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1377. ) or (
  1378. (p.oper[1]^.typ=top_ref) and
  1379. not RegInRef(reg,p.oper[1]^.ref^)
  1380. )
  1381. )
  1382. ) or (
  1383. (
  1384. (p.ops=1) and
  1385. (
  1386. (
  1387. (
  1388. (p.oper[0]^.typ=top_reg) and
  1389. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1390. )
  1391. ) or (
  1392. (p.oper[0]^.typ=top_ref) and
  1393. not RegInRef(reg,p.oper[0]^.ref^)
  1394. )
  1395. ) and (
  1396. (
  1397. (p.opsize=S_B) and
  1398. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1399. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1400. ) or (
  1401. (p.opsize=S_W) and
  1402. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1403. ) or (
  1404. (p.opsize=S_L) and
  1405. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1406. {$ifdef x86_64}
  1407. ) or (
  1408. (p.opsize=S_Q) and
  1409. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1410. {$endif x86_64}
  1411. )
  1412. )
  1413. )
  1414. );
  1415. A_CBW:
  1416. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1417. {$ifndef x86_64}
  1418. A_LDS:
  1419. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1420. A_LES:
  1421. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1422. {$endif not x86_64}
  1423. A_LFS:
  1424. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1425. A_LGS:
  1426. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1427. A_LSS:
  1428. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1429. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1430. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1431. A_LODSB:
  1432. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1433. A_LODSW:
  1434. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1435. {$ifdef x86_64}
  1436. A_LODSQ:
  1437. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1438. {$endif x86_64}
  1439. A_LODSD:
  1440. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1441. A_FSTSW, A_FNSTSW:
  1442. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1443. else
  1444. begin
  1445. with insprop[p.opcode] do
  1446. begin
  1447. if (
  1448. { xor %reg,%reg etc. is classed as a new value }
  1449. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1450. MatchOpType(p, top_reg, top_reg) and
  1451. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1452. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1453. ) then
  1454. begin
  1455. Result := True;
  1456. Exit;
  1457. end;
  1458. { Make sure the entire register is overwritten }
  1459. if (getregtype(reg) = R_INTREGISTER) then
  1460. begin
  1461. if (p.ops > 0) then
  1462. begin
  1463. if RegInOp(reg, p.oper[0]^) then
  1464. begin
  1465. if (p.oper[0]^.typ = top_ref) then
  1466. begin
  1467. if RegInRef(reg, p.oper[0]^.ref^) then
  1468. begin
  1469. Result := False;
  1470. Exit;
  1471. end;
  1472. end
  1473. else if (p.oper[0]^.typ = top_reg) then
  1474. begin
  1475. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1476. begin
  1477. Result := False;
  1478. Exit;
  1479. end
  1480. else if ([Ch_WOp1]*Ch<>[]) then
  1481. begin
  1482. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1483. Result := True
  1484. else
  1485. begin
  1486. Result := False;
  1487. Exit;
  1488. end;
  1489. end;
  1490. end;
  1491. end;
  1492. if (p.ops > 1) then
  1493. begin
  1494. if RegInOp(reg, p.oper[1]^) then
  1495. begin
  1496. if (p.oper[1]^.typ = top_ref) then
  1497. begin
  1498. if RegInRef(reg, p.oper[1]^.ref^) then
  1499. begin
  1500. Result := False;
  1501. Exit;
  1502. end;
  1503. end
  1504. else if (p.oper[1]^.typ = top_reg) then
  1505. begin
  1506. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1507. begin
  1508. Result := False;
  1509. Exit;
  1510. end
  1511. else if ([Ch_WOp2]*Ch<>[]) then
  1512. begin
  1513. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1514. Result := True
  1515. else
  1516. begin
  1517. Result := False;
  1518. Exit;
  1519. end;
  1520. end;
  1521. end;
  1522. end;
  1523. if (p.ops > 2) then
  1524. begin
  1525. if RegInOp(reg, p.oper[2]^) then
  1526. begin
  1527. if (p.oper[2]^.typ = top_ref) then
  1528. begin
  1529. if RegInRef(reg, p.oper[2]^.ref^) then
  1530. begin
  1531. Result := False;
  1532. Exit;
  1533. end;
  1534. end
  1535. else if (p.oper[2]^.typ = top_reg) then
  1536. begin
  1537. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1538. begin
  1539. Result := False;
  1540. Exit;
  1541. end
  1542. else if ([Ch_WOp3]*Ch<>[]) then
  1543. begin
  1544. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1545. Result := True
  1546. else
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end;
  1551. end;
  1552. end;
  1553. end;
  1554. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1555. begin
  1556. if (p.oper[3]^.typ = top_ref) then
  1557. begin
  1558. if RegInRef(reg, p.oper[3]^.ref^) then
  1559. begin
  1560. Result := False;
  1561. Exit;
  1562. end;
  1563. end
  1564. else if (p.oper[3]^.typ = top_reg) then
  1565. begin
  1566. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1567. begin
  1568. Result := False;
  1569. Exit;
  1570. end
  1571. else if ([Ch_WOp4]*Ch<>[]) then
  1572. begin
  1573. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1574. Result := True
  1575. else
  1576. begin
  1577. Result := False;
  1578. Exit;
  1579. end;
  1580. end;
  1581. end;
  1582. end;
  1583. end;
  1584. end;
  1585. end;
  1586. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1587. case getsupreg(reg) of
  1588. RS_EAX:
  1589. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1590. begin
  1591. Result := True;
  1592. Exit;
  1593. end;
  1594. RS_ECX:
  1595. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1596. begin
  1597. Result := True;
  1598. Exit;
  1599. end;
  1600. RS_EDX:
  1601. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1602. begin
  1603. Result := True;
  1604. Exit;
  1605. end;
  1606. RS_EBX:
  1607. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1608. begin
  1609. Result := True;
  1610. Exit;
  1611. end;
  1612. RS_ESP:
  1613. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1614. begin
  1615. Result := True;
  1616. Exit;
  1617. end;
  1618. RS_EBP:
  1619. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1620. begin
  1621. Result := True;
  1622. Exit;
  1623. end;
  1624. RS_ESI:
  1625. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1626. begin
  1627. Result := True;
  1628. Exit;
  1629. end;
  1630. RS_EDI:
  1631. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1632. begin
  1633. Result := True;
  1634. Exit;
  1635. end;
  1636. else
  1637. ;
  1638. end;
  1639. end;
  1640. end;
  1641. end;
  1642. end;
  1643. end;
  1644. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1645. var
  1646. hp2,hp3 : tai;
  1647. begin
  1648. { some x86-64 issue a NOP before the real exit code }
  1649. if MatchInstruction(p,A_NOP,[]) then
  1650. GetNextInstruction(p,p);
  1651. result:=assigned(p) and (p.typ=ait_instruction) and
  1652. ((taicpu(p).opcode = A_RET) or
  1653. ((taicpu(p).opcode=A_LEAVE) and
  1654. GetNextInstruction(p,hp2) and
  1655. MatchInstruction(hp2,A_RET,[S_NO])
  1656. ) or
  1657. (((taicpu(p).opcode=A_LEA) and
  1658. MatchOpType(taicpu(p),top_ref,top_reg) and
  1659. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1660. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1661. ) and
  1662. GetNextInstruction(p,hp2) and
  1663. MatchInstruction(hp2,A_RET,[S_NO])
  1664. ) or
  1665. ((((taicpu(p).opcode=A_MOV) and
  1666. MatchOpType(taicpu(p),top_reg,top_reg) and
  1667. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1668. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1669. ((taicpu(p).opcode=A_LEA) and
  1670. MatchOpType(taicpu(p),top_ref,top_reg) and
  1671. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1672. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1673. )
  1674. ) and
  1675. GetNextInstruction(p,hp2) and
  1676. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1677. MatchOpType(taicpu(hp2),top_reg) and
  1678. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1679. GetNextInstruction(hp2,hp3) and
  1680. MatchInstruction(hp3,A_RET,[S_NO])
  1681. )
  1682. );
  1683. end;
  1684. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1685. begin
  1686. isFoldableArithOp := False;
  1687. case hp1.opcode of
  1688. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1689. isFoldableArithOp :=
  1690. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1691. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1692. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1693. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1694. (taicpu(hp1).oper[1]^.reg = reg);
  1695. A_INC,A_DEC,A_NEG,A_NOT:
  1696. isFoldableArithOp :=
  1697. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1698. (taicpu(hp1).oper[0]^.reg = reg);
  1699. else
  1700. ;
  1701. end;
  1702. end;
  1703. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1704. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1705. var
  1706. hp2: tai;
  1707. begin
  1708. hp2 := p;
  1709. repeat
  1710. hp2 := tai(hp2.previous);
  1711. if assigned(hp2) and
  1712. (hp2.typ = ait_regalloc) and
  1713. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1714. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1715. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1716. begin
  1717. RemoveInstruction(hp2);
  1718. break;
  1719. end;
  1720. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1721. end;
  1722. begin
  1723. case current_procinfo.procdef.returndef.typ of
  1724. arraydef,recorddef,pointerdef,
  1725. stringdef,enumdef,procdef,objectdef,errordef,
  1726. filedef,setdef,procvardef,
  1727. classrefdef,forwarddef:
  1728. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1729. orddef:
  1730. if current_procinfo.procdef.returndef.size <> 0 then
  1731. begin
  1732. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1733. { for int64/qword }
  1734. if current_procinfo.procdef.returndef.size = 8 then
  1735. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1736. end;
  1737. else
  1738. ;
  1739. end;
  1740. end;
  1741. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1742. var
  1743. hp1,hp2 : tai;
  1744. begin
  1745. result:=false;
  1746. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1747. begin
  1748. { vmova* reg1,reg1
  1749. =>
  1750. <nop> }
  1751. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1752. begin
  1753. RemoveCurrentP(p);
  1754. result:=true;
  1755. exit;
  1756. end
  1757. else if GetNextInstruction(p,hp1) then
  1758. begin
  1759. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1760. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1761. begin
  1762. { vmova* reg1,reg2
  1763. vmova* reg2,reg3
  1764. dealloc reg2
  1765. =>
  1766. vmova* reg1,reg3 }
  1767. TransferUsedRegs(TmpUsedRegs);
  1768. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1769. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1770. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1771. begin
  1772. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1773. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1774. RemoveInstruction(hp1);
  1775. result:=true;
  1776. exit;
  1777. end
  1778. { special case:
  1779. vmova* reg1,<op>
  1780. vmova* <op>,reg1
  1781. =>
  1782. vmova* reg1,<op> }
  1783. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1784. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1785. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1786. ) then
  1787. begin
  1788. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1789. RemoveInstruction(hp1);
  1790. result:=true;
  1791. exit;
  1792. end
  1793. end
  1794. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1795. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1796. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1797. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1798. ) and
  1799. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1800. begin
  1801. { vmova* reg1,reg2
  1802. vmovs* reg2,<op>
  1803. dealloc reg2
  1804. =>
  1805. vmovs* reg1,reg3 }
  1806. TransferUsedRegs(TmpUsedRegs);
  1807. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1808. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1809. begin
  1810. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1811. taicpu(p).opcode:=taicpu(hp1).opcode;
  1812. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1813. RemoveInstruction(hp1);
  1814. result:=true;
  1815. exit;
  1816. end
  1817. end;
  1818. end;
  1819. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1820. begin
  1821. if MatchInstruction(hp1,[A_VFMADDPD,
  1822. A_VFMADD132PD,
  1823. A_VFMADD132PS,
  1824. A_VFMADD132SD,
  1825. A_VFMADD132SS,
  1826. A_VFMADD213PD,
  1827. A_VFMADD213PS,
  1828. A_VFMADD213SD,
  1829. A_VFMADD213SS,
  1830. A_VFMADD231PD,
  1831. A_VFMADD231PS,
  1832. A_VFMADD231SD,
  1833. A_VFMADD231SS,
  1834. A_VFMADDSUB132PD,
  1835. A_VFMADDSUB132PS,
  1836. A_VFMADDSUB213PD,
  1837. A_VFMADDSUB213PS,
  1838. A_VFMADDSUB231PD,
  1839. A_VFMADDSUB231PS,
  1840. A_VFMSUB132PD,
  1841. A_VFMSUB132PS,
  1842. A_VFMSUB132SD,
  1843. A_VFMSUB132SS,
  1844. A_VFMSUB213PD,
  1845. A_VFMSUB213PS,
  1846. A_VFMSUB213SD,
  1847. A_VFMSUB213SS,
  1848. A_VFMSUB231PD,
  1849. A_VFMSUB231PS,
  1850. A_VFMSUB231SD,
  1851. A_VFMSUB231SS,
  1852. A_VFMSUBADD132PD,
  1853. A_VFMSUBADD132PS,
  1854. A_VFMSUBADD213PD,
  1855. A_VFMSUBADD213PS,
  1856. A_VFMSUBADD231PD,
  1857. A_VFMSUBADD231PS,
  1858. A_VFNMADD132PD,
  1859. A_VFNMADD132PS,
  1860. A_VFNMADD132SD,
  1861. A_VFNMADD132SS,
  1862. A_VFNMADD213PD,
  1863. A_VFNMADD213PS,
  1864. A_VFNMADD213SD,
  1865. A_VFNMADD213SS,
  1866. A_VFNMADD231PD,
  1867. A_VFNMADD231PS,
  1868. A_VFNMADD231SD,
  1869. A_VFNMADD231SS,
  1870. A_VFNMSUB132PD,
  1871. A_VFNMSUB132PS,
  1872. A_VFNMSUB132SD,
  1873. A_VFNMSUB132SS,
  1874. A_VFNMSUB213PD,
  1875. A_VFNMSUB213PS,
  1876. A_VFNMSUB213SD,
  1877. A_VFNMSUB213SS,
  1878. A_VFNMSUB231PD,
  1879. A_VFNMSUB231PS,
  1880. A_VFNMSUB231SD,
  1881. A_VFNMSUB231SS],[S_NO]) and
  1882. { we mix single and double opperations here because we assume that the compiler
  1883. generates vmovapd only after double operations and vmovaps only after single operations }
  1884. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1885. GetNextInstruction(hp1,hp2) and
  1886. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1887. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1888. begin
  1889. TransferUsedRegs(TmpUsedRegs);
  1890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1891. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1892. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1893. begin
  1894. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1895. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1896. RemoveInstruction(hp2);
  1897. end;
  1898. end
  1899. else if (hp1.typ = ait_instruction) and
  1900. GetNextInstruction(hp1, hp2) and
  1901. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1902. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1903. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1904. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1905. (((taicpu(p).opcode=A_MOVAPS) and
  1906. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1907. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1908. ((taicpu(p).opcode=A_MOVAPD) and
  1909. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1910. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1911. ) then
  1912. { change
  1913. movapX reg,reg2
  1914. addsX/subsX/... reg3, reg2
  1915. movapX reg2,reg
  1916. to
  1917. addsX/subsX/... reg3,reg
  1918. }
  1919. begin
  1920. TransferUsedRegs(TmpUsedRegs);
  1921. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1922. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1923. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1924. begin
  1925. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1926. debug_op2str(taicpu(p).opcode)+' '+
  1927. debug_op2str(taicpu(hp1).opcode)+' '+
  1928. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1929. { we cannot eliminate the first move if
  1930. the operations uses the same register for source and dest }
  1931. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1932. RemoveCurrentP(p, nil);
  1933. p:=hp1;
  1934. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1935. RemoveInstruction(hp2);
  1936. result:=true;
  1937. end;
  1938. end
  1939. else if (hp1.typ = ait_instruction) and
  1940. (((taicpu(p).opcode=A_VMOVAPD) and
  1941. (taicpu(hp1).opcode=A_VCOMISD)) or
  1942. ((taicpu(p).opcode=A_VMOVAPS) and
  1943. ((taicpu(hp1).opcode=A_VCOMISS))
  1944. )
  1945. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1946. { change
  1947. movapX reg,reg1
  1948. vcomisX reg1,reg1
  1949. to
  1950. vcomisX reg,reg
  1951. }
  1952. begin
  1953. TransferUsedRegs(TmpUsedRegs);
  1954. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1955. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1956. begin
  1957. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1958. debug_op2str(taicpu(p).opcode)+' '+
  1959. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1960. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1961. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  1962. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1963. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  1964. RemoveCurrentP(p, nil);
  1965. result:=true;
  1966. exit;
  1967. end;
  1968. end
  1969. end;
  1970. end;
  1971. end;
  1972. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1973. var
  1974. hp1 : tai;
  1975. begin
  1976. result:=false;
  1977. { replace
  1978. V<Op>X %mreg1,%mreg2,%mreg3
  1979. VMovX %mreg3,%mreg4
  1980. dealloc %mreg3
  1981. by
  1982. V<Op>X %mreg1,%mreg2,%mreg4
  1983. ?
  1984. }
  1985. if GetNextInstruction(p,hp1) and
  1986. { we mix single and double operations here because we assume that the compiler
  1987. generates vmovapd only after double operations and vmovaps only after single operations }
  1988. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1989. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1990. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1991. begin
  1992. TransferUsedRegs(TmpUsedRegs);
  1993. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1994. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1995. begin
  1996. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1997. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1998. RemoveInstruction(hp1);
  1999. result:=true;
  2000. end;
  2001. end;
  2002. end;
  2003. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2004. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2005. begin
  2006. Result := False;
  2007. { For safety reasons, only check for exact register matches }
  2008. { Check base register }
  2009. if (ref.base = AOldReg) then
  2010. begin
  2011. ref.base := ANewReg;
  2012. Result := True;
  2013. end;
  2014. { Check index register }
  2015. if (ref.index = AOldReg) then
  2016. begin
  2017. ref.index := ANewReg;
  2018. Result := True;
  2019. end;
  2020. end;
  2021. { Replaces all references to AOldReg in an operand to ANewReg }
  2022. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2023. var
  2024. OldSupReg, NewSupReg: TSuperRegister;
  2025. OldSubReg, NewSubReg: TSubRegister;
  2026. OldRegType: TRegisterType;
  2027. ThisOper: POper;
  2028. begin
  2029. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2030. Result := False;
  2031. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2032. InternalError(2020011801);
  2033. OldSupReg := getsupreg(AOldReg);
  2034. OldSubReg := getsubreg(AOldReg);
  2035. OldRegType := getregtype(AOldReg);
  2036. NewSupReg := getsupreg(ANewReg);
  2037. NewSubReg := getsubreg(ANewReg);
  2038. if OldRegType <> getregtype(ANewReg) then
  2039. InternalError(2020011802);
  2040. if OldSubReg <> NewSubReg then
  2041. InternalError(2020011803);
  2042. case ThisOper^.typ of
  2043. top_reg:
  2044. if (
  2045. (ThisOper^.reg = AOldReg) or
  2046. (
  2047. (OldRegType = R_INTREGISTER) and
  2048. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2049. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2050. (
  2051. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2052. {$ifndef x86_64}
  2053. and (
  2054. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2055. don't have an 8-bit representation }
  2056. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2057. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2058. )
  2059. {$endif x86_64}
  2060. )
  2061. )
  2062. ) then
  2063. begin
  2064. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2065. Result := True;
  2066. end;
  2067. top_ref:
  2068. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2069. Result := True;
  2070. else
  2071. ;
  2072. end;
  2073. end;
  2074. { Replaces all references to AOldReg in an instruction to ANewReg }
  2075. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2076. const
  2077. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2078. var
  2079. OperIdx: Integer;
  2080. begin
  2081. Result := False;
  2082. for OperIdx := 0 to p.ops - 1 do
  2083. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2084. begin
  2085. { The shift and rotate instructions can only use CL }
  2086. if not (
  2087. (OperIdx = 0) and
  2088. { This second condition just helps to avoid unnecessarily
  2089. calling MatchInstruction for 10 different opcodes }
  2090. (p.oper[0]^.reg = NR_CL) and
  2091. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2092. ) then
  2093. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2094. end
  2095. else if p.oper[OperIdx]^.typ = top_ref then
  2096. { It's okay to replace registers in references that get written to }
  2097. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2098. end;
  2099. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2100. begin
  2101. with ref^ do
  2102. Result :=
  2103. (index = NR_NO) and
  2104. (
  2105. {$ifdef x86_64}
  2106. (
  2107. (base = NR_RIP) and
  2108. (refaddr in [addr_pic, addr_pic_no_got])
  2109. ) or
  2110. {$endif x86_64}
  2111. (base = NR_STACK_POINTER_REG) or
  2112. (base = current_procinfo.framepointer)
  2113. );
  2114. end;
  2115. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2116. var
  2117. l: asizeint;
  2118. begin
  2119. Result := False;
  2120. { Should have been checked previously }
  2121. if p.opcode <> A_LEA then
  2122. InternalError(2020072501);
  2123. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2124. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2125. not(cs_opt_size in current_settings.optimizerswitches) then
  2126. exit;
  2127. with p.oper[0]^.ref^ do
  2128. begin
  2129. if (base <> p.oper[1]^.reg) or
  2130. (index <> NR_NO) or
  2131. assigned(symbol) then
  2132. exit;
  2133. l:=offset;
  2134. if (l=1) and UseIncDec then
  2135. begin
  2136. p.opcode:=A_INC;
  2137. p.loadreg(0,p.oper[1]^.reg);
  2138. p.ops:=1;
  2139. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2140. end
  2141. else if (l=-1) and UseIncDec then
  2142. begin
  2143. p.opcode:=A_DEC;
  2144. p.loadreg(0,p.oper[1]^.reg);
  2145. p.ops:=1;
  2146. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2147. end
  2148. else
  2149. begin
  2150. if (l<0) and (l<>-2147483648) then
  2151. begin
  2152. p.opcode:=A_SUB;
  2153. p.loadConst(0,-l);
  2154. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2155. end
  2156. else
  2157. begin
  2158. p.opcode:=A_ADD;
  2159. p.loadConst(0,l);
  2160. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2161. end;
  2162. end;
  2163. end;
  2164. Result := True;
  2165. end;
  2166. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2167. var
  2168. CurrentReg, ReplaceReg: TRegister;
  2169. begin
  2170. Result := False;
  2171. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2172. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2173. case hp.opcode of
  2174. A_FSTSW, A_FNSTSW,
  2175. A_IN, A_INS, A_OUT, A_OUTS,
  2176. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2177. { These routines have explicit operands, but they are restricted in
  2178. what they can be (e.g. IN and OUT can only read from AL, AX or
  2179. EAX. }
  2180. Exit;
  2181. A_IMUL:
  2182. begin
  2183. { The 1-operand version writes to implicit registers
  2184. The 2-operand version reads from the first operator, and reads
  2185. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2186. the 3-operand version reads from a register that it doesn't write to
  2187. }
  2188. case hp.ops of
  2189. 1:
  2190. if (
  2191. (
  2192. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2193. ) or
  2194. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2195. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2196. begin
  2197. Result := True;
  2198. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2199. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2200. end;
  2201. 2:
  2202. { Only modify the first parameter }
  2203. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2204. begin
  2205. Result := True;
  2206. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2207. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2208. end;
  2209. 3:
  2210. { Only modify the second parameter }
  2211. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2212. begin
  2213. Result := True;
  2214. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2215. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2216. end;
  2217. else
  2218. InternalError(2020012901);
  2219. end;
  2220. end;
  2221. else
  2222. if (hp.ops > 0) and
  2223. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2224. begin
  2225. Result := True;
  2226. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2227. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2228. end;
  2229. end;
  2230. end;
  2231. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2232. var
  2233. hp1, hp2, hp3: tai;
  2234. DoOptimisation, TempBool: Boolean;
  2235. {$ifdef x86_64}
  2236. NewConst: TCGInt;
  2237. {$endif x86_64}
  2238. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2239. begin
  2240. if taicpu(hp1).opcode = signed_movop then
  2241. begin
  2242. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2243. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2244. end
  2245. else
  2246. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2247. end;
  2248. function TryConstMerge(var p1, p2: tai): Boolean;
  2249. var
  2250. ThisRef: TReference;
  2251. begin
  2252. Result := False;
  2253. ThisRef := taicpu(p2).oper[1]^.ref^;
  2254. { Only permit writes to the stack, since we can guarantee alignment with that }
  2255. if (ThisRef.index = NR_NO) and
  2256. (
  2257. (ThisRef.base = NR_STACK_POINTER_REG) or
  2258. (ThisRef.base = current_procinfo.framepointer)
  2259. ) then
  2260. begin
  2261. case taicpu(p).opsize of
  2262. S_B:
  2263. begin
  2264. { Word writes must be on a 2-byte boundary }
  2265. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2266. begin
  2267. { Reduce offset of second reference to see if it is sequential with the first }
  2268. Dec(ThisRef.offset, 1);
  2269. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2270. begin
  2271. { Make sure the constants aren't represented as a
  2272. negative number, as these won't merge properly }
  2273. taicpu(p1).opsize := S_W;
  2274. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2275. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2276. RemoveInstruction(p2);
  2277. Result := True;
  2278. end;
  2279. end;
  2280. end;
  2281. S_W:
  2282. begin
  2283. { Longword writes must be on a 4-byte boundary }
  2284. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2285. begin
  2286. { Reduce offset of second reference to see if it is sequential with the first }
  2287. Dec(ThisRef.offset, 2);
  2288. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2289. begin
  2290. { Make sure the constants aren't represented as a
  2291. negative number, as these won't merge properly }
  2292. taicpu(p1).opsize := S_L;
  2293. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2294. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2295. RemoveInstruction(p2);
  2296. Result := True;
  2297. end;
  2298. end;
  2299. end;
  2300. {$ifdef x86_64}
  2301. S_L:
  2302. begin
  2303. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2304. see if the constants can be encoded this way. }
  2305. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2306. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2307. { Quadword writes must be on an 8-byte boundary }
  2308. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2309. begin
  2310. { Reduce offset of second reference to see if it is sequential with the first }
  2311. Dec(ThisRef.offset, 4);
  2312. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2313. begin
  2314. { Make sure the constants aren't represented as a
  2315. negative number, as these won't merge properly }
  2316. taicpu(p1).opsize := S_Q;
  2317. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2318. taicpu(p1).oper[0]^.val := NewConst;
  2319. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2320. RemoveInstruction(p2);
  2321. Result := True;
  2322. end;
  2323. end;
  2324. end;
  2325. {$endif x86_64}
  2326. else
  2327. ;
  2328. end;
  2329. end;
  2330. end;
  2331. var
  2332. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2333. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2334. NewSize: topsize;
  2335. CurrentReg, ActiveReg: TRegister;
  2336. SourceRef, TargetRef: TReference;
  2337. MovAligned, MovUnaligned: TAsmOp;
  2338. ThisRef: TReference;
  2339. begin
  2340. Result:=false;
  2341. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2342. { remove mov reg1,reg1? }
  2343. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2344. then
  2345. begin
  2346. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2347. { take care of the register (de)allocs following p }
  2348. RemoveCurrentP(p, hp1);
  2349. Result:=true;
  2350. exit;
  2351. end;
  2352. { All the next optimisations require a next instruction }
  2353. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2354. Exit;
  2355. { Look for:
  2356. mov %reg1,%reg2
  2357. ??? %reg2,r/m
  2358. Change to:
  2359. mov %reg1,%reg2
  2360. ??? %reg1,r/m
  2361. }
  2362. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2363. begin
  2364. CurrentReg := taicpu(p).oper[1]^.reg;
  2365. if RegReadByInstruction(CurrentReg, hp1) and
  2366. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2367. begin
  2368. { A change has occurred, just not in p }
  2369. Result := True;
  2370. TransferUsedRegs(TmpUsedRegs);
  2371. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2372. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2373. { Just in case something didn't get modified (e.g. an
  2374. implicit register) }
  2375. not RegReadByInstruction(CurrentReg, hp1) then
  2376. begin
  2377. { We can remove the original MOV }
  2378. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2379. RemoveCurrentp(p, hp1);
  2380. { UsedRegs got updated by RemoveCurrentp }
  2381. Result := True;
  2382. Exit;
  2383. end;
  2384. { If we know a MOV instruction has become a null operation, we might as well
  2385. get rid of it now to save time. }
  2386. if (taicpu(hp1).opcode = A_MOV) and
  2387. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2388. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2389. { Just being a register is enough to confirm it's a null operation }
  2390. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2391. begin
  2392. Result := True;
  2393. { Speed-up to reduce a pipeline stall... if we had something like...
  2394. movl %eax,%edx
  2395. movw %dx,%ax
  2396. ... the second instruction would change to movw %ax,%ax, but
  2397. given that it is now %ax that's active rather than %eax,
  2398. penalties might occur due to a partial register write, so instead,
  2399. change it to a MOVZX instruction when optimising for speed.
  2400. }
  2401. if not (cs_opt_size in current_settings.optimizerswitches) and
  2402. IsMOVZXAcceptable and
  2403. (taicpu(hp1).opsize < taicpu(p).opsize)
  2404. {$ifdef x86_64}
  2405. { operations already implicitly set the upper 64 bits to zero }
  2406. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2407. {$endif x86_64}
  2408. then
  2409. begin
  2410. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2411. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2412. case taicpu(p).opsize of
  2413. S_W:
  2414. if taicpu(hp1).opsize = S_B then
  2415. taicpu(hp1).opsize := S_BL
  2416. else
  2417. InternalError(2020012911);
  2418. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2419. case taicpu(hp1).opsize of
  2420. S_B:
  2421. taicpu(hp1).opsize := S_BL;
  2422. S_W:
  2423. taicpu(hp1).opsize := S_WL;
  2424. else
  2425. InternalError(2020012912);
  2426. end;
  2427. else
  2428. InternalError(2020012910);
  2429. end;
  2430. taicpu(hp1).opcode := A_MOVZX;
  2431. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2432. end
  2433. else
  2434. begin
  2435. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2436. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2437. RemoveInstruction(hp1);
  2438. { The instruction after what was hp1 is now the immediate next instruction,
  2439. so we can continue to make optimisations if it's present }
  2440. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2441. Exit;
  2442. hp1 := hp2;
  2443. end;
  2444. end;
  2445. end;
  2446. end;
  2447. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2448. overwrites the original destination register. e.g.
  2449. movl ###,%reg2d
  2450. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2451. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2452. }
  2453. if (taicpu(p).oper[1]^.typ = top_reg) and
  2454. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2455. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2456. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2457. begin
  2458. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2459. begin
  2460. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2461. case taicpu(p).oper[0]^.typ of
  2462. top_const:
  2463. { We have something like:
  2464. movb $x, %regb
  2465. movzbl %regb,%regd
  2466. Change to:
  2467. movl $x, %regd
  2468. }
  2469. begin
  2470. case taicpu(hp1).opsize of
  2471. S_BW:
  2472. begin
  2473. convert_mov_value(A_MOVSX, $FF);
  2474. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2475. taicpu(p).opsize := S_W;
  2476. end;
  2477. S_BL:
  2478. begin
  2479. convert_mov_value(A_MOVSX, $FF);
  2480. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2481. taicpu(p).opsize := S_L;
  2482. end;
  2483. S_WL:
  2484. begin
  2485. convert_mov_value(A_MOVSX, $FFFF);
  2486. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2487. taicpu(p).opsize := S_L;
  2488. end;
  2489. {$ifdef x86_64}
  2490. S_BQ:
  2491. begin
  2492. convert_mov_value(A_MOVSX, $FF);
  2493. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2494. taicpu(p).opsize := S_Q;
  2495. end;
  2496. S_WQ:
  2497. begin
  2498. convert_mov_value(A_MOVSX, $FFFF);
  2499. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2500. taicpu(p).opsize := S_Q;
  2501. end;
  2502. S_LQ:
  2503. begin
  2504. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2505. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2506. taicpu(p).opsize := S_Q;
  2507. end;
  2508. {$endif x86_64}
  2509. else
  2510. { If hp1 was a MOV instruction, it should have been
  2511. optimised already }
  2512. InternalError(2020021001);
  2513. end;
  2514. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2515. RemoveInstruction(hp1);
  2516. Result := True;
  2517. Exit;
  2518. end;
  2519. top_ref:
  2520. begin
  2521. { We have something like:
  2522. movb mem, %regb
  2523. movzbl %regb,%regd
  2524. Change to:
  2525. movzbl mem, %regd
  2526. }
  2527. ThisRef := taicpu(p).oper[0]^.ref^;
  2528. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2529. begin
  2530. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2531. taicpu(hp1).loadref(0, ThisRef);
  2532. { Make sure any registers in the references are properly tracked }
  2533. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2534. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2535. if (ThisRef.index <> NR_NO) then
  2536. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2537. RemoveCurrentP(p, hp1);
  2538. Result := True;
  2539. Exit;
  2540. end;
  2541. end;
  2542. else
  2543. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2544. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2545. Exit;
  2546. end;
  2547. end
  2548. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2549. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2550. optimised }
  2551. else
  2552. begin
  2553. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2554. RemoveCurrentP(p, hp1);
  2555. Result := True;
  2556. Exit;
  2557. end;
  2558. end;
  2559. if (taicpu(hp1).opcode = A_AND) and
  2560. (taicpu(p).oper[1]^.typ = top_reg) and
  2561. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2562. begin
  2563. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2564. begin
  2565. case taicpu(p).opsize of
  2566. S_L:
  2567. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2568. begin
  2569. { Optimize out:
  2570. mov x, %reg
  2571. and ffffffffh, %reg
  2572. }
  2573. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2574. RemoveInstruction(hp1);
  2575. Result:=true;
  2576. exit;
  2577. end;
  2578. S_Q: { TODO: Confirm if this is even possible }
  2579. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2580. begin
  2581. { Optimize out:
  2582. mov x, %reg
  2583. and ffffffffffffffffh, %reg
  2584. }
  2585. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2586. RemoveInstruction(hp1);
  2587. Result:=true;
  2588. exit;
  2589. end;
  2590. else
  2591. ;
  2592. end;
  2593. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2594. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2595. GetNextInstruction(hp1,hp2) and
  2596. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2597. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2598. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2599. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2600. GetNextInstruction(hp2,hp3) and
  2601. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2602. (taicpu(hp3).condition in [C_E,C_NE]) then
  2603. begin
  2604. TransferUsedRegs(TmpUsedRegs);
  2605. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2606. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2607. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2608. begin
  2609. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2610. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2611. taicpu(hp1).opcode:=A_TEST;
  2612. RemoveInstruction(hp2);
  2613. RemoveCurrentP(p, hp1);
  2614. Result:=true;
  2615. exit;
  2616. end;
  2617. end;
  2618. end
  2619. else if IsMOVZXAcceptable and
  2620. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2621. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2622. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2623. then
  2624. begin
  2625. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2626. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2627. case taicpu(p).opsize of
  2628. S_B:
  2629. if (taicpu(hp1).oper[0]^.val = $ff) then
  2630. begin
  2631. { Convert:
  2632. movb x, %regl movb x, %regl
  2633. andw ffh, %regw andl ffh, %regd
  2634. To:
  2635. movzbw x, %regd movzbl x, %regd
  2636. (Identical registers, just different sizes)
  2637. }
  2638. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2639. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2640. case taicpu(hp1).opsize of
  2641. S_W: NewSize := S_BW;
  2642. S_L: NewSize := S_BL;
  2643. {$ifdef x86_64}
  2644. S_Q: NewSize := S_BQ;
  2645. {$endif x86_64}
  2646. else
  2647. InternalError(2018011510);
  2648. end;
  2649. end
  2650. else
  2651. NewSize := S_NO;
  2652. S_W:
  2653. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2654. begin
  2655. { Convert:
  2656. movw x, %regw
  2657. andl ffffh, %regd
  2658. To:
  2659. movzwl x, %regd
  2660. (Identical registers, just different sizes)
  2661. }
  2662. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2663. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2664. case taicpu(hp1).opsize of
  2665. S_L: NewSize := S_WL;
  2666. {$ifdef x86_64}
  2667. S_Q: NewSize := S_WQ;
  2668. {$endif x86_64}
  2669. else
  2670. InternalError(2018011511);
  2671. end;
  2672. end
  2673. else
  2674. NewSize := S_NO;
  2675. else
  2676. NewSize := S_NO;
  2677. end;
  2678. if NewSize <> S_NO then
  2679. begin
  2680. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2681. { The actual optimization }
  2682. taicpu(p).opcode := A_MOVZX;
  2683. taicpu(p).changeopsize(NewSize);
  2684. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2685. { Safeguard if "and" is followed by a conditional command }
  2686. TransferUsedRegs(TmpUsedRegs);
  2687. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2688. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2689. begin
  2690. { At this point, the "and" command is effectively equivalent to
  2691. "test %reg,%reg". This will be handled separately by the
  2692. Peephole Optimizer. [Kit] }
  2693. DebugMsg(SPeepholeOptimization + PreMessage +
  2694. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2695. end
  2696. else
  2697. begin
  2698. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2699. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2700. RemoveInstruction(hp1);
  2701. end;
  2702. Result := True;
  2703. Exit;
  2704. end;
  2705. end;
  2706. end;
  2707. if (taicpu(hp1).opcode = A_OR) and
  2708. (taicpu(p).oper[1]^.typ = top_reg) and
  2709. MatchOperand(taicpu(p).oper[0]^, 0) and
  2710. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2711. begin
  2712. { mov 0, %reg
  2713. or ###,%reg
  2714. Change to (only if the flags are not used):
  2715. mov ###,%reg
  2716. }
  2717. TransferUsedRegs(TmpUsedRegs);
  2718. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2719. DoOptimisation := True;
  2720. { Even if the flags are used, we might be able to do the optimisation
  2721. if the conditions are predictable }
  2722. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2723. begin
  2724. { Only perform if ### = %reg (the same register) or equal to 0,
  2725. so %reg is guaranteed to still have a value of zero }
  2726. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2727. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2728. begin
  2729. hp2 := hp1;
  2730. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2731. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2732. GetNextInstruction(hp2, hp3) do
  2733. begin
  2734. { Don't continue modifying if the flags state is getting changed }
  2735. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2736. Break;
  2737. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2738. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2739. begin
  2740. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2741. begin
  2742. { Condition is always true }
  2743. case taicpu(hp3).opcode of
  2744. A_Jcc:
  2745. begin
  2746. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2747. { Check for jump shortcuts before we destroy the condition }
  2748. DoJumpOptimizations(hp3, TempBool);
  2749. MakeUnconditional(taicpu(hp3));
  2750. Result := True;
  2751. end;
  2752. A_CMOVcc:
  2753. begin
  2754. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2755. taicpu(hp3).opcode := A_MOV;
  2756. taicpu(hp3).condition := C_None;
  2757. Result := True;
  2758. end;
  2759. A_SETcc:
  2760. begin
  2761. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2762. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2763. taicpu(hp3).opcode := A_MOV;
  2764. taicpu(hp3).ops := 2;
  2765. taicpu(hp3).condition := C_None;
  2766. taicpu(hp3).opsize := S_B;
  2767. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2768. taicpu(hp3).loadconst(0, 1);
  2769. Result := True;
  2770. end;
  2771. else
  2772. InternalError(2021090701);
  2773. end;
  2774. end
  2775. 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
  2776. begin
  2777. { Condition is always false }
  2778. case taicpu(hp3).opcode of
  2779. A_Jcc:
  2780. begin
  2781. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2782. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2783. RemoveInstruction(hp3);
  2784. Result := True;
  2785. { Since hp3 was deleted, hp2 must not be updated }
  2786. Continue;
  2787. end;
  2788. A_CMOVcc:
  2789. begin
  2790. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2791. RemoveInstruction(hp3);
  2792. Result := True;
  2793. { Since hp3 was deleted, hp2 must not be updated }
  2794. Continue;
  2795. end;
  2796. A_SETcc:
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2799. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2800. taicpu(hp3).opcode := A_MOV;
  2801. taicpu(hp3).ops := 2;
  2802. taicpu(hp3).condition := C_None;
  2803. taicpu(hp3).opsize := S_B;
  2804. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2805. taicpu(hp3).loadconst(0, 0);
  2806. Result := True;
  2807. end;
  2808. else
  2809. InternalError(2021090702);
  2810. end;
  2811. end
  2812. else
  2813. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2814. DoOptimisation := False;
  2815. end;
  2816. hp2 := hp3;
  2817. end;
  2818. { Flags are still in use - don't optimise }
  2819. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2820. DoOptimisation := False;
  2821. end
  2822. else
  2823. DoOptimisation := False;
  2824. end;
  2825. if DoOptimisation then
  2826. begin
  2827. {$ifdef x86_64}
  2828. { OR only supports 32-bit sign-extended constants for 64-bit
  2829. instructions, so compensate for this if the constant is
  2830. encoded as a value greater than or equal to 2^31 }
  2831. if (taicpu(hp1).opsize = S_Q) and
  2832. (taicpu(hp1).oper[0]^.typ = top_const) and
  2833. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2834. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2835. {$endif x86_64}
  2836. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2837. taicpu(hp1).opcode := A_MOV;
  2838. RemoveCurrentP(p, hp1);
  2839. Result := True;
  2840. Exit;
  2841. end;
  2842. end;
  2843. { Next instruction is also a MOV ? }
  2844. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2845. begin
  2846. if MatchOpType(taicpu(p), top_const, top_ref) and
  2847. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2848. TryConstMerge(p, hp1) then
  2849. begin
  2850. Result := True;
  2851. { In case we have four byte writes in a row, check for 2 more
  2852. right now so we don't have to wait for another iteration of
  2853. pass 1
  2854. }
  2855. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2856. case taicpu(p).opsize of
  2857. S_W:
  2858. begin
  2859. if GetNextInstruction(p, hp1) and
  2860. MatchInstruction(hp1, A_MOV, [S_B]) and
  2861. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2862. GetNextInstruction(hp1, hp2) and
  2863. MatchInstruction(hp2, A_MOV, [S_B]) and
  2864. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2865. { Try to merge the two bytes }
  2866. TryConstMerge(hp1, hp2) then
  2867. { Now try to merge the two words (hp2 will get deleted) }
  2868. TryConstMerge(p, hp1);
  2869. end;
  2870. S_L:
  2871. begin
  2872. { Though this only really benefits x86_64 and not i386, it
  2873. gets a potential optimisation done faster and hence
  2874. reduces the number of times OptPass1MOV is entered }
  2875. if GetNextInstruction(p, hp1) and
  2876. MatchInstruction(hp1, A_MOV, [S_W]) and
  2877. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2878. GetNextInstruction(hp1, hp2) and
  2879. MatchInstruction(hp2, A_MOV, [S_W]) and
  2880. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2881. { Try to merge the two words }
  2882. TryConstMerge(hp1, hp2) then
  2883. { This will always fail on i386, so don't bother
  2884. calling it unless we're doing x86_64 }
  2885. {$ifdef x86_64}
  2886. { Now try to merge the two longwords (hp2 will get deleted) }
  2887. TryConstMerge(p, hp1)
  2888. {$endif x86_64}
  2889. ;
  2890. end;
  2891. else
  2892. ;
  2893. end;
  2894. Exit;
  2895. end;
  2896. if (taicpu(p).oper[1]^.typ = top_reg) and
  2897. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2898. begin
  2899. CurrentReg := taicpu(p).oper[1]^.reg;
  2900. TransferUsedRegs(TmpUsedRegs);
  2901. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2902. { we have
  2903. mov x, %treg
  2904. mov %treg, y
  2905. }
  2906. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2907. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2908. { we've got
  2909. mov x, %treg
  2910. mov %treg, y
  2911. with %treg is not used after }
  2912. case taicpu(p).oper[0]^.typ Of
  2913. { top_reg is covered by DeepMOVOpt }
  2914. top_const:
  2915. begin
  2916. { change
  2917. mov const, %treg
  2918. mov %treg, y
  2919. to
  2920. mov const, y
  2921. }
  2922. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2923. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2924. begin
  2925. if taicpu(hp1).oper[1]^.typ=top_reg then
  2926. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2927. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2928. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2929. RemoveInstruction(hp1);
  2930. Result:=true;
  2931. Exit;
  2932. end;
  2933. end;
  2934. top_ref:
  2935. case taicpu(hp1).oper[1]^.typ of
  2936. top_reg:
  2937. begin
  2938. { change
  2939. mov mem, %treg
  2940. mov %treg, %reg
  2941. to
  2942. mov mem, %reg"
  2943. }
  2944. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2945. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2946. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2947. RemoveInstruction(hp1);
  2948. Result:=true;
  2949. Exit;
  2950. end;
  2951. top_ref:
  2952. begin
  2953. {$ifdef x86_64}
  2954. { Look for the following to simplify:
  2955. mov x(mem1), %reg
  2956. mov %reg, y(mem2)
  2957. mov x+8(mem1), %reg
  2958. mov %reg, y+8(mem2)
  2959. Change to:
  2960. movdqu x(mem1), %xmmreg
  2961. movdqu %xmmreg, y(mem2)
  2962. ...but only as long as the memory blocks don't overlap
  2963. }
  2964. SourceRef := taicpu(p).oper[0]^.ref^;
  2965. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2966. if (taicpu(p).opsize = S_Q) and
  2967. GetNextInstruction(hp1, hp2) and
  2968. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2969. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2970. begin
  2971. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2972. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2973. Inc(SourceRef.offset, 8);
  2974. if UseAVX then
  2975. begin
  2976. MovAligned := A_VMOVDQA;
  2977. MovUnaligned := A_VMOVDQU;
  2978. end
  2979. else
  2980. begin
  2981. MovAligned := A_MOVDQA;
  2982. MovUnaligned := A_MOVDQU;
  2983. end;
  2984. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  2985. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  2986. begin
  2987. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2988. Inc(TargetRef.offset, 8);
  2989. if GetNextInstruction(hp2, hp3) and
  2990. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2991. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2992. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2993. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2994. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2995. begin
  2996. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2997. if CurrentReg <> NR_NO then
  2998. begin
  2999. { Remember that the offsets are 8 ahead }
  3000. if ((SourceRef.offset mod 16) = 8) and
  3001. (
  3002. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3003. (SourceRef.base = current_procinfo.framepointer) or
  3004. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3005. ) then
  3006. taicpu(p).opcode := MovAligned
  3007. else
  3008. taicpu(p).opcode := MovUnaligned;
  3009. taicpu(p).opsize := S_XMM;
  3010. taicpu(p).oper[1]^.reg := CurrentReg;
  3011. if ((TargetRef.offset mod 16) = 8) and
  3012. (
  3013. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3014. (TargetRef.base = current_procinfo.framepointer) or
  3015. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3016. ) then
  3017. taicpu(hp1).opcode := MovAligned
  3018. else
  3019. taicpu(hp1).opcode := MovUnaligned;
  3020. taicpu(hp1).opsize := S_XMM;
  3021. taicpu(hp1).oper[0]^.reg := CurrentReg;
  3022. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3023. RemoveInstruction(hp2);
  3024. RemoveInstruction(hp3);
  3025. Result := True;
  3026. Exit;
  3027. end;
  3028. end;
  3029. end
  3030. else
  3031. begin
  3032. { See if the next references are 8 less rather than 8 greater }
  3033. Dec(SourceRef.offset, 16); { -8 the other way }
  3034. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3035. begin
  3036. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3037. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3038. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3039. GetNextInstruction(hp2, hp3) and
  3040. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3041. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3042. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3043. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3044. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3045. begin
  3046. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3047. if CurrentReg <> NR_NO then
  3048. begin
  3049. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3050. if ((SourceRef.offset mod 16) = 0) and
  3051. (
  3052. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3053. (SourceRef.base = current_procinfo.framepointer) or
  3054. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3055. ) then
  3056. taicpu(hp2).opcode := MovAligned
  3057. else
  3058. taicpu(hp2).opcode := MovUnaligned;
  3059. taicpu(hp2).opsize := S_XMM;
  3060. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3061. if ((TargetRef.offset mod 16) = 0) and
  3062. (
  3063. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3064. (TargetRef.base = current_procinfo.framepointer) or
  3065. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3066. ) then
  3067. taicpu(hp3).opcode := MovAligned
  3068. else
  3069. taicpu(hp3).opcode := MovUnaligned;
  3070. taicpu(hp3).opsize := S_XMM;
  3071. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3072. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3073. RemoveInstruction(hp1);
  3074. RemoveCurrentP(p, hp2);
  3075. Result := True;
  3076. Exit;
  3077. end;
  3078. end;
  3079. end;
  3080. end;
  3081. end;
  3082. {$endif x86_64}
  3083. end;
  3084. else
  3085. { The write target should be a reg or a ref }
  3086. InternalError(2021091601);
  3087. end;
  3088. else
  3089. ;
  3090. end
  3091. else
  3092. { %treg is used afterwards, but all eventualities
  3093. other than the first MOV instruction being a constant
  3094. are covered by DeepMOVOpt, so only check for that }
  3095. if (taicpu(p).oper[0]^.typ = top_const) and
  3096. (
  3097. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3098. not (cs_opt_size in current_settings.optimizerswitches) or
  3099. (taicpu(hp1).opsize = S_B)
  3100. ) and
  3101. (
  3102. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3103. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3104. ) then
  3105. begin
  3106. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3107. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3108. end;
  3109. end;
  3110. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3111. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3112. { mov reg1, mem1 or mov mem1, reg1
  3113. mov mem2, reg2 mov reg2, mem2}
  3114. begin
  3115. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3116. { mov reg1, mem1 or mov mem1, reg1
  3117. mov mem2, reg1 mov reg2, mem1}
  3118. begin
  3119. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3120. { Removes the second statement from
  3121. mov reg1, mem1/reg2
  3122. mov mem1/reg2, reg1 }
  3123. begin
  3124. if taicpu(p).oper[0]^.typ=top_reg then
  3125. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3126. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3127. RemoveInstruction(hp1);
  3128. Result:=true;
  3129. exit;
  3130. end
  3131. else
  3132. begin
  3133. TransferUsedRegs(TmpUsedRegs);
  3134. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3135. if (taicpu(p).oper[1]^.typ = top_ref) and
  3136. { mov reg1, mem1
  3137. mov mem2, reg1 }
  3138. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3139. GetNextInstruction(hp1, hp2) and
  3140. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3141. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3142. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3143. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3144. { change to
  3145. mov reg1, mem1 mov reg1, mem1
  3146. mov mem2, reg1 cmp reg1, mem2
  3147. cmp mem1, reg1
  3148. }
  3149. begin
  3150. RemoveInstruction(hp2);
  3151. taicpu(hp1).opcode := A_CMP;
  3152. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3153. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3154. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3155. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3156. end;
  3157. end;
  3158. end
  3159. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3160. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3161. begin
  3162. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3163. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3164. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3165. end
  3166. else
  3167. begin
  3168. TransferUsedRegs(TmpUsedRegs);
  3169. if GetNextInstruction(hp1, hp2) and
  3170. MatchOpType(taicpu(p),top_ref,top_reg) and
  3171. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3172. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3173. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3174. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3175. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3176. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3177. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3178. { mov mem1, %reg1
  3179. mov %reg1, mem2
  3180. mov mem2, reg2
  3181. to:
  3182. mov mem1, reg2
  3183. mov reg2, mem2}
  3184. begin
  3185. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3186. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3187. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3188. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3189. RemoveInstruction(hp2);
  3190. Result := True;
  3191. end
  3192. {$ifdef i386}
  3193. { this is enabled for i386 only, as the rules to create the reg sets below
  3194. are too complicated for x86-64, so this makes this code too error prone
  3195. on x86-64
  3196. }
  3197. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3198. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3199. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3200. { mov mem1, reg1 mov mem1, reg1
  3201. mov reg1, mem2 mov reg1, mem2
  3202. mov mem2, reg2 mov mem2, reg1
  3203. to: to:
  3204. mov mem1, reg1 mov mem1, reg1
  3205. mov mem1, reg2 mov reg1, mem2
  3206. mov reg1, mem2
  3207. or (if mem1 depends on reg1
  3208. and/or if mem2 depends on reg2)
  3209. to:
  3210. mov mem1, reg1
  3211. mov reg1, mem2
  3212. mov reg1, reg2
  3213. }
  3214. begin
  3215. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3216. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3217. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3218. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3219. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3220. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3221. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3222. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3223. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3224. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3225. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3226. end
  3227. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3228. begin
  3229. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3230. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3231. end
  3232. else
  3233. begin
  3234. RemoveInstruction(hp2);
  3235. end
  3236. {$endif i386}
  3237. ;
  3238. end;
  3239. end
  3240. { movl [mem1],reg1
  3241. movl [mem1],reg2
  3242. to
  3243. movl [mem1],reg1
  3244. movl reg1,reg2
  3245. }
  3246. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3247. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3248. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3249. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3250. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3251. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3252. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3253. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3254. begin
  3255. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3256. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3257. end;
  3258. { movl const1,[mem1]
  3259. movl [mem1],reg1
  3260. to
  3261. movl const1,reg1
  3262. movl reg1,[mem1]
  3263. }
  3264. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3265. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3266. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3267. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3268. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3269. begin
  3270. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3271. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3272. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3273. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3274. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3275. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3276. Result:=true;
  3277. exit;
  3278. end;
  3279. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3280. { Change:
  3281. movl %reg1,%reg2
  3282. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3283. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3284. To:
  3285. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3286. movl x(%reg1),%reg1
  3287. movl %reg1,%regX
  3288. }
  3289. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3290. begin
  3291. CurrentReg := taicpu(p).oper[0]^.reg;
  3292. ActiveReg := taicpu(p).oper[1]^.reg;
  3293. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3294. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3295. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3296. GetNextInstruction(hp1, hp2) and
  3297. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3298. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3299. begin
  3300. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3301. if RegInRef(ActiveReg, SourceRef) and
  3302. { If %reg1 also appears in the second reference, then it will
  3303. not refer to the same memory block as the first reference }
  3304. not RegInRef(CurrentReg, SourceRef) then
  3305. begin
  3306. { Check to see if the references match if %reg2 is changed to %reg1 }
  3307. if SourceRef.base = ActiveReg then
  3308. SourceRef.base := CurrentReg;
  3309. if SourceRef.index = ActiveReg then
  3310. SourceRef.index := CurrentReg;
  3311. { RefsEqual also checks to ensure both references are non-volatile }
  3312. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3313. begin
  3314. taicpu(hp2).loadreg(0, CurrentReg);
  3315. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3316. Result := True;
  3317. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3318. begin
  3319. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3320. RemoveCurrentP(p, hp1);
  3321. Exit;
  3322. end
  3323. else
  3324. begin
  3325. { Check to see if %reg2 is no longer in use }
  3326. TransferUsedRegs(TmpUsedRegs);
  3327. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3328. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3329. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3330. begin
  3331. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3332. RemoveCurrentP(p, hp1);
  3333. Exit;
  3334. end;
  3335. end;
  3336. { If we reach this point, p and hp1 weren't actually modified,
  3337. so we can do a bit more work on this pass }
  3338. end;
  3339. end;
  3340. end;
  3341. end;
  3342. end;
  3343. { search further than the next instruction for a mov (as long as it's not a jump) }
  3344. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3345. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3346. (taicpu(p).oper[1]^.typ = top_reg) and
  3347. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3348. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3349. begin
  3350. { we work with hp2 here, so hp1 can be still used later on when
  3351. checking for GetNextInstruction_p }
  3352. hp3 := hp1;
  3353. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3354. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3355. { Saves on a large number of dereferences }
  3356. ActiveReg := taicpu(p).oper[1]^.reg;
  3357. TransferUsedRegs(TmpUsedRegs);
  3358. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3359. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3360. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3361. (hp2.typ=ait_instruction) do
  3362. begin
  3363. case taicpu(hp2).opcode of
  3364. A_POP:
  3365. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3366. begin
  3367. if not CrossJump and
  3368. not RegUsedBetween(ActiveReg, p, hp2) then
  3369. begin
  3370. { We can remove the original MOV since the register
  3371. wasn't used between it and its popping from the stack }
  3372. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3373. RemoveCurrentp(p, hp1);
  3374. Result := True;
  3375. Exit;
  3376. end;
  3377. { Can't go any further }
  3378. Break;
  3379. end;
  3380. A_MOV:
  3381. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3382. ((taicpu(p).oper[0]^.typ=top_const) or
  3383. ((taicpu(p).oper[0]^.typ=top_reg) and
  3384. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3385. )
  3386. ) then
  3387. begin
  3388. { we have
  3389. mov x, %treg
  3390. mov %treg, y
  3391. }
  3392. { We don't need to call UpdateUsedRegs for every instruction between
  3393. p and hp2 because the register we're concerned about will not
  3394. become deallocated (otherwise GetNextInstructionUsingReg would
  3395. have stopped at an earlier instruction). [Kit] }
  3396. TempRegUsed :=
  3397. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3398. RegReadByInstruction(ActiveReg, hp3) or
  3399. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3400. case taicpu(p).oper[0]^.typ Of
  3401. top_reg:
  3402. begin
  3403. { change
  3404. mov %reg, %treg
  3405. mov %treg, y
  3406. to
  3407. mov %reg, y
  3408. }
  3409. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3410. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3411. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3412. begin
  3413. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3414. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3415. if TempRegUsed then
  3416. begin
  3417. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3418. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3419. { Set the start of the next GetNextInstructionUsingRegCond search
  3420. to start at the entry right before hp2 (which is about to be removed) }
  3421. hp3 := tai(hp2.Previous);
  3422. RemoveInstruction(hp2);
  3423. { See if there's more we can optimise }
  3424. Continue;
  3425. end
  3426. else
  3427. begin
  3428. RemoveInstruction(hp2);
  3429. { We can remove the original MOV too }
  3430. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3431. RemoveCurrentP(p, hp1);
  3432. Result:=true;
  3433. Exit;
  3434. end;
  3435. end
  3436. else
  3437. begin
  3438. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3439. taicpu(hp2).loadReg(0, CurrentReg);
  3440. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3441. { Check to see if the register also appears in the reference }
  3442. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3443. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3444. { Don't remove the first instruction if the temporary register is in use }
  3445. if not TempRegUsed and
  3446. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3447. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3448. begin
  3449. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3450. RemoveCurrentP(p, hp1);
  3451. Result:=true;
  3452. Exit;
  3453. end;
  3454. { No need to set Result to True here. If there's another instruction later
  3455. on that can be optimised, it will be detected when the main Pass 1 loop
  3456. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3457. end;
  3458. end;
  3459. top_const:
  3460. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3461. begin
  3462. { change
  3463. mov const, %treg
  3464. mov %treg, y
  3465. to
  3466. mov const, y
  3467. }
  3468. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3469. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3470. begin
  3471. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3472. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3473. if TempRegUsed then
  3474. begin
  3475. { Don't remove the first instruction if the temporary register is in use }
  3476. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3477. { No need to set Result to True. If there's another instruction later on
  3478. that can be optimised, it will be detected when the main Pass 1 loop
  3479. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3480. end
  3481. else
  3482. begin
  3483. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3484. RemoveCurrentP(p, hp1);
  3485. Result:=true;
  3486. Exit;
  3487. end;
  3488. end;
  3489. end;
  3490. else
  3491. Internalerror(2019103001);
  3492. end;
  3493. end
  3494. else
  3495. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3496. begin
  3497. if not CrossJump and
  3498. not RegUsedBetween(ActiveReg, p, hp2) and
  3499. not RegReadByInstruction(ActiveReg, hp2) then
  3500. begin
  3501. { Register is not used before it is overwritten }
  3502. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3503. RemoveCurrentp(p, hp1);
  3504. Result := True;
  3505. Exit;
  3506. end;
  3507. if (taicpu(p).oper[0]^.typ = top_const) and
  3508. (taicpu(hp2).oper[0]^.typ = top_const) then
  3509. begin
  3510. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3511. begin
  3512. { Same value - register hasn't changed }
  3513. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3514. RemoveInstruction(hp2);
  3515. Result := True;
  3516. { See if there's more we can optimise }
  3517. Continue;
  3518. end;
  3519. end;
  3520. end;
  3521. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3522. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3523. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3524. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3525. begin
  3526. {
  3527. Change from:
  3528. mov ###, %reg
  3529. ...
  3530. movs/z %reg,%reg (Same register, just different sizes)
  3531. To:
  3532. movs/z ###, %reg (Longer version)
  3533. ...
  3534. (remove)
  3535. }
  3536. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3537. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3538. { Keep the first instruction as mov if ### is a constant }
  3539. if taicpu(p).oper[0]^.typ = top_const then
  3540. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3541. else
  3542. begin
  3543. taicpu(p).opcode := taicpu(hp2).opcode;
  3544. taicpu(p).opsize := taicpu(hp2).opsize;
  3545. end;
  3546. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3547. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3548. RemoveInstruction(hp2);
  3549. Result := True;
  3550. Exit;
  3551. end;
  3552. else
  3553. { Move down to the MatchOpType if-block below };
  3554. end;
  3555. { Also catches MOV/S/Z instructions that aren't modified }
  3556. if taicpu(p).oper[0]^.typ = top_reg then
  3557. begin
  3558. CurrentReg := taicpu(p).oper[0]^.reg;
  3559. if
  3560. not RegModifiedByInstruction(CurrentReg, hp3) and
  3561. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3562. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3563. begin
  3564. Result := True;
  3565. { Just in case something didn't get modified (e.g. an
  3566. implicit register). Also, if it does read from this
  3567. register, then there's no longer an advantage to
  3568. changing the register on subsequent instructions.}
  3569. if not RegReadByInstruction(ActiveReg, hp2) then
  3570. begin
  3571. { If a conditional jump was crossed, do not delete
  3572. the original MOV no matter what }
  3573. if not CrossJump and
  3574. { RegEndOfLife returns True if the register is
  3575. deallocated before the next instruction or has
  3576. been loaded with a new value }
  3577. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3578. begin
  3579. { We can remove the original MOV }
  3580. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3581. RemoveCurrentp(p, hp1);
  3582. Exit;
  3583. end;
  3584. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3585. begin
  3586. { See if there's more we can optimise }
  3587. hp3 := hp2;
  3588. Continue;
  3589. end;
  3590. end;
  3591. end;
  3592. end;
  3593. { Break out of the while loop under normal circumstances }
  3594. Break;
  3595. end;
  3596. end;
  3597. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3598. (taicpu(p).oper[1]^.typ = top_reg) and
  3599. (taicpu(p).opsize = S_L) and
  3600. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3601. (taicpu(hp2).opcode = A_AND) and
  3602. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3603. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3604. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3605. ) then
  3606. begin
  3607. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3608. begin
  3609. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3610. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3611. begin
  3612. { Optimize out:
  3613. mov x, %reg
  3614. and ffffffffh, %reg
  3615. }
  3616. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3617. RemoveInstruction(hp2);
  3618. Result:=true;
  3619. exit;
  3620. end;
  3621. end;
  3622. end;
  3623. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3624. x >= RetOffset) as it doesn't do anything (it writes either to a
  3625. parameter or to the temporary storage room for the function
  3626. result)
  3627. }
  3628. if IsExitCode(hp1) and
  3629. (taicpu(p).oper[1]^.typ = top_ref) and
  3630. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3631. (
  3632. (
  3633. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3634. not (
  3635. assigned(current_procinfo.procdef.funcretsym) and
  3636. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3637. )
  3638. ) or
  3639. { Also discard writes to the stack that are below the base pointer,
  3640. as this is temporary storage rather than a function result on the
  3641. stack, say. }
  3642. (
  3643. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3644. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3645. )
  3646. ) then
  3647. begin
  3648. RemoveCurrentp(p, hp1);
  3649. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3650. RemoveLastDeallocForFuncRes(p);
  3651. Result:=true;
  3652. exit;
  3653. end;
  3654. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3655. begin
  3656. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3657. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3658. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3659. begin
  3660. { change
  3661. mov reg1, mem1
  3662. test/cmp x, mem1
  3663. to
  3664. mov reg1, mem1
  3665. test/cmp x, reg1
  3666. }
  3667. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3668. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3669. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3670. Result := True;
  3671. Exit;
  3672. end;
  3673. if DoMovCmpMemOpt(p, hp1, True) then
  3674. begin
  3675. Result := True;
  3676. Exit;
  3677. end;
  3678. end;
  3679. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3680. { If the flags register is in use, don't change the instruction to an
  3681. ADD otherwise this will scramble the flags. [Kit] }
  3682. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3683. begin
  3684. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3685. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3686. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3687. ) or
  3688. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3689. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3690. )
  3691. ) then
  3692. { mov reg1,ref
  3693. lea reg2,[reg1,reg2]
  3694. to
  3695. add reg2,ref}
  3696. begin
  3697. TransferUsedRegs(TmpUsedRegs);
  3698. { reg1 may not be used afterwards }
  3699. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3700. begin
  3701. Taicpu(hp1).opcode:=A_ADD;
  3702. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3703. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3704. RemoveCurrentp(p, hp1);
  3705. result:=true;
  3706. exit;
  3707. end;
  3708. end;
  3709. { If the LEA instruction can be converted into an arithmetic instruction,
  3710. it may be possible to then fold it in the next optimisation, otherwise
  3711. there's nothing more that can be optimised here. }
  3712. if not ConvertLEA(taicpu(hp1)) then
  3713. Exit;
  3714. end;
  3715. if (taicpu(p).oper[1]^.typ = top_reg) and
  3716. (hp1.typ = ait_instruction) and
  3717. GetNextInstruction(hp1, hp2) and
  3718. MatchInstruction(hp2,A_MOV,[]) and
  3719. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3720. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3721. (
  3722. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3723. {$ifdef x86_64}
  3724. or
  3725. (
  3726. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3727. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3728. )
  3729. {$endif x86_64}
  3730. ) then
  3731. begin
  3732. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3733. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3734. { change movsX/movzX reg/ref, reg2
  3735. add/sub/or/... reg3/$const, reg2
  3736. mov reg2 reg/ref
  3737. dealloc reg2
  3738. to
  3739. add/sub/or/... reg3/$const, reg/ref }
  3740. begin
  3741. TransferUsedRegs(TmpUsedRegs);
  3742. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3743. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3744. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3745. begin
  3746. { by example:
  3747. movswl %si,%eax movswl %si,%eax p
  3748. decl %eax addl %edx,%eax hp1
  3749. movw %ax,%si movw %ax,%si hp2
  3750. ->
  3751. movswl %si,%eax movswl %si,%eax p
  3752. decw %eax addw %edx,%eax hp1
  3753. movw %ax,%si movw %ax,%si hp2
  3754. }
  3755. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3756. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3757. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3758. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3759. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3760. {
  3761. ->
  3762. movswl %si,%eax movswl %si,%eax p
  3763. decw %si addw %dx,%si hp1
  3764. movw %ax,%si movw %ax,%si hp2
  3765. }
  3766. case taicpu(hp1).ops of
  3767. 1:
  3768. begin
  3769. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3770. if taicpu(hp1).oper[0]^.typ=top_reg then
  3771. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3772. end;
  3773. 2:
  3774. begin
  3775. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3776. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3777. (taicpu(hp1).opcode<>A_SHL) and
  3778. (taicpu(hp1).opcode<>A_SHR) and
  3779. (taicpu(hp1).opcode<>A_SAR) then
  3780. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3781. end;
  3782. else
  3783. internalerror(2008042701);
  3784. end;
  3785. {
  3786. ->
  3787. decw %si addw %dx,%si p
  3788. }
  3789. RemoveInstruction(hp2);
  3790. RemoveCurrentP(p, hp1);
  3791. Result:=True;
  3792. Exit;
  3793. end;
  3794. end;
  3795. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3796. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3797. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3798. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3799. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3800. )
  3801. {$ifdef i386}
  3802. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3803. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3804. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3805. {$endif i386}
  3806. then
  3807. { change movsX/movzX reg/ref, reg2
  3808. add/sub/or/... regX/$const, reg2
  3809. mov reg2, reg3
  3810. dealloc reg2
  3811. to
  3812. movsX/movzX reg/ref, reg3
  3813. add/sub/or/... reg3/$const, reg3
  3814. }
  3815. begin
  3816. TransferUsedRegs(TmpUsedRegs);
  3817. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3818. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3819. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3820. begin
  3821. { by example:
  3822. movswl %si,%eax movswl %si,%eax p
  3823. decl %eax addl %edx,%eax hp1
  3824. movw %ax,%si movw %ax,%si hp2
  3825. ->
  3826. movswl %si,%eax movswl %si,%eax p
  3827. decw %eax addw %edx,%eax hp1
  3828. movw %ax,%si movw %ax,%si hp2
  3829. }
  3830. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3831. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3832. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3833. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3834. { limit size of constants as well to avoid assembler errors, but
  3835. check opsize to avoid overflow when left shifting the 1 }
  3836. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3837. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3838. {$ifdef x86_64}
  3839. { Be careful of, for example:
  3840. movl %reg1,%reg2
  3841. addl %reg3,%reg2
  3842. movq %reg2,%reg4
  3843. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3844. }
  3845. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3846. begin
  3847. taicpu(hp2).changeopsize(S_L);
  3848. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3849. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3850. end;
  3851. {$endif x86_64}
  3852. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3853. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3854. if taicpu(p).oper[0]^.typ=top_reg then
  3855. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3856. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3857. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3858. {
  3859. ->
  3860. movswl %si,%eax movswl %si,%eax p
  3861. decw %si addw %dx,%si hp1
  3862. movw %ax,%si movw %ax,%si hp2
  3863. }
  3864. case taicpu(hp1).ops of
  3865. 1:
  3866. begin
  3867. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3868. if taicpu(hp1).oper[0]^.typ=top_reg then
  3869. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3870. end;
  3871. 2:
  3872. begin
  3873. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3874. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3875. (taicpu(hp1).opcode<>A_SHL) and
  3876. (taicpu(hp1).opcode<>A_SHR) and
  3877. (taicpu(hp1).opcode<>A_SAR) then
  3878. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3879. end;
  3880. else
  3881. internalerror(2018111801);
  3882. end;
  3883. {
  3884. ->
  3885. decw %si addw %dx,%si p
  3886. }
  3887. RemoveInstruction(hp2);
  3888. end;
  3889. end;
  3890. end;
  3891. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3892. GetNextInstruction(hp1, hp2) and
  3893. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3894. MatchOperand(Taicpu(p).oper[0]^,0) and
  3895. (Taicpu(p).oper[1]^.typ = top_reg) and
  3896. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3897. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3898. { mov reg1,0
  3899. bts reg1,operand1 --> mov reg1,operand2
  3900. or reg1,operand2 bts reg1,operand1}
  3901. begin
  3902. Taicpu(hp2).opcode:=A_MOV;
  3903. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3904. asml.remove(hp1);
  3905. insertllitem(hp2,hp2.next,hp1);
  3906. RemoveCurrentp(p, hp1);
  3907. Result:=true;
  3908. exit;
  3909. end;
  3910. {
  3911. mov ref,reg0
  3912. <op> reg0,reg1
  3913. dealloc reg0
  3914. to
  3915. <op> ref,reg1
  3916. }
  3917. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3918. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3919. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3920. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3921. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3922. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3923. begin
  3924. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3925. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3926. RemoveCurrentp(p, hp1);
  3927. Result:=true;
  3928. exit;
  3929. end;
  3930. {$ifdef x86_64}
  3931. { Convert:
  3932. movq x(ref),%reg64
  3933. shrq y,%reg64
  3934. To:
  3935. movl x+4(ref),%reg32
  3936. shrl y-32,%reg32 (Remove if y = 32)
  3937. }
  3938. if (taicpu(p).opsize = S_Q) and
  3939. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3940. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3941. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3942. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3943. (taicpu(hp1).oper[0]^.val >= 32) and
  3944. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3945. begin
  3946. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3947. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3948. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3949. { Convert to 32-bit }
  3950. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3951. taicpu(p).opsize := S_L;
  3952. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3953. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3954. if (taicpu(hp1).oper[0]^.val = 32) then
  3955. begin
  3956. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3957. RemoveInstruction(hp1);
  3958. end
  3959. else
  3960. begin
  3961. { This will potentially open up more arithmetic operations since
  3962. the peephole optimizer now has a big hint that only the lower
  3963. 32 bits are currently in use (and opcodes are smaller in size) }
  3964. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3965. taicpu(hp1).opsize := S_L;
  3966. Dec(taicpu(hp1).oper[0]^.val, 32);
  3967. DebugMsg(SPeepholeOptimization + PreMessage +
  3968. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3969. end;
  3970. Result := True;
  3971. Exit;
  3972. end;
  3973. {$endif x86_64}
  3974. { Backward optimisation. If we have:
  3975. func. %reg1,%reg2
  3976. mov %reg2,%reg3
  3977. (dealloc %reg2)
  3978. Change to:
  3979. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3980. }
  3981. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3982. begin
  3983. CurrentReg := taicpu(p).oper[0]^.reg;
  3984. ActiveReg := taicpu(p).oper[1]^.reg;
  3985. TransferUsedRegs(TmpUsedRegs);
  3986. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3987. GetLastInstruction(p, hp2) and
  3988. (hp2.typ = ait_instruction) and
  3989. { Have to make sure it's an instruction that only reads from
  3990. operand 1 and only writes (not reads or modifies) from operand 2;
  3991. in essence, a one-operand pure function such as BSR or POPCNT }
  3992. (taicpu(hp2).ops = 2) and
  3993. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3994. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3995. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3996. begin
  3997. case taicpu(hp2).opcode of
  3998. A_FSTSW, A_FNSTSW,
  3999. A_IN, A_INS, A_OUT, A_OUTS,
  4000. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  4001. { These routines have explicit operands, but they are restricted in
  4002. what they can be (e.g. IN and OUT can only read from AL, AX or
  4003. EAX. }
  4004. A_CMOVcc:
  4005. { CMOV is not valid either because then CurrentReg will depend
  4006. on an unknown value if the condition is False and hence is
  4007. not a pure write }
  4008. ;
  4009. else
  4010. begin
  4011. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4012. taicpu(hp2).oper[1]^.reg := ActiveReg;
  4013. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  4014. RemoveCurrentp(p, hp1);
  4015. Result := True;
  4016. Exit;
  4017. end;
  4018. end;
  4019. end;
  4020. end;
  4021. end;
  4022. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4023. var
  4024. hp1 : tai;
  4025. begin
  4026. Result:=false;
  4027. if taicpu(p).ops <> 2 then
  4028. exit;
  4029. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4030. GetNextInstruction(p,hp1) then
  4031. begin
  4032. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4033. (taicpu(hp1).ops = 2) then
  4034. begin
  4035. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4036. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4037. { movXX reg1, mem1 or movXX mem1, reg1
  4038. movXX mem2, reg2 movXX reg2, mem2}
  4039. begin
  4040. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4041. { movXX reg1, mem1 or movXX mem1, reg1
  4042. movXX mem2, reg1 movXX reg2, mem1}
  4043. begin
  4044. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4045. begin
  4046. { Removes the second statement from
  4047. movXX reg1, mem1/reg2
  4048. movXX mem1/reg2, reg1
  4049. }
  4050. if taicpu(p).oper[0]^.typ=top_reg then
  4051. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4052. { Removes the second statement from
  4053. movXX mem1/reg1, reg2
  4054. movXX reg2, mem1/reg1
  4055. }
  4056. if (taicpu(p).oper[1]^.typ=top_reg) and
  4057. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4058. begin
  4059. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4060. RemoveInstruction(hp1);
  4061. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4062. Result:=true;
  4063. exit;
  4064. end
  4065. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4066. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4067. begin
  4068. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4069. RemoveInstruction(hp1);
  4070. Result:=true;
  4071. exit;
  4072. end;
  4073. end
  4074. end;
  4075. end;
  4076. end;
  4077. end;
  4078. end;
  4079. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4080. var
  4081. hp1 : tai;
  4082. begin
  4083. result:=false;
  4084. { replace
  4085. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4086. MovX %mreg2,%mreg1
  4087. dealloc %mreg2
  4088. by
  4089. <Op>X %mreg2,%mreg1
  4090. ?
  4091. }
  4092. if GetNextInstruction(p,hp1) and
  4093. { we mix single and double opperations here because we assume that the compiler
  4094. generates vmovapd only after double operations and vmovaps only after single operations }
  4095. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4096. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4097. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4098. (taicpu(p).oper[0]^.typ=top_reg) then
  4099. begin
  4100. TransferUsedRegs(TmpUsedRegs);
  4101. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4102. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4103. begin
  4104. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4105. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4106. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4107. RemoveInstruction(hp1);
  4108. result:=true;
  4109. end;
  4110. end;
  4111. end;
  4112. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4113. var
  4114. hp1, p_label, p_dist, hp1_dist: tai;
  4115. JumpLabel, JumpLabel_dist: TAsmLabel;
  4116. FirstValue, SecondValue: TCGInt;
  4117. begin
  4118. Result := False;
  4119. if (taicpu(p).oper[0]^.typ = top_const) and
  4120. (taicpu(p).oper[0]^.val <> -1) then
  4121. begin
  4122. { Convert unsigned maximum constants to -1 to aid optimisation }
  4123. case taicpu(p).opsize of
  4124. S_B:
  4125. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4126. begin
  4127. taicpu(p).oper[0]^.val := -1;
  4128. Result := True;
  4129. Exit;
  4130. end;
  4131. S_W:
  4132. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4133. begin
  4134. taicpu(p).oper[0]^.val := -1;
  4135. Result := True;
  4136. Exit;
  4137. end;
  4138. S_L:
  4139. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4140. begin
  4141. taicpu(p).oper[0]^.val := -1;
  4142. Result := True;
  4143. Exit;
  4144. end;
  4145. {$ifdef x86_64}
  4146. S_Q:
  4147. { Storing anything greater than $7FFFFFFF is not possible so do
  4148. nothing };
  4149. {$endif x86_64}
  4150. else
  4151. InternalError(2021121001);
  4152. end;
  4153. end;
  4154. if GetNextInstruction(p, hp1) and
  4155. TrySwapMovCmp(p, hp1) then
  4156. begin
  4157. Result := True;
  4158. Exit;
  4159. end;
  4160. { Search for:
  4161. test $x,(reg/ref)
  4162. jne @lbl1
  4163. test $y,(reg/ref) (same register or reference)
  4164. jne @lbl1
  4165. Change to:
  4166. test $(x or y),(reg/ref)
  4167. jne @lbl1
  4168. (Note, this doesn't work with je instead of jne)
  4169. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4170. Also search for:
  4171. test $x,(reg/ref)
  4172. je @lbl1
  4173. test $y,(reg/ref)
  4174. je/jne @lbl2
  4175. If (x or y) = x, then the second jump is deterministic
  4176. }
  4177. if (
  4178. (
  4179. (taicpu(p).oper[0]^.typ = top_const) or
  4180. (
  4181. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4182. (taicpu(p).oper[0]^.typ = top_reg) and
  4183. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4184. )
  4185. ) and
  4186. MatchInstruction(hp1, A_JCC, [])
  4187. ) then
  4188. begin
  4189. if (taicpu(p).oper[0]^.typ = top_reg) and
  4190. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4191. FirstValue := -1
  4192. else
  4193. FirstValue := taicpu(p).oper[0]^.val;
  4194. { If we have several test/jne's in a row, it might be the case that
  4195. the second label doesn't go to the same location, but the one
  4196. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4197. so accommodate for this with a while loop.
  4198. }
  4199. hp1_dist := hp1;
  4200. if GetNextInstruction(hp1, p_dist) and
  4201. (p_dist.typ = ait_instruction) and
  4202. (
  4203. (
  4204. (taicpu(p_dist).opcode = A_TEST) and
  4205. (
  4206. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4207. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4208. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4209. )
  4210. ) or
  4211. (
  4212. { cmp 0,%reg = test %reg,%reg }
  4213. (taicpu(p_dist).opcode = A_CMP) and
  4214. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4215. )
  4216. ) and
  4217. { Make sure the destination operands are actually the same }
  4218. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4219. GetNextInstruction(p_dist, hp1_dist) and
  4220. MatchInstruction(hp1_dist, A_JCC, []) then
  4221. begin
  4222. if
  4223. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4224. (
  4225. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4226. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4227. ) then
  4228. SecondValue := -1
  4229. else
  4230. SecondValue := taicpu(p_dist).oper[0]^.val;
  4231. { If both of the TEST constants are identical, delete the second
  4232. TEST that is unnecessary. }
  4233. if (FirstValue = SecondValue) then
  4234. begin
  4235. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4236. RemoveInstruction(p_dist);
  4237. { Don't let the flags register become deallocated and reallocated between the jumps }
  4238. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4239. Result := True;
  4240. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4241. begin
  4242. { Since the second jump's condition is a subset of the first, we
  4243. know it will never branch because the first jump dominates it.
  4244. Get it out of the way now rather than wait for the jump
  4245. optimisations for a speed boost. }
  4246. if IsJumpToLabel(taicpu(hp1_dist)) then
  4247. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4248. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4249. RemoveInstruction(hp1_dist);
  4250. end
  4251. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4252. begin
  4253. { If the inverse of the first condition is a subset of the second,
  4254. the second one will definitely branch if the first one doesn't }
  4255. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4256. MakeUnconditional(taicpu(hp1_dist));
  4257. RemoveDeadCodeAfterJump(hp1_dist);
  4258. end;
  4259. Exit;
  4260. end;
  4261. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4262. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4263. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4264. then the second jump will never branch, so it can also be
  4265. removed regardless of where it goes }
  4266. (
  4267. (FirstValue = -1) or
  4268. (SecondValue = -1) or
  4269. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4270. ) then
  4271. begin
  4272. { Same jump location... can be a register since nothing's changed }
  4273. { If any of the entries are equivalent to test %reg,%reg, then the
  4274. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4275. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4276. if IsJumpToLabel(taicpu(hp1_dist)) then
  4277. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4278. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4279. RemoveInstruction(hp1_dist);
  4280. { Only remove the second test if no jumps or other conditional instructions follow }
  4281. TransferUsedRegs(TmpUsedRegs);
  4282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4283. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4284. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4285. RemoveInstruction(p_dist);
  4286. Result := True;
  4287. Exit;
  4288. end;
  4289. end;
  4290. end;
  4291. { Search for:
  4292. test %reg,%reg
  4293. j(c1) @lbl1
  4294. ...
  4295. @lbl:
  4296. test %reg,%reg (same register)
  4297. j(c2) @lbl2
  4298. If c2 is a subset of c1, change to:
  4299. test %reg,%reg
  4300. j(c1) @lbl2
  4301. (@lbl1 may become a dead label as a result)
  4302. }
  4303. if (taicpu(p).oper[1]^.typ = top_reg) and
  4304. (taicpu(p).oper[0]^.typ = top_reg) and
  4305. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4306. MatchInstruction(hp1, A_JCC, []) and
  4307. IsJumpToLabel(taicpu(hp1)) then
  4308. begin
  4309. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4310. p_label := nil;
  4311. if Assigned(JumpLabel) then
  4312. p_label := getlabelwithsym(JumpLabel);
  4313. if Assigned(p_label) and
  4314. GetNextInstruction(p_label, p_dist) and
  4315. MatchInstruction(p_dist, A_TEST, []) and
  4316. { It's fine if the second test uses smaller sub-registers }
  4317. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4318. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4319. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4320. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4321. GetNextInstruction(p_dist, hp1_dist) and
  4322. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4323. begin
  4324. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4325. if JumpLabel = JumpLabel_dist then
  4326. { This is an infinite loop }
  4327. Exit;
  4328. { Best optimisation when the first condition is a subset (or equal) of the second }
  4329. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4330. begin
  4331. { Any registers used here will already be allocated }
  4332. if Assigned(JumpLabel_dist) then
  4333. JumpLabel_dist.IncRefs;
  4334. if Assigned(JumpLabel) then
  4335. JumpLabel.DecRefs;
  4336. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4337. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4338. Result := True;
  4339. Exit;
  4340. end;
  4341. end;
  4342. end;
  4343. end;
  4344. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4345. var
  4346. hp1, hp2: tai;
  4347. ActiveReg: TRegister;
  4348. OldOffset: asizeint;
  4349. ThisConst: TCGInt;
  4350. function RegDeallocated: Boolean;
  4351. begin
  4352. TransferUsedRegs(TmpUsedRegs);
  4353. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4354. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4355. end;
  4356. begin
  4357. result:=false;
  4358. hp1 := nil;
  4359. { replace
  4360. addX const,%reg1
  4361. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4362. dealloc %reg1
  4363. by
  4364. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4365. }
  4366. if MatchOpType(taicpu(p),top_const,top_reg) then
  4367. begin
  4368. ActiveReg := taicpu(p).oper[1]^.reg;
  4369. { Ensures the entire register was updated }
  4370. if (taicpu(p).opsize >= S_L) and
  4371. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4372. MatchInstruction(hp1,A_LEA,[]) and
  4373. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4374. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4375. (
  4376. { Cover the case where the register in the reference is also the destination register }
  4377. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4378. (
  4379. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4380. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4381. RegDeallocated
  4382. )
  4383. ) then
  4384. begin
  4385. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4386. {$push}
  4387. {$R-}{$Q-}
  4388. { Explicitly disable overflow checking for these offset calculation
  4389. as those do not matter for the final result }
  4390. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4391. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4392. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4393. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4394. {$pop}
  4395. {$ifdef x86_64}
  4396. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4397. begin
  4398. { Overflow; abort }
  4399. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4400. end
  4401. else
  4402. {$endif x86_64}
  4403. begin
  4404. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4405. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4406. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4407. RemoveCurrentP(p, hp1)
  4408. else
  4409. RemoveCurrentP(p);
  4410. result:=true;
  4411. Exit;
  4412. end;
  4413. end;
  4414. if (
  4415. { Save calling GetNextInstructionUsingReg again }
  4416. Assigned(hp1) or
  4417. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4418. ) and
  4419. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4420. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4421. begin
  4422. if taicpu(hp1).oper[0]^.typ = top_const then
  4423. begin
  4424. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4425. if taicpu(hp1).opcode = A_ADD then
  4426. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4427. else
  4428. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4429. Result := True;
  4430. { Handle any overflows }
  4431. case taicpu(p).opsize of
  4432. S_B:
  4433. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4434. S_W:
  4435. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4436. S_L:
  4437. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4438. {$ifdef x86_64}
  4439. S_Q:
  4440. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4441. { Overflow; abort }
  4442. Result := False
  4443. else
  4444. taicpu(p).oper[0]^.val := ThisConst;
  4445. {$endif x86_64}
  4446. else
  4447. InternalError(2021102610);
  4448. end;
  4449. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4450. if Result then
  4451. begin
  4452. if (taicpu(p).oper[0]^.val < 0) and
  4453. (
  4454. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4455. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4456. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4457. ) then
  4458. begin
  4459. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4460. taicpu(p).opcode := A_SUB;
  4461. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4462. end
  4463. else
  4464. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4465. RemoveInstruction(hp1);
  4466. end;
  4467. end
  4468. else
  4469. begin
  4470. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4471. TransferUsedRegs(TmpUsedRegs);
  4472. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4473. hp2 := p;
  4474. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4475. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4476. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4477. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4478. begin
  4479. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4480. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4481. Asml.Remove(p);
  4482. Asml.InsertAfter(p, hp1);
  4483. p := hp1;
  4484. Result := True;
  4485. end;
  4486. end;
  4487. end;
  4488. end;
  4489. end;
  4490. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4491. var
  4492. hp1: tai;
  4493. ref: Integer;
  4494. saveref: treference;
  4495. TempReg: TRegister;
  4496. Multiple: TCGInt;
  4497. begin
  4498. Result:=false;
  4499. { play save and throw an error if LEA uses a seg register prefix,
  4500. this is most likely an error somewhere else }
  4501. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4502. internalerror(2022022001);
  4503. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4504. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4505. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4506. (
  4507. { do not mess with leas accessing the stack pointer
  4508. unless it's a null operation }
  4509. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4510. (
  4511. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4512. (taicpu(p).oper[0]^.ref^.offset = 0)
  4513. )
  4514. ) and
  4515. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4516. begin
  4517. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4518. begin
  4519. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4520. begin
  4521. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4522. taicpu(p).oper[1]^.reg);
  4523. InsertLLItem(p.previous,p.next, hp1);
  4524. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4525. p.free;
  4526. p:=hp1;
  4527. end
  4528. else
  4529. begin
  4530. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4531. RemoveCurrentP(p);
  4532. end;
  4533. Result:=true;
  4534. exit;
  4535. end
  4536. else if (
  4537. { continue to use lea to adjust the stack pointer,
  4538. it is the recommended way, but only if not optimizing for size }
  4539. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4540. (cs_opt_size in current_settings.optimizerswitches)
  4541. ) and
  4542. { If the flags register is in use, don't change the instruction
  4543. to an ADD otherwise this will scramble the flags. [Kit] }
  4544. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4545. ConvertLEA(taicpu(p)) then
  4546. begin
  4547. Result:=true;
  4548. exit;
  4549. end;
  4550. end;
  4551. if GetNextInstruction(p,hp1) and
  4552. (hp1.typ=ait_instruction) then
  4553. begin
  4554. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4555. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4556. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4557. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4558. begin
  4559. TransferUsedRegs(TmpUsedRegs);
  4560. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4561. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4562. begin
  4563. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4564. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4565. RemoveInstruction(hp1);
  4566. result:=true;
  4567. exit;
  4568. end;
  4569. end;
  4570. { changes
  4571. lea <ref1>, reg1
  4572. <op> ...,<ref. with reg1>,...
  4573. to
  4574. <op> ...,<ref1>,... }
  4575. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4576. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4577. not(MatchInstruction(hp1,A_LEA,[])) then
  4578. begin
  4579. { find a reference which uses reg1 }
  4580. 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
  4581. ref:=0
  4582. 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
  4583. ref:=1
  4584. else
  4585. ref:=-1;
  4586. if (ref<>-1) and
  4587. { reg1 must be either the base or the index }
  4588. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4589. begin
  4590. { reg1 can be removed from the reference }
  4591. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4592. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4593. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4594. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4595. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4596. else
  4597. Internalerror(2019111201);
  4598. { check if the can insert all data of the lea into the second instruction }
  4599. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4600. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4601. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4602. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4603. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4604. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4605. { Segment register of p.oper[0]^.ref will be NR_NO already }
  4606. (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4607. {$ifdef x86_64}
  4608. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4609. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4610. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4611. )
  4612. {$endif x86_64}
  4613. then
  4614. begin
  4615. { reg1 might not used by the second instruction after it is remove from the reference }
  4616. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4617. begin
  4618. TransferUsedRegs(TmpUsedRegs);
  4619. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4620. { reg1 is not updated so it might not be used afterwards }
  4621. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4622. begin
  4623. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4624. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4625. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4626. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4627. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4628. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4629. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4630. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4631. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4632. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4633. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4634. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4635. RemoveCurrentP(p, hp1);
  4636. result:=true;
  4637. exit;
  4638. end
  4639. end;
  4640. end;
  4641. { recover }
  4642. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4643. end;
  4644. end;
  4645. end;
  4646. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4647. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4648. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4649. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4650. begin
  4651. { Check common LEA/LEA conditions }
  4652. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4653. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4654. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4655. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4656. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4657. { Since we're merging two LEA instructions, the segment registers don't matter }
  4658. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4659. (
  4660. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4661. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4662. ) and (
  4663. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4664. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4665. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4666. ) then
  4667. begin
  4668. { changes
  4669. lea (regX,scale), reg1
  4670. lea offset(reg1,reg1), reg1
  4671. to
  4672. lea offset(regX,scale*2), reg1
  4673. and
  4674. lea (regX,scale1), reg1
  4675. lea offset(reg1,scale2), reg1
  4676. to
  4677. lea offset(regX,scale1*scale2), reg1
  4678. ... so long as the final scale does not exceed 8
  4679. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4680. }
  4681. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4682. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4683. (
  4684. (
  4685. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4686. ) or (
  4687. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4688. (
  4689. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4690. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4691. )
  4692. )
  4693. ) and (
  4694. (
  4695. { lea (reg1,scale2), reg1 variant }
  4696. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4697. (
  4698. (
  4699. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4700. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4701. ) or (
  4702. { lea (regX,regX), reg1 variant }
  4703. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4704. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4705. )
  4706. )
  4707. ) or (
  4708. { lea (reg1,reg1), reg1 variant }
  4709. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4710. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4711. )
  4712. ) then
  4713. begin
  4714. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4715. { Make everything homogeneous to make calculations easier }
  4716. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4717. begin
  4718. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4719. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4720. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4721. else
  4722. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4723. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4724. end;
  4725. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4726. begin
  4727. { Just to prevent miscalculations }
  4728. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4729. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4730. else
  4731. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4732. end
  4733. else
  4734. begin
  4735. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4736. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4737. end;
  4738. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4739. RemoveCurrentP(p);
  4740. result:=true;
  4741. exit;
  4742. end
  4743. { changes
  4744. lea offset1(regX), reg1
  4745. lea offset2(reg1), reg1
  4746. to
  4747. lea offset1+offset2(regX), reg1 }
  4748. else if
  4749. (
  4750. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4751. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4752. ) or (
  4753. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4754. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4755. (
  4756. (
  4757. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4758. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4759. ) or (
  4760. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4761. (
  4762. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4763. (
  4764. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4765. (
  4766. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4767. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4768. )
  4769. )
  4770. )
  4771. )
  4772. )
  4773. ) then
  4774. begin
  4775. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4776. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4777. begin
  4778. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4779. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4780. { if the register is used as index and base, we have to increase for base as well
  4781. and adapt base }
  4782. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4783. begin
  4784. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4785. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4786. end;
  4787. end
  4788. else
  4789. begin
  4790. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4791. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4792. end;
  4793. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4794. begin
  4795. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4796. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4797. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4798. end;
  4799. RemoveCurrentP(p);
  4800. result:=true;
  4801. exit;
  4802. end;
  4803. end;
  4804. { Change:
  4805. leal/q $x(%reg1),%reg2
  4806. ...
  4807. shll/q $y,%reg2
  4808. To:
  4809. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4810. }
  4811. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4812. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4813. (taicpu(hp1).oper[0]^.val <= 3) then
  4814. begin
  4815. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4816. TransferUsedRegs(TmpUsedRegs);
  4817. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4818. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4819. if
  4820. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4821. (this works even if scalefactor is zero) }
  4822. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4823. { Ensure offset doesn't go out of bounds }
  4824. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4825. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4826. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4827. (
  4828. (
  4829. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4830. (
  4831. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4832. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4833. (
  4834. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4835. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4836. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4837. )
  4838. )
  4839. ) or (
  4840. (
  4841. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4842. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4843. ) and
  4844. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4845. )
  4846. ) then
  4847. begin
  4848. repeat
  4849. with taicpu(p).oper[0]^.ref^ do
  4850. begin
  4851. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4852. if index = base then
  4853. begin
  4854. if Multiple > 4 then
  4855. { Optimisation will no longer work because resultant
  4856. scale factor will exceed 8 }
  4857. Break;
  4858. base := NR_NO;
  4859. scalefactor := 2;
  4860. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4861. end
  4862. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4863. begin
  4864. { Scale factor only works on the index register }
  4865. index := base;
  4866. base := NR_NO;
  4867. end;
  4868. { For safety }
  4869. if scalefactor <= 1 then
  4870. begin
  4871. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4872. scalefactor := Multiple;
  4873. end
  4874. else
  4875. begin
  4876. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4877. scalefactor := scalefactor * Multiple;
  4878. end;
  4879. offset := offset * Multiple;
  4880. end;
  4881. RemoveInstruction(hp1);
  4882. Result := True;
  4883. Exit;
  4884. { This repeat..until loop exists for the benefit of Break }
  4885. until True;
  4886. end;
  4887. end;
  4888. end;
  4889. end;
  4890. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4891. var
  4892. hp1 : tai;
  4893. begin
  4894. DoSubAddOpt := False;
  4895. if taicpu(p).oper[0]^.typ <> top_const then
  4896. { Should have been confirmed before calling }
  4897. InternalError(2021102601);
  4898. if GetLastInstruction(p, hp1) and
  4899. (hp1.typ = ait_instruction) and
  4900. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4901. case taicpu(hp1).opcode Of
  4902. A_DEC:
  4903. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4904. begin
  4905. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4906. RemoveInstruction(hp1);
  4907. end;
  4908. A_SUB:
  4909. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4910. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4911. begin
  4912. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4913. RemoveInstruction(hp1);
  4914. end;
  4915. A_ADD:
  4916. begin
  4917. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4918. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4919. begin
  4920. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4921. RemoveInstruction(hp1);
  4922. if (taicpu(p).oper[0]^.val = 0) then
  4923. begin
  4924. hp1 := tai(p.next);
  4925. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4926. if not GetLastInstruction(hp1, p) then
  4927. p := hp1;
  4928. DoSubAddOpt := True;
  4929. end
  4930. end;
  4931. end;
  4932. else
  4933. ;
  4934. end;
  4935. end;
  4936. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4937. begin
  4938. Result := False;
  4939. if UpdateTmpUsedRegs then
  4940. TransferUsedRegs(TmpUsedRegs);
  4941. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4942. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4943. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4944. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4945. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4946. (
  4947. (
  4948. (taicpu(hp1).opcode = A_TEST)
  4949. ) or (
  4950. (taicpu(hp1).opcode = A_CMP) and
  4951. { A sanity check more than anything }
  4952. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4953. )
  4954. ) then
  4955. begin
  4956. { change
  4957. mov mem, %reg
  4958. cmp/test x, %reg / test %reg,%reg
  4959. (reg deallocated)
  4960. to
  4961. cmp/test x, mem / cmp 0, mem
  4962. }
  4963. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4964. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4965. begin
  4966. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4967. if (taicpu(hp1).opcode = A_TEST) and
  4968. (
  4969. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4970. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4971. ) then
  4972. begin
  4973. taicpu(hp1).opcode := A_CMP;
  4974. taicpu(hp1).loadconst(0, 0);
  4975. end;
  4976. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4977. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4978. RemoveCurrentP(p, hp1);
  4979. Result := True;
  4980. Exit;
  4981. end;
  4982. end;
  4983. end;
  4984. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  4985. var
  4986. hp2, hp3, hp4, hp5, hp6: tai;
  4987. ThisReg: TRegister;
  4988. JumpLoc: TAsmLabel;
  4989. begin
  4990. Result := False;
  4991. {
  4992. Convert:
  4993. j<c> .L1
  4994. .L2:
  4995. mov 1,reg
  4996. jmp .L3 (or ret, although it might not be a RET yet)
  4997. .L1:
  4998. mov 0,reg
  4999. jmp .L3 (or ret)
  5000. ( As long as .L3 <> .L1 or .L2)
  5001. To:
  5002. mov 0,reg
  5003. set<not(c)> reg
  5004. jmp .L3 (or ret)
  5005. .L2:
  5006. mov 1,reg
  5007. jmp .L3 (or ret)
  5008. .L1:
  5009. mov 0,reg
  5010. jmp .L3 (or ret)
  5011. }
  5012. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5013. Exit;
  5014. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5015. if GetNextInstruction(hp_label, hp2) and
  5016. MatchInstruction(hp2,A_MOV,[]) and
  5017. (taicpu(hp2).oper[0]^.typ = top_const) and
  5018. (
  5019. (
  5020. (taicpu(hp2).oper[1]^.typ = top_reg)
  5021. {$ifdef i386}
  5022. { Under i386, ESI, EDI, EBP and ESP
  5023. don't have an 8-bit representation }
  5024. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5025. {$endif i386}
  5026. ) or (
  5027. {$ifdef i386}
  5028. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5029. {$endif i386}
  5030. (taicpu(hp2).opsize = S_B)
  5031. )
  5032. ) and
  5033. GetNextInstruction(hp2, hp3) and
  5034. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5035. (
  5036. (taicpu(hp3).opcode=A_RET) or
  5037. (
  5038. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5039. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5040. )
  5041. ) and
  5042. GetNextInstruction(hp3, hp4) and
  5043. SkipAligns(hp4, hp4) and
  5044. (hp4.typ=ait_label) and
  5045. (tai_label(hp4).labsym=JumpLoc) and
  5046. (
  5047. not (cs_opt_size in current_settings.optimizerswitches) or
  5048. { If the initial jump is the label's only reference, then it will
  5049. become a dead label if the other conditions are met and hence
  5050. remove at least 2 instructions, including a jump }
  5051. (JumpLoc.getrefs = 1)
  5052. ) and
  5053. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5054. that will be optimised out }
  5055. GetNextInstruction(hp4, hp5) and
  5056. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5057. (taicpu(hp5).oper[0]^.typ = top_const) and
  5058. (
  5059. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5060. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5061. ) and
  5062. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5063. GetNextInstruction(hp5,hp6) and
  5064. (
  5065. (hp6.typ<>ait_label) or
  5066. SkipLabels(hp6, hp6)
  5067. ) and
  5068. (hp6.typ=ait_instruction) then
  5069. begin
  5070. { First, let's look at the two jumps that are hp3 and hp6 }
  5071. if not
  5072. (
  5073. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5074. (
  5075. (taicpu(hp6).opcode=A_RET) or
  5076. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5077. )
  5078. ) then
  5079. { If condition is False, then the JMP/RET instructions matched conventionally }
  5080. begin
  5081. { See if one of the jumps can be instantly converted into a RET }
  5082. if (taicpu(hp3).opcode=A_JMP) then
  5083. begin
  5084. { Reuse hp5 }
  5085. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5086. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5087. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5088. Exit;
  5089. if MatchInstruction(hp5, A_RET, []) then
  5090. begin
  5091. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5092. ConvertJumpToRET(hp3, hp5);
  5093. Result := True;
  5094. end
  5095. else
  5096. Exit;
  5097. end;
  5098. if (taicpu(hp6).opcode=A_JMP) then
  5099. begin
  5100. { Reuse hp5 }
  5101. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5102. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5103. Exit;
  5104. if MatchInstruction(hp5, A_RET, []) then
  5105. begin
  5106. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5107. ConvertJumpToRET(hp6, hp5);
  5108. Result := True;
  5109. end
  5110. else
  5111. Exit;
  5112. end;
  5113. if not
  5114. (
  5115. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5116. (
  5117. (taicpu(hp6).opcode=A_RET) or
  5118. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5119. )
  5120. ) then
  5121. { Still doesn't match }
  5122. Exit;
  5123. end;
  5124. if (taicpu(hp2).oper[0]^.val = 1) then
  5125. begin
  5126. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5127. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5128. end
  5129. else
  5130. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5131. if taicpu(hp2).opsize=S_B then
  5132. begin
  5133. if taicpu(hp2).oper[1]^.typ = top_reg then
  5134. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5135. else
  5136. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5137. hp2 := p;
  5138. end
  5139. else
  5140. begin
  5141. { Will be a register because the size can't be S_B otherwise }
  5142. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5143. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5144. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5145. { Inserting it right before p will guarantee that the flags are also tracked }
  5146. Asml.InsertBefore(hp2, p);
  5147. end;
  5148. taicpu(hp4).condition:=taicpu(p).condition;
  5149. asml.InsertBefore(hp4, hp2);
  5150. JumpLoc.decrefs;
  5151. if taicpu(hp3).opcode = A_JMP then
  5152. begin
  5153. MakeUnconditional(taicpu(p));
  5154. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5155. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5156. end
  5157. else
  5158. begin
  5159. taicpu(p).condition := C_None;
  5160. taicpu(p).opcode := A_RET;
  5161. taicpu(p).clearop(0);
  5162. taicpu(p).ops := 0;
  5163. end;
  5164. if (JumpLoc.getrefs = 0) then
  5165. RemoveDeadCodeAfterJump(hp3);
  5166. Result:=true;
  5167. exit;
  5168. end;
  5169. end;
  5170. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5171. var
  5172. hp1, hp2: tai;
  5173. ActiveReg: TRegister;
  5174. OldOffset: asizeint;
  5175. ThisConst: TCGInt;
  5176. function RegDeallocated: Boolean;
  5177. begin
  5178. TransferUsedRegs(TmpUsedRegs);
  5179. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5180. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5181. end;
  5182. begin
  5183. Result:=false;
  5184. hp1 := nil;
  5185. { replace
  5186. subX const,%reg1
  5187. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5188. dealloc %reg1
  5189. by
  5190. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5191. }
  5192. if MatchOpType(taicpu(p),top_const,top_reg) then
  5193. begin
  5194. ActiveReg := taicpu(p).oper[1]^.reg;
  5195. { Ensures the entire register was updated }
  5196. if (taicpu(p).opsize >= S_L) and
  5197. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5198. MatchInstruction(hp1,A_LEA,[]) and
  5199. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5200. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5201. (
  5202. { Cover the case where the register in the reference is also the destination register }
  5203. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5204. (
  5205. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5206. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5207. RegDeallocated
  5208. )
  5209. ) then
  5210. begin
  5211. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5212. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5213. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5214. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5215. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5216. {$ifdef x86_64}
  5217. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5218. begin
  5219. { Overflow; abort }
  5220. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5221. end
  5222. else
  5223. {$endif x86_64}
  5224. begin
  5225. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5226. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5227. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5228. RemoveCurrentP(p, hp1)
  5229. else
  5230. RemoveCurrentP(p);
  5231. result:=true;
  5232. Exit;
  5233. end;
  5234. end;
  5235. if (
  5236. { Save calling GetNextInstructionUsingReg again }
  5237. Assigned(hp1) or
  5238. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5239. ) and
  5240. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5241. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5242. begin
  5243. if taicpu(hp1).oper[0]^.typ = top_const then
  5244. begin
  5245. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5246. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5247. Result := True;
  5248. { Handle any overflows }
  5249. case taicpu(p).opsize of
  5250. S_B:
  5251. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5252. S_W:
  5253. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5254. S_L:
  5255. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5256. {$ifdef x86_64}
  5257. S_Q:
  5258. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5259. { Overflow; abort }
  5260. Result := False
  5261. else
  5262. taicpu(p).oper[0]^.val := ThisConst;
  5263. {$endif x86_64}
  5264. else
  5265. InternalError(2021102610);
  5266. end;
  5267. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5268. if Result then
  5269. begin
  5270. if (taicpu(p).oper[0]^.val < 0) and
  5271. (
  5272. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5273. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5274. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5275. ) then
  5276. begin
  5277. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5278. taicpu(p).opcode := A_SUB;
  5279. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5280. end
  5281. else
  5282. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5283. RemoveInstruction(hp1);
  5284. end;
  5285. end
  5286. else
  5287. begin
  5288. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5289. TransferUsedRegs(TmpUsedRegs);
  5290. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5291. hp2 := p;
  5292. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5293. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5294. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5295. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5296. begin
  5297. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5298. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5299. Asml.Remove(p);
  5300. Asml.InsertAfter(p, hp1);
  5301. p := hp1;
  5302. Result := True;
  5303. Exit;
  5304. end;
  5305. end;
  5306. end;
  5307. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5308. { * change "sub/add const1, reg" or "dec reg" followed by
  5309. "sub const2, reg" to one "sub ..., reg" }
  5310. {$ifdef i386}
  5311. if (taicpu(p).oper[0]^.val = 2) and
  5312. (ActiveReg = NR_ESP) and
  5313. { Don't do the sub/push optimization if the sub }
  5314. { comes from setting up the stack frame (JM) }
  5315. (not(GetLastInstruction(p,hp1)) or
  5316. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5317. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5318. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5319. begin
  5320. hp1 := tai(p.next);
  5321. while Assigned(hp1) and
  5322. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5323. not RegReadByInstruction(NR_ESP,hp1) and
  5324. not RegModifiedByInstruction(NR_ESP,hp1) do
  5325. hp1 := tai(hp1.next);
  5326. if Assigned(hp1) and
  5327. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5328. begin
  5329. taicpu(hp1).changeopsize(S_L);
  5330. if taicpu(hp1).oper[0]^.typ=top_reg then
  5331. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5332. hp1 := tai(p.next);
  5333. RemoveCurrentp(p, hp1);
  5334. Result:=true;
  5335. exit;
  5336. end;
  5337. end;
  5338. {$endif i386}
  5339. if DoSubAddOpt(p) then
  5340. Result:=true;
  5341. end;
  5342. end;
  5343. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5344. var
  5345. TmpBool1,TmpBool2 : Boolean;
  5346. tmpref : treference;
  5347. hp1,hp2: tai;
  5348. mask: tcgint;
  5349. begin
  5350. Result:=false;
  5351. { All these optimisations work on "shl/sal const,%reg" }
  5352. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5353. Exit;
  5354. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5355. (taicpu(p).oper[0]^.val <= 3) then
  5356. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5357. begin
  5358. { should we check the next instruction? }
  5359. TmpBool1 := True;
  5360. { have we found an add/sub which could be
  5361. integrated in the lea? }
  5362. TmpBool2 := False;
  5363. reference_reset(tmpref,2,[]);
  5364. TmpRef.index := taicpu(p).oper[1]^.reg;
  5365. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5366. while TmpBool1 and
  5367. GetNextInstruction(p, hp1) and
  5368. (tai(hp1).typ = ait_instruction) and
  5369. ((((taicpu(hp1).opcode = A_ADD) or
  5370. (taicpu(hp1).opcode = A_SUB)) and
  5371. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5372. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5373. (((taicpu(hp1).opcode = A_INC) or
  5374. (taicpu(hp1).opcode = A_DEC)) and
  5375. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5376. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5377. ((taicpu(hp1).opcode = A_LEA) and
  5378. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5379. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5380. (not GetNextInstruction(hp1,hp2) or
  5381. not instrReadsFlags(hp2)) Do
  5382. begin
  5383. TmpBool1 := False;
  5384. if taicpu(hp1).opcode=A_LEA then
  5385. begin
  5386. if (TmpRef.base = NR_NO) and
  5387. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5388. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5389. { Segment register isn't a concern here }
  5390. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5391. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5392. begin
  5393. TmpBool1 := True;
  5394. TmpBool2 := True;
  5395. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5396. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5397. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5398. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5399. RemoveInstruction(hp1);
  5400. end
  5401. end
  5402. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5403. begin
  5404. TmpBool1 := True;
  5405. TmpBool2 := True;
  5406. case taicpu(hp1).opcode of
  5407. A_ADD:
  5408. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5409. A_SUB:
  5410. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5411. else
  5412. internalerror(2019050536);
  5413. end;
  5414. RemoveInstruction(hp1);
  5415. end
  5416. else
  5417. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5418. (((taicpu(hp1).opcode = A_ADD) and
  5419. (TmpRef.base = NR_NO)) or
  5420. (taicpu(hp1).opcode = A_INC) or
  5421. (taicpu(hp1).opcode = A_DEC)) then
  5422. begin
  5423. TmpBool1 := True;
  5424. TmpBool2 := True;
  5425. case taicpu(hp1).opcode of
  5426. A_ADD:
  5427. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5428. A_INC:
  5429. inc(TmpRef.offset);
  5430. A_DEC:
  5431. dec(TmpRef.offset);
  5432. else
  5433. internalerror(2019050535);
  5434. end;
  5435. RemoveInstruction(hp1);
  5436. end;
  5437. end;
  5438. if TmpBool2
  5439. {$ifndef x86_64}
  5440. or
  5441. ((current_settings.optimizecputype < cpu_Pentium2) and
  5442. (taicpu(p).oper[0]^.val <= 3) and
  5443. not(cs_opt_size in current_settings.optimizerswitches))
  5444. {$endif x86_64}
  5445. then
  5446. begin
  5447. if not(TmpBool2) and
  5448. (taicpu(p).oper[0]^.val=1) then
  5449. begin
  5450. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5451. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5452. end
  5453. else
  5454. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5455. taicpu(p).oper[1]^.reg);
  5456. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5457. InsertLLItem(p.previous, p.next, hp1);
  5458. p.free;
  5459. p := hp1;
  5460. end;
  5461. end
  5462. {$ifndef x86_64}
  5463. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5464. begin
  5465. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5466. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5467. (unlike shl, which is only Tairable in the U pipe) }
  5468. if taicpu(p).oper[0]^.val=1 then
  5469. begin
  5470. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5471. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5472. InsertLLItem(p.previous, p.next, hp1);
  5473. p.free;
  5474. p := hp1;
  5475. end
  5476. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5477. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5478. else if (taicpu(p).opsize = S_L) and
  5479. (taicpu(p).oper[0]^.val<= 3) then
  5480. begin
  5481. reference_reset(tmpref,2,[]);
  5482. TmpRef.index := taicpu(p).oper[1]^.reg;
  5483. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5484. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5485. InsertLLItem(p.previous, p.next, hp1);
  5486. p.free;
  5487. p := hp1;
  5488. end;
  5489. end
  5490. {$endif x86_64}
  5491. else if
  5492. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5493. (
  5494. (
  5495. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5496. SetAndTest(hp1, hp2)
  5497. {$ifdef x86_64}
  5498. ) or
  5499. (
  5500. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5501. GetNextInstruction(hp1, hp2) and
  5502. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5503. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5504. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5505. {$endif x86_64}
  5506. )
  5507. ) and
  5508. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5509. begin
  5510. { Change:
  5511. shl x, %reg1
  5512. mov -(1<<x), %reg2
  5513. and %reg2, %reg1
  5514. Or:
  5515. shl x, %reg1
  5516. and -(1<<x), %reg1
  5517. To just:
  5518. shl x, %reg1
  5519. Since the and operation only zeroes bits that are already zero from the shl operation
  5520. }
  5521. case taicpu(p).oper[0]^.val of
  5522. 8:
  5523. mask:=$FFFFFFFFFFFFFF00;
  5524. 16:
  5525. mask:=$FFFFFFFFFFFF0000;
  5526. 32:
  5527. mask:=$FFFFFFFF00000000;
  5528. 63:
  5529. { Constant pre-calculated to prevent overflow errors with Int64 }
  5530. mask:=$8000000000000000;
  5531. else
  5532. begin
  5533. if taicpu(p).oper[0]^.val >= 64 then
  5534. { Shouldn't happen realistically, since the register
  5535. is guaranteed to be set to zero at this point }
  5536. mask := 0
  5537. else
  5538. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5539. end;
  5540. end;
  5541. if taicpu(hp1).oper[0]^.val = mask then
  5542. begin
  5543. { Everything checks out, perform the optimisation, as long as
  5544. the FLAGS register isn't being used}
  5545. TransferUsedRegs(TmpUsedRegs);
  5546. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5547. {$ifdef x86_64}
  5548. if (hp1 <> hp2) then
  5549. begin
  5550. { "shl/mov/and" version }
  5551. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5552. { Don't do the optimisation if the FLAGS register is in use }
  5553. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5554. begin
  5555. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5556. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5557. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5558. begin
  5559. RemoveInstruction(hp1);
  5560. Result := True;
  5561. end;
  5562. { Only set Result to True if the 'mov' instruction was removed }
  5563. RemoveInstruction(hp2);
  5564. end;
  5565. end
  5566. else
  5567. {$endif x86_64}
  5568. begin
  5569. { "shl/and" version }
  5570. { Don't do the optimisation if the FLAGS register is in use }
  5571. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5572. begin
  5573. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5574. RemoveInstruction(hp1);
  5575. Result := True;
  5576. end;
  5577. end;
  5578. Exit;
  5579. end
  5580. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5581. begin
  5582. { Even if the mask doesn't allow for its removal, we might be
  5583. able to optimise the mask for the "shl/and" version, which
  5584. may permit other peephole optimisations }
  5585. {$ifdef DEBUG_AOPTCPU}
  5586. mask := taicpu(hp1).oper[0]^.val and mask;
  5587. if taicpu(hp1).oper[0]^.val <> mask then
  5588. begin
  5589. DebugMsg(
  5590. SPeepholeOptimization +
  5591. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5592. ' to $' + debug_tostr(mask) +
  5593. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5594. taicpu(hp1).oper[0]^.val := mask;
  5595. end;
  5596. {$else DEBUG_AOPTCPU}
  5597. { If debugging is off, just set the operand even if it's the same }
  5598. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5599. {$endif DEBUG_AOPTCPU}
  5600. end;
  5601. end;
  5602. {
  5603. change
  5604. shl/sal const,reg
  5605. <op> ...(...,reg,1),...
  5606. into
  5607. <op> ...(...,reg,1 shl const),...
  5608. if const in 1..3
  5609. }
  5610. if MatchOpType(taicpu(p), top_const, top_reg) and
  5611. (taicpu(p).oper[0]^.val in [1..3]) and
  5612. GetNextInstruction(p, hp1) and
  5613. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5614. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5615. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5616. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5617. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5618. begin
  5619. TransferUsedRegs(TmpUsedRegs);
  5620. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5621. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5622. begin
  5623. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5624. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5625. RemoveCurrentP(p);
  5626. Result:=true;
  5627. end;
  5628. end;
  5629. end;
  5630. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5631. var
  5632. CurrentRef: TReference;
  5633. FullReg: TRegister;
  5634. hp1, hp2: tai;
  5635. begin
  5636. Result := False;
  5637. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5638. Exit;
  5639. { We assume you've checked if the operand is actually a reference by
  5640. this point. If it isn't, you'll most likely get an access violation }
  5641. CurrentRef := first_mov.oper[1]^.ref^;
  5642. { Memory must be aligned }
  5643. if (CurrentRef.offset mod 4) <> 0 then
  5644. Exit;
  5645. Inc(CurrentRef.offset);
  5646. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5647. if MatchOperand(second_mov.oper[0]^, 0) and
  5648. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5649. GetNextInstruction(second_mov, hp1) and
  5650. (hp1.typ = ait_instruction) and
  5651. (taicpu(hp1).opcode = A_MOV) and
  5652. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5653. (taicpu(hp1).oper[0]^.val = 0) then
  5654. begin
  5655. Inc(CurrentRef.offset);
  5656. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5657. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5658. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5659. begin
  5660. case taicpu(hp1).opsize of
  5661. S_B:
  5662. if GetNextInstruction(hp1, hp2) and
  5663. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5664. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5665. (taicpu(hp2).oper[0]^.val = 0) then
  5666. begin
  5667. Inc(CurrentRef.offset);
  5668. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5669. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5670. (taicpu(hp2).opsize = S_B) then
  5671. begin
  5672. RemoveInstruction(hp1);
  5673. RemoveInstruction(hp2);
  5674. first_mov.opsize := S_L;
  5675. if first_mov.oper[0]^.typ = top_reg then
  5676. begin
  5677. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5678. { Reuse second_mov as a MOVZX instruction }
  5679. second_mov.opcode := A_MOVZX;
  5680. second_mov.opsize := S_BL;
  5681. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5682. second_mov.loadreg(1, FullReg);
  5683. first_mov.oper[0]^.reg := FullReg;
  5684. asml.Remove(second_mov);
  5685. asml.InsertBefore(second_mov, first_mov);
  5686. end
  5687. else
  5688. { It's a value }
  5689. begin
  5690. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5691. RemoveInstruction(second_mov);
  5692. end;
  5693. Result := True;
  5694. Exit;
  5695. end;
  5696. end;
  5697. S_W:
  5698. begin
  5699. RemoveInstruction(hp1);
  5700. first_mov.opsize := S_L;
  5701. if first_mov.oper[0]^.typ = top_reg then
  5702. begin
  5703. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5704. { Reuse second_mov as a MOVZX instruction }
  5705. second_mov.opcode := A_MOVZX;
  5706. second_mov.opsize := S_BL;
  5707. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5708. second_mov.loadreg(1, FullReg);
  5709. first_mov.oper[0]^.reg := FullReg;
  5710. asml.Remove(second_mov);
  5711. asml.InsertBefore(second_mov, first_mov);
  5712. end
  5713. else
  5714. { It's a value }
  5715. begin
  5716. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5717. RemoveInstruction(second_mov);
  5718. end;
  5719. Result := True;
  5720. Exit;
  5721. end;
  5722. else
  5723. ;
  5724. end;
  5725. end;
  5726. end;
  5727. end;
  5728. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5729. { returns true if a "continue" should be done after this optimization }
  5730. var
  5731. hp1, hp2: tai;
  5732. begin
  5733. Result := false;
  5734. if MatchOpType(taicpu(p),top_ref) and
  5735. GetNextInstruction(p, hp1) and
  5736. (hp1.typ = ait_instruction) and
  5737. (((taicpu(hp1).opcode = A_FLD) and
  5738. (taicpu(p).opcode = A_FSTP)) or
  5739. ((taicpu(p).opcode = A_FISTP) and
  5740. (taicpu(hp1).opcode = A_FILD))) and
  5741. MatchOpType(taicpu(hp1),top_ref) and
  5742. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5743. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5744. begin
  5745. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5746. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5747. GetNextInstruction(hp1, hp2) and
  5748. (hp2.typ = ait_instruction) and
  5749. IsExitCode(hp2) and
  5750. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5751. not(assigned(current_procinfo.procdef.funcretsym) and
  5752. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5753. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5754. begin
  5755. RemoveInstruction(hp1);
  5756. RemoveCurrentP(p, hp2);
  5757. RemoveLastDeallocForFuncRes(p);
  5758. Result := true;
  5759. end
  5760. else
  5761. { we can do this only in fast math mode as fstp is rounding ...
  5762. ... still disabled as it breaks the compiler and/or rtl }
  5763. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5764. { ... or if another fstp equal to the first one follows }
  5765. (GetNextInstruction(hp1,hp2) and
  5766. (hp2.typ = ait_instruction) and
  5767. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5768. (taicpu(p).opsize=taicpu(hp2).opsize))
  5769. ) and
  5770. { fst can't store an extended/comp value }
  5771. (taicpu(p).opsize <> S_FX) and
  5772. (taicpu(p).opsize <> S_IQ) then
  5773. begin
  5774. if (taicpu(p).opcode = A_FSTP) then
  5775. taicpu(p).opcode := A_FST
  5776. else
  5777. taicpu(p).opcode := A_FIST;
  5778. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5779. RemoveInstruction(hp1);
  5780. end;
  5781. end;
  5782. end;
  5783. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5784. var
  5785. hp1, hp2: tai;
  5786. begin
  5787. result:=false;
  5788. if MatchOpType(taicpu(p),top_reg) and
  5789. GetNextInstruction(p, hp1) and
  5790. (hp1.typ = Ait_Instruction) and
  5791. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5792. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5793. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5794. { change to
  5795. fld reg fxxx reg,st
  5796. fxxxp st, st1 (hp1)
  5797. Remark: non commutative operations must be reversed!
  5798. }
  5799. begin
  5800. case taicpu(hp1).opcode Of
  5801. A_FMULP,A_FADDP,
  5802. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5803. begin
  5804. case taicpu(hp1).opcode Of
  5805. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5806. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5807. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5808. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5809. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5810. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5811. else
  5812. internalerror(2019050534);
  5813. end;
  5814. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5815. taicpu(hp1).oper[1]^.reg := NR_ST;
  5816. RemoveCurrentP(p, hp1);
  5817. Result:=true;
  5818. exit;
  5819. end;
  5820. else
  5821. ;
  5822. end;
  5823. end
  5824. else
  5825. if MatchOpType(taicpu(p),top_ref) and
  5826. GetNextInstruction(p, hp2) and
  5827. (hp2.typ = Ait_Instruction) and
  5828. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5829. (taicpu(p).opsize in [S_FS, S_FL]) and
  5830. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5831. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5832. if GetLastInstruction(p, hp1) and
  5833. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5834. MatchOpType(taicpu(hp1),top_ref) and
  5835. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5836. if ((taicpu(hp2).opcode = A_FMULP) or
  5837. (taicpu(hp2).opcode = A_FADDP)) then
  5838. { change to
  5839. fld/fst mem1 (hp1) fld/fst mem1
  5840. fld mem1 (p) fadd/
  5841. faddp/ fmul st, st
  5842. fmulp st, st1 (hp2) }
  5843. begin
  5844. RemoveCurrentP(p, hp1);
  5845. if (taicpu(hp2).opcode = A_FADDP) then
  5846. taicpu(hp2).opcode := A_FADD
  5847. else
  5848. taicpu(hp2).opcode := A_FMUL;
  5849. taicpu(hp2).oper[1]^.reg := NR_ST;
  5850. end
  5851. else
  5852. { change to
  5853. fld/fst mem1 (hp1) fld/fst mem1
  5854. fld mem1 (p) fld st}
  5855. begin
  5856. taicpu(p).changeopsize(S_FL);
  5857. taicpu(p).loadreg(0,NR_ST);
  5858. end
  5859. else
  5860. begin
  5861. case taicpu(hp2).opcode Of
  5862. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5863. { change to
  5864. fld/fst mem1 (hp1) fld/fst mem1
  5865. fld mem2 (p) fxxx mem2
  5866. fxxxp st, st1 (hp2) }
  5867. begin
  5868. case taicpu(hp2).opcode Of
  5869. A_FADDP: taicpu(p).opcode := A_FADD;
  5870. A_FMULP: taicpu(p).opcode := A_FMUL;
  5871. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5872. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5873. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5874. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5875. else
  5876. internalerror(2019050533);
  5877. end;
  5878. RemoveInstruction(hp2);
  5879. end
  5880. else
  5881. ;
  5882. end
  5883. end
  5884. end;
  5885. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5886. begin
  5887. Result := condition_in(cond1, cond2) or
  5888. { Not strictly subsets due to the actual flags checked, but because we're
  5889. comparing integers, E is a subset of AE and GE and their aliases }
  5890. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5891. end;
  5892. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5893. var
  5894. v: TCGInt;
  5895. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5896. FirstMatch: Boolean;
  5897. NewReg: TRegister;
  5898. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5899. begin
  5900. Result:=false;
  5901. { All these optimisations need a next instruction }
  5902. if not GetNextInstruction(p, hp1) then
  5903. Exit;
  5904. { Search for:
  5905. cmp ###,###
  5906. j(c1) @lbl1
  5907. ...
  5908. @lbl:
  5909. cmp ###.### (same comparison as above)
  5910. j(c2) @lbl2
  5911. If c1 is a subset of c2, change to:
  5912. cmp ###,###
  5913. j(c2) @lbl2
  5914. (@lbl1 may become a dead label as a result)
  5915. }
  5916. { Also handle cases where there are multiple jumps in a row }
  5917. p_jump := hp1;
  5918. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5919. begin
  5920. if IsJumpToLabel(taicpu(p_jump)) then
  5921. begin
  5922. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5923. p_label := nil;
  5924. if Assigned(JumpLabel) then
  5925. p_label := getlabelwithsym(JumpLabel);
  5926. if Assigned(p_label) and
  5927. GetNextInstruction(p_label, p_dist) and
  5928. MatchInstruction(p_dist, A_CMP, []) and
  5929. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5930. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5931. GetNextInstruction(p_dist, hp1_dist) and
  5932. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5933. begin
  5934. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5935. if JumpLabel = JumpLabel_dist then
  5936. { This is an infinite loop }
  5937. Exit;
  5938. { Best optimisation when the first condition is a subset (or equal) of the second }
  5939. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5940. begin
  5941. { Any registers used here will already be allocated }
  5942. if Assigned(JumpLabel_dist) then
  5943. JumpLabel_dist.IncRefs;
  5944. if Assigned(JumpLabel) then
  5945. JumpLabel.DecRefs;
  5946. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5947. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5948. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5949. Result := True;
  5950. { Don't exit yet. Since p and p_jump haven't actually been
  5951. removed, we can check for more on this iteration }
  5952. end
  5953. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5954. GetNextInstruction(hp1_dist, hp1_label) and
  5955. SkipAligns(hp1_label, hp1_label) and
  5956. (hp1_label.typ = ait_label) then
  5957. begin
  5958. JumpLabel_far := tai_label(hp1_label).labsym;
  5959. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5960. { This is an infinite loop }
  5961. Exit;
  5962. if Assigned(JumpLabel_far) then
  5963. begin
  5964. { In this situation, if the first jump branches, the second one will never,
  5965. branch so change the destination label to after the second jump }
  5966. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5967. if Assigned(JumpLabel) then
  5968. JumpLabel.DecRefs;
  5969. JumpLabel_far.IncRefs;
  5970. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5971. Result := True;
  5972. { Don't exit yet. Since p and p_jump haven't actually been
  5973. removed, we can check for more on this iteration }
  5974. Continue;
  5975. end;
  5976. end;
  5977. end;
  5978. end;
  5979. { Search for:
  5980. cmp ###,###
  5981. j(c1) @lbl1
  5982. cmp ###,### (same as first)
  5983. Remove second cmp
  5984. }
  5985. if GetNextInstruction(p_jump, hp2) and
  5986. (
  5987. (
  5988. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5989. (
  5990. (
  5991. MatchOpType(taicpu(p), top_const, top_reg) and
  5992. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5993. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5994. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5995. ) or (
  5996. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5997. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5998. )
  5999. )
  6000. ) or (
  6001. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6002. MatchOperand(taicpu(p).oper[0]^, 0) and
  6003. (taicpu(p).oper[1]^.typ = top_reg) and
  6004. MatchInstruction(hp2, A_TEST, []) and
  6005. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6006. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6007. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6008. )
  6009. ) then
  6010. begin
  6011. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6012. RemoveInstruction(hp2);
  6013. Result := True;
  6014. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6015. end;
  6016. GetNextInstruction(p_jump, p_jump);
  6017. end;
  6018. {
  6019. Try to optimise the following:
  6020. cmp $x,### ($x and $y can be registers or constants)
  6021. je @lbl1 (only reference)
  6022. cmp $y,### (### are identical)
  6023. @Lbl:
  6024. sete %reg1
  6025. Change to:
  6026. cmp $x,###
  6027. sete %reg2 (allocate new %reg2)
  6028. cmp $y,###
  6029. sete %reg1
  6030. orb %reg2,%reg1
  6031. (dealloc %reg2)
  6032. This adds an instruction (so don't perform under -Os), but it removes
  6033. a conditional branch.
  6034. }
  6035. if not (cs_opt_size in current_settings.optimizerswitches) and
  6036. (
  6037. (hp1 = p_jump) or
  6038. GetNextInstruction(p, hp1)
  6039. ) and
  6040. MatchInstruction(hp1, A_Jcc, []) and
  6041. IsJumpToLabel(taicpu(hp1)) and
  6042. (taicpu(hp1).condition in [C_E, C_Z]) and
  6043. GetNextInstruction(hp1, hp2) and
  6044. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6045. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6046. { The first operand of CMP instructions can only be a register or
  6047. immediate anyway, so no need to check }
  6048. GetNextInstruction(hp2, p_label) and
  6049. (p_label.typ = ait_label) and
  6050. (tai_label(p_label).labsym.getrefs = 1) and
  6051. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6052. GetNextInstruction(p_label, p_dist) and
  6053. MatchInstruction(p_dist, A_SETcc, []) and
  6054. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6055. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6056. begin
  6057. TransferUsedRegs(TmpUsedRegs);
  6058. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6059. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6060. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6061. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6062. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6063. { Get the instruction after the SETcc instruction so we can
  6064. allocate a new register over the entire range }
  6065. GetNextInstruction(p_dist, hp1_dist) then
  6066. begin
  6067. { Register can appear in p if it's not used afterwards, so only
  6068. allocate between hp1 and hp1_dist }
  6069. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6070. if NewReg <> NR_NO then
  6071. begin
  6072. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6073. { Change the jump instruction into a SETcc instruction }
  6074. taicpu(hp1).opcode := A_SETcc;
  6075. taicpu(hp1).opsize := S_B;
  6076. taicpu(hp1).loadreg(0, NewReg);
  6077. { This is now a dead label }
  6078. tai_label(p_label).labsym.decrefs;
  6079. { Prefer adding before the next instruction so the FLAGS
  6080. register is deallicated first }
  6081. AsmL.InsertBefore(
  6082. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6083. hp1_dist
  6084. );
  6085. Result := True;
  6086. { Don't exit yet, as p wasn't changed and hp1, while
  6087. modified, is still intact and might be optimised by the
  6088. SETcc optimisation below }
  6089. end;
  6090. end;
  6091. end;
  6092. if taicpu(p).oper[0]^.typ = top_const then
  6093. begin
  6094. if (taicpu(p).oper[0]^.val = 0) and
  6095. (taicpu(p).oper[1]^.typ = top_reg) and
  6096. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6097. begin
  6098. hp2 := p;
  6099. FirstMatch := True;
  6100. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6101. anything meaningful once it's converted to "test %reg,%reg";
  6102. additionally, some jumps will always (or never) branch, so
  6103. evaluate every jump immediately following the
  6104. comparison, optimising the conditions if possible.
  6105. Similarly with SETcc... those that are always set to 0 or 1
  6106. are changed to MOV instructions }
  6107. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6108. (
  6109. GetNextInstruction(hp2, hp1) and
  6110. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6111. ) do
  6112. begin
  6113. FirstMatch := False;
  6114. case taicpu(hp1).condition of
  6115. C_B, C_C, C_NAE, C_O:
  6116. { For B/NAE:
  6117. Will never branch since an unsigned integer can never be below zero
  6118. For C/O:
  6119. Result cannot overflow because 0 is being subtracted
  6120. }
  6121. begin
  6122. if taicpu(hp1).opcode = A_Jcc then
  6123. begin
  6124. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6125. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6126. RemoveInstruction(hp1);
  6127. { Since hp1 was deleted, hp2 must not be updated }
  6128. Continue;
  6129. end
  6130. else
  6131. begin
  6132. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6133. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6134. taicpu(hp1).opcode := A_MOV;
  6135. taicpu(hp1).ops := 2;
  6136. taicpu(hp1).condition := C_None;
  6137. taicpu(hp1).opsize := S_B;
  6138. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6139. taicpu(hp1).loadconst(0, 0);
  6140. end;
  6141. end;
  6142. C_BE, C_NA:
  6143. begin
  6144. { Will only branch if equal to zero }
  6145. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6146. taicpu(hp1).condition := C_E;
  6147. end;
  6148. C_A, C_NBE:
  6149. begin
  6150. { Will only branch if not equal to zero }
  6151. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6152. taicpu(hp1).condition := C_NE;
  6153. end;
  6154. C_AE, C_NB, C_NC, C_NO:
  6155. begin
  6156. { Will always branch }
  6157. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6158. if taicpu(hp1).opcode = A_Jcc then
  6159. begin
  6160. MakeUnconditional(taicpu(hp1));
  6161. { Any jumps/set that follow will now be dead code }
  6162. RemoveDeadCodeAfterJump(taicpu(hp1));
  6163. Break;
  6164. end
  6165. else
  6166. begin
  6167. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6168. taicpu(hp1).opcode := A_MOV;
  6169. taicpu(hp1).ops := 2;
  6170. taicpu(hp1).condition := C_None;
  6171. taicpu(hp1).opsize := S_B;
  6172. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6173. taicpu(hp1).loadconst(0, 1);
  6174. end;
  6175. end;
  6176. C_None:
  6177. InternalError(2020012201);
  6178. C_P, C_PE, C_NP, C_PO:
  6179. { We can't handle parity checks and they should never be generated
  6180. after a general-purpose CMP (it's used in some floating-point
  6181. comparisons that don't use CMP) }
  6182. InternalError(2020012202);
  6183. else
  6184. { Zero/Equality, Sign, their complements and all of the
  6185. signed comparisons do not need to be converted };
  6186. end;
  6187. hp2 := hp1;
  6188. end;
  6189. { Convert the instruction to a TEST }
  6190. taicpu(p).opcode := A_TEST;
  6191. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6192. Result := True;
  6193. Exit;
  6194. end
  6195. else if (taicpu(p).oper[0]^.val = 1) and
  6196. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6197. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6198. begin
  6199. { Convert; To:
  6200. cmp $1,r/m cmp $0,r/m
  6201. jl @lbl jle @lbl
  6202. }
  6203. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6204. taicpu(p).oper[0]^.val := 0;
  6205. taicpu(hp1).condition := C_LE;
  6206. { If the instruction is now "cmp $0,%reg", convert it to a
  6207. TEST (and effectively do the work of the "cmp $0,%reg" in
  6208. the block above)
  6209. If it's a reference, we can get away with not setting
  6210. Result to True because he haven't evaluated the jump
  6211. in this pass yet.
  6212. }
  6213. if (taicpu(p).oper[1]^.typ = top_reg) then
  6214. begin
  6215. taicpu(p).opcode := A_TEST;
  6216. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6217. Result := True;
  6218. end;
  6219. Exit;
  6220. end
  6221. else if (taicpu(p).oper[1]^.typ = top_reg)
  6222. {$ifdef x86_64}
  6223. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6224. {$endif x86_64}
  6225. then
  6226. begin
  6227. { cmp register,$8000 neg register
  6228. je target --> jo target
  6229. .... only if register is deallocated before jump.}
  6230. case Taicpu(p).opsize of
  6231. S_B: v:=$80;
  6232. S_W: v:=$8000;
  6233. S_L: v:=qword($80000000);
  6234. else
  6235. internalerror(2013112905);
  6236. end;
  6237. if (taicpu(p).oper[0]^.val=v) and
  6238. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6239. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6240. begin
  6241. TransferUsedRegs(TmpUsedRegs);
  6242. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6243. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6244. begin
  6245. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6246. Taicpu(p).opcode:=A_NEG;
  6247. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6248. Taicpu(p).clearop(1);
  6249. Taicpu(p).ops:=1;
  6250. if Taicpu(hp1).condition=C_E then
  6251. Taicpu(hp1).condition:=C_O
  6252. else
  6253. Taicpu(hp1).condition:=C_NO;
  6254. Result:=true;
  6255. exit;
  6256. end;
  6257. end;
  6258. end;
  6259. end;
  6260. if TrySwapMovCmp(p, hp1) then
  6261. begin
  6262. Result := True;
  6263. Exit;
  6264. end;
  6265. end;
  6266. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6267. var
  6268. hp1: tai;
  6269. begin
  6270. {
  6271. remove the second (v)pxor from
  6272. pxor reg,reg
  6273. ...
  6274. pxor reg,reg
  6275. }
  6276. Result:=false;
  6277. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6278. MatchOpType(taicpu(p),top_reg,top_reg) and
  6279. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6280. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6281. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6282. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6283. begin
  6284. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6285. RemoveInstruction(hp1);
  6286. Result:=true;
  6287. Exit;
  6288. end
  6289. {
  6290. replace
  6291. pxor reg1,reg1
  6292. movapd/s reg1,reg2
  6293. dealloc reg1
  6294. by
  6295. pxor reg2,reg2
  6296. }
  6297. else if GetNextInstruction(p,hp1) and
  6298. { we mix single and double opperations here because we assume that the compiler
  6299. generates vmovapd only after double operations and vmovaps only after single operations }
  6300. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6301. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6302. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6303. (taicpu(p).oper[0]^.typ=top_reg) then
  6304. begin
  6305. TransferUsedRegs(TmpUsedRegs);
  6306. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6307. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6308. begin
  6309. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6310. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6311. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6312. RemoveInstruction(hp1);
  6313. result:=true;
  6314. end;
  6315. end;
  6316. end;
  6317. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6318. var
  6319. hp1: tai;
  6320. begin
  6321. {
  6322. remove the second (v)pxor from
  6323. (v)pxor reg,reg
  6324. ...
  6325. (v)pxor reg,reg
  6326. }
  6327. Result:=false;
  6328. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6329. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6330. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6331. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6332. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6333. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6334. begin
  6335. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6336. RemoveInstruction(hp1);
  6337. Result:=true;
  6338. Exit;
  6339. end
  6340. else
  6341. Result:=OptPass1VOP(p);
  6342. end;
  6343. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6344. var
  6345. hp1 : tai;
  6346. begin
  6347. result:=false;
  6348. { replace
  6349. IMul const,%mreg1,%mreg2
  6350. Mov %reg2,%mreg3
  6351. dealloc %mreg3
  6352. by
  6353. Imul const,%mreg1,%mreg23
  6354. }
  6355. if (taicpu(p).ops=3) and
  6356. GetNextInstruction(p,hp1) and
  6357. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6358. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6359. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6360. begin
  6361. TransferUsedRegs(TmpUsedRegs);
  6362. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6363. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6364. begin
  6365. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6366. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6367. RemoveInstruction(hp1);
  6368. result:=true;
  6369. end;
  6370. end;
  6371. end;
  6372. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6373. var
  6374. hp1 : tai;
  6375. begin
  6376. result:=false;
  6377. { replace
  6378. IMul %reg0,%reg1,%reg2
  6379. Mov %reg2,%reg3
  6380. dealloc %reg2
  6381. by
  6382. Imul %reg0,%reg1,%reg3
  6383. }
  6384. if GetNextInstruction(p,hp1) and
  6385. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6386. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6387. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6388. begin
  6389. TransferUsedRegs(TmpUsedRegs);
  6390. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6391. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6392. begin
  6393. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6394. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6395. RemoveInstruction(hp1);
  6396. result:=true;
  6397. end;
  6398. end;
  6399. end;
  6400. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6401. var
  6402. hp1: tai;
  6403. begin
  6404. Result:=false;
  6405. { get rid of
  6406. (v)cvtss2sd reg0,<reg1,>reg2
  6407. (v)cvtss2sd reg2,<reg2,>reg0
  6408. }
  6409. if GetNextInstruction(p,hp1) and
  6410. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6411. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6412. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6413. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6414. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6415. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6416. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6417. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6418. )
  6419. ) then
  6420. begin
  6421. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6422. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6423. begin
  6424. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6425. RemoveCurrentP(p);
  6426. RemoveInstruction(hp1);
  6427. end
  6428. else
  6429. begin
  6430. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6431. if taicpu(hp1).opcode=A_CVTSD2SS then
  6432. begin
  6433. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6434. taicpu(p).opcode:=A_MOVAPS;
  6435. end
  6436. else
  6437. begin
  6438. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6439. taicpu(p).opcode:=A_VMOVAPS;
  6440. end;
  6441. taicpu(p).ops:=2;
  6442. RemoveInstruction(hp1);
  6443. end;
  6444. Result:=true;
  6445. Exit;
  6446. end;
  6447. end;
  6448. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6449. var
  6450. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6451. ThisReg: TRegister;
  6452. begin
  6453. Result := False;
  6454. if not GetNextInstruction(p,hp1) then
  6455. Exit;
  6456. {
  6457. convert
  6458. j<c> .L1
  6459. mov 1,reg
  6460. jmp .L2
  6461. .L1
  6462. mov 0,reg
  6463. .L2
  6464. into
  6465. mov 0,reg
  6466. set<not(c)> reg
  6467. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6468. would destroy the flag contents
  6469. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6470. executed at the same time as a previous comparison.
  6471. set<not(c)> reg
  6472. movzx reg, reg
  6473. }
  6474. if MatchInstruction(hp1,A_MOV,[]) and
  6475. (taicpu(hp1).oper[0]^.typ = top_const) and
  6476. (
  6477. (
  6478. (taicpu(hp1).oper[1]^.typ = top_reg)
  6479. {$ifdef i386}
  6480. { Under i386, ESI, EDI, EBP and ESP
  6481. don't have an 8-bit representation }
  6482. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6483. {$endif i386}
  6484. ) or (
  6485. {$ifdef i386}
  6486. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6487. {$endif i386}
  6488. (taicpu(hp1).opsize = S_B)
  6489. )
  6490. ) and
  6491. GetNextInstruction(hp1,hp2) and
  6492. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6493. GetNextInstruction(hp2,hp3) and
  6494. SkipAligns(hp3, hp3) and
  6495. (hp3.typ=ait_label) and
  6496. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6497. GetNextInstruction(hp3,hp4) and
  6498. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6499. (taicpu(hp4).oper[0]^.typ = top_const) and
  6500. (
  6501. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6502. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6503. ) and
  6504. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6505. GetNextInstruction(hp4,hp5) and
  6506. SkipAligns(hp5, hp5) and
  6507. (hp5.typ=ait_label) and
  6508. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6509. begin
  6510. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6511. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6512. tai_label(hp3).labsym.DecRefs;
  6513. { If this isn't the only reference to the middle label, we can
  6514. still make a saving - only that the first jump and everything
  6515. that follows will remain. }
  6516. if (tai_label(hp3).labsym.getrefs = 0) then
  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)',p)
  6520. else
  6521. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6522. { remove jump, first label and second MOV (also catching any aligns) }
  6523. repeat
  6524. if not GetNextInstruction(hp2, hp3) then
  6525. InternalError(2021040810);
  6526. RemoveInstruction(hp2);
  6527. hp2 := hp3;
  6528. until hp2 = hp5;
  6529. { Don't decrement reference count before the removal loop
  6530. above, otherwise GetNextInstruction won't stop on the
  6531. the label }
  6532. tai_label(hp5).labsym.DecRefs;
  6533. end
  6534. else
  6535. begin
  6536. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6537. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6538. else
  6539. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6540. end;
  6541. taicpu(p).opcode:=A_SETcc;
  6542. taicpu(p).opsize:=S_B;
  6543. taicpu(p).is_jmp:=False;
  6544. if taicpu(hp1).opsize=S_B then
  6545. begin
  6546. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6547. if taicpu(hp1).oper[1]^.typ = top_reg then
  6548. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6549. RemoveInstruction(hp1);
  6550. end
  6551. else
  6552. begin
  6553. { Will be a register because the size can't be S_B otherwise }
  6554. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6555. taicpu(p).loadreg(0, ThisReg);
  6556. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6557. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6558. begin
  6559. case taicpu(hp1).opsize of
  6560. S_W:
  6561. taicpu(hp1).opsize := S_BW;
  6562. S_L:
  6563. taicpu(hp1).opsize := S_BL;
  6564. {$ifdef x86_64}
  6565. S_Q:
  6566. begin
  6567. taicpu(hp1).opsize := S_BL;
  6568. { Change the destination register to 32-bit }
  6569. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6570. end;
  6571. {$endif x86_64}
  6572. else
  6573. InternalError(2021040820);
  6574. end;
  6575. taicpu(hp1).opcode := A_MOVZX;
  6576. taicpu(hp1).loadreg(0, ThisReg);
  6577. end
  6578. else
  6579. begin
  6580. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6581. { hp1 is already a MOV instruction with the correct register }
  6582. taicpu(hp1).loadconst(0, 0);
  6583. { Inserting it right before p will guarantee that the flags are also tracked }
  6584. asml.Remove(hp1);
  6585. asml.InsertBefore(hp1, p);
  6586. end;
  6587. end;
  6588. Result:=true;
  6589. exit;
  6590. end
  6591. else if (hp1.typ = ait_label) then
  6592. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6593. end;
  6594. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6595. var
  6596. hp1, hp2, hp3: tai;
  6597. SourceRef, TargetRef: TReference;
  6598. CurrentReg: TRegister;
  6599. begin
  6600. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6601. if not UseAVX then
  6602. InternalError(2021100501);
  6603. Result := False;
  6604. { Look for the following to simplify:
  6605. vmovdqa/u x(mem1), %xmmreg
  6606. vmovdqa/u %xmmreg, y(mem2)
  6607. vmovdqa/u x+16(mem1), %xmmreg
  6608. vmovdqa/u %xmmreg, y+16(mem2)
  6609. Change to:
  6610. vmovdqa/u x(mem1), %ymmreg
  6611. vmovdqa/u %ymmreg, y(mem2)
  6612. vpxor %ymmreg, %ymmreg, %ymmreg
  6613. ( The VPXOR instruction is to zero the upper half, thus removing the
  6614. need to call the potentially expensive VZEROUPPER instruction. Other
  6615. peephole optimisations can remove VPXOR if it's unnecessary )
  6616. }
  6617. TransferUsedRegs(TmpUsedRegs);
  6618. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6619. { NOTE: In the optimisations below, if the references dictate that an
  6620. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6621. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6622. if (taicpu(p).opsize = S_XMM) and
  6623. MatchOpType(taicpu(p), top_ref, top_reg) and
  6624. GetNextInstruction(p, hp1) and
  6625. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6626. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6627. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6628. begin
  6629. SourceRef := taicpu(p).oper[0]^.ref^;
  6630. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6631. if GetNextInstruction(hp1, hp2) and
  6632. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6633. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6634. begin
  6635. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6636. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6637. Inc(SourceRef.offset, 16);
  6638. { Reuse the register in the first block move }
  6639. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6640. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6641. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6642. begin
  6643. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6644. Inc(TargetRef.offset, 16);
  6645. if GetNextInstruction(hp2, hp3) and
  6646. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6647. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6648. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6649. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6650. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6651. begin
  6652. { Update the register tracking to the new size }
  6653. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6654. { Remember that the offsets are 16 ahead }
  6655. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6656. if not (
  6657. ((SourceRef.offset mod 32) = 16) and
  6658. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6659. ) then
  6660. taicpu(p).opcode := A_VMOVDQU;
  6661. taicpu(p).opsize := S_YMM;
  6662. taicpu(p).oper[1]^.reg := CurrentReg;
  6663. if not (
  6664. ((TargetRef.offset mod 32) = 16) and
  6665. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6666. ) then
  6667. taicpu(hp1).opcode := A_VMOVDQU;
  6668. taicpu(hp1).opsize := S_YMM;
  6669. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6670. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6671. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6672. if (pi_uses_ymm in current_procinfo.flags) then
  6673. RemoveInstruction(hp2)
  6674. else
  6675. begin
  6676. taicpu(hp2).opcode := A_VPXOR;
  6677. taicpu(hp2).opsize := S_YMM;
  6678. taicpu(hp2).loadreg(0, CurrentReg);
  6679. taicpu(hp2).loadreg(1, CurrentReg);
  6680. taicpu(hp2).loadreg(2, CurrentReg);
  6681. taicpu(hp2).ops := 3;
  6682. end;
  6683. RemoveInstruction(hp3);
  6684. Result := True;
  6685. Exit;
  6686. end;
  6687. end
  6688. else
  6689. begin
  6690. { See if the next references are 16 less rather than 16 greater }
  6691. Dec(SourceRef.offset, 32); { -16 the other way }
  6692. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6693. begin
  6694. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6695. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6696. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6697. GetNextInstruction(hp2, hp3) and
  6698. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6699. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6700. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6701. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6702. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6703. begin
  6704. { Update the register tracking to the new size }
  6705. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6706. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6707. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6708. if not(
  6709. ((SourceRef.offset mod 32) = 0) and
  6710. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6711. ) then
  6712. taicpu(hp2).opcode := A_VMOVDQU;
  6713. taicpu(hp2).opsize := S_YMM;
  6714. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6715. if not (
  6716. ((TargetRef.offset mod 32) = 0) and
  6717. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6718. ) then
  6719. taicpu(hp3).opcode := A_VMOVDQU;
  6720. taicpu(hp3).opsize := S_YMM;
  6721. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6722. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6723. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6724. if (pi_uses_ymm in current_procinfo.flags) then
  6725. RemoveInstruction(hp1)
  6726. else
  6727. begin
  6728. taicpu(hp1).opcode := A_VPXOR;
  6729. taicpu(hp1).opsize := S_YMM;
  6730. taicpu(hp1).loadreg(0, CurrentReg);
  6731. taicpu(hp1).loadreg(1, CurrentReg);
  6732. taicpu(hp1).loadreg(2, CurrentReg);
  6733. taicpu(hp1).ops := 3;
  6734. Asml.Remove(hp1);
  6735. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6736. end;
  6737. RemoveCurrentP(p, hp2);
  6738. Result := True;
  6739. Exit;
  6740. end;
  6741. end;
  6742. end;
  6743. end;
  6744. end;
  6745. end;
  6746. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6747. var
  6748. hp2, hp3, first_assignment: tai;
  6749. IncCount, OperIdx: Integer;
  6750. OrigLabel: TAsmLabel;
  6751. begin
  6752. Count := 0;
  6753. Result := False;
  6754. first_assignment := nil;
  6755. if (LoopCount >= 20) then
  6756. begin
  6757. { Guard against infinite loops }
  6758. Exit;
  6759. end;
  6760. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6761. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6762. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6763. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6764. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6765. Exit;
  6766. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6767. {
  6768. change
  6769. jmp .L1
  6770. ...
  6771. .L1:
  6772. mov ##, ## ( multiple movs possible )
  6773. jmp/ret
  6774. into
  6775. mov ##, ##
  6776. jmp/ret
  6777. }
  6778. if not Assigned(hp1) then
  6779. begin
  6780. hp1 := GetLabelWithSym(OrigLabel);
  6781. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6782. Exit;
  6783. end;
  6784. hp2 := hp1;
  6785. while Assigned(hp2) do
  6786. begin
  6787. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6788. SkipLabels(hp2,hp2);
  6789. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6790. Break;
  6791. case taicpu(hp2).opcode of
  6792. A_MOVSS:
  6793. begin
  6794. if taicpu(hp2).ops = 0 then
  6795. { Wrong MOVSS }
  6796. Break;
  6797. Inc(Count);
  6798. if Count >= 5 then
  6799. { Too many to be worthwhile }
  6800. Break;
  6801. GetNextInstruction(hp2, hp2);
  6802. Continue;
  6803. end;
  6804. A_MOV,
  6805. A_MOVD,
  6806. A_MOVQ,
  6807. A_MOVSX,
  6808. {$ifdef x86_64}
  6809. A_MOVSXD,
  6810. {$endif x86_64}
  6811. A_MOVZX,
  6812. A_MOVAPS,
  6813. A_MOVUPS,
  6814. A_MOVSD,
  6815. A_MOVAPD,
  6816. A_MOVUPD,
  6817. A_MOVDQA,
  6818. A_MOVDQU,
  6819. A_VMOVSS,
  6820. A_VMOVAPS,
  6821. A_VMOVUPS,
  6822. A_VMOVSD,
  6823. A_VMOVAPD,
  6824. A_VMOVUPD,
  6825. A_VMOVDQA,
  6826. A_VMOVDQU:
  6827. begin
  6828. Inc(Count);
  6829. if Count >= 5 then
  6830. { Too many to be worthwhile }
  6831. Break;
  6832. GetNextInstruction(hp2, hp2);
  6833. Continue;
  6834. end;
  6835. A_JMP:
  6836. begin
  6837. { Guard against infinite loops }
  6838. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6839. Exit;
  6840. { Analyse this jump first in case it also duplicates assignments }
  6841. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6842. begin
  6843. { Something did change! }
  6844. Result := True;
  6845. Inc(Count, IncCount);
  6846. if Count >= 5 then
  6847. begin
  6848. { Too many to be worthwhile }
  6849. Exit;
  6850. end;
  6851. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6852. Break;
  6853. end;
  6854. Result := True;
  6855. Break;
  6856. end;
  6857. A_RET:
  6858. begin
  6859. Result := True;
  6860. Break;
  6861. end;
  6862. else
  6863. Break;
  6864. end;
  6865. end;
  6866. if Result then
  6867. begin
  6868. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6869. if Count = 0 then
  6870. begin
  6871. Result := False;
  6872. Exit;
  6873. end;
  6874. hp3 := p;
  6875. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6876. while True do
  6877. begin
  6878. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6879. SkipLabels(hp1,hp1);
  6880. if (hp1.typ <> ait_instruction) then
  6881. InternalError(2021040720);
  6882. case taicpu(hp1).opcode of
  6883. A_JMP:
  6884. begin
  6885. { Change the original jump to the new destination }
  6886. OrigLabel.decrefs;
  6887. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6888. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6889. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6890. if not Assigned(first_assignment) then
  6891. InternalError(2021040810)
  6892. else
  6893. p := first_assignment;
  6894. Exit;
  6895. end;
  6896. A_RET:
  6897. begin
  6898. { Now change the jump into a RET instruction }
  6899. ConvertJumpToRET(p, hp1);
  6900. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6901. if not Assigned(first_assignment) then
  6902. InternalError(2021040811)
  6903. else
  6904. p := first_assignment;
  6905. Exit;
  6906. end;
  6907. else
  6908. begin
  6909. { Duplicate the MOV instruction }
  6910. hp3:=tai(hp1.getcopy);
  6911. if first_assignment = nil then
  6912. first_assignment := hp3;
  6913. asml.InsertBefore(hp3, p);
  6914. { Make sure the compiler knows about any final registers written here }
  6915. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6916. with taicpu(hp3).oper[OperIdx]^ do
  6917. begin
  6918. case typ of
  6919. top_ref:
  6920. begin
  6921. if (ref^.base <> NR_NO) and
  6922. (getsupreg(ref^.base) <> RS_ESP) and
  6923. (getsupreg(ref^.base) <> RS_EBP)
  6924. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6925. then
  6926. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6927. if (ref^.index <> NR_NO) and
  6928. (getsupreg(ref^.index) <> RS_ESP) and
  6929. (getsupreg(ref^.index) <> RS_EBP)
  6930. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6931. (ref^.index <> ref^.base) then
  6932. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6933. end;
  6934. top_reg:
  6935. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6936. else
  6937. ;
  6938. end;
  6939. end;
  6940. end;
  6941. end;
  6942. if not GetNextInstruction(hp1, hp1) then
  6943. { Should have dropped out earlier }
  6944. InternalError(2021040710);
  6945. end;
  6946. end;
  6947. end;
  6948. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6949. var
  6950. hp2: tai;
  6951. X: Integer;
  6952. const
  6953. WriteOp: array[0..3] of set of TInsChange = (
  6954. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6955. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6956. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6957. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6958. RegWriteFlags: array[0..7] of set of TInsChange = (
  6959. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6960. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6961. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6962. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6963. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6964. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6965. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6966. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6967. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6968. begin
  6969. { If we have something like:
  6970. cmp ###,%reg1
  6971. mov 0,%reg2
  6972. And no modified registers are shared, move the instruction to before
  6973. the comparison as this means it can be optimised without worrying
  6974. about the FLAGS register. (CMP/MOV is generated by
  6975. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6976. As long as the second instruction doesn't use the flags or one of the
  6977. registers used by CMP or TEST (also check any references that use the
  6978. registers), then it can be moved prior to the comparison.
  6979. }
  6980. Result := False;
  6981. if (hp1.typ <> ait_instruction) or
  6982. taicpu(hp1).is_jmp or
  6983. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6984. Exit;
  6985. { NOP is a pipeline fence, likely marking the beginning of the function
  6986. epilogue, so drop out. Similarly, drop out if POP or RET are
  6987. encountered }
  6988. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6989. Exit;
  6990. if (taicpu(hp1).opcode = A_MOVSS) and
  6991. (taicpu(hp1).ops = 0) then
  6992. { Wrong MOVSS }
  6993. Exit;
  6994. { Check for writes to specific registers first }
  6995. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6996. for X := 0 to 7 do
  6997. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6998. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6999. Exit;
  7000. for X := 0 to taicpu(hp1).ops - 1 do
  7001. begin
  7002. { Check to see if this operand writes to something }
  7003. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7004. { And matches something in the CMP/TEST instruction }
  7005. (
  7006. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7007. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7008. (
  7009. { If it's a register, make sure the register written to doesn't
  7010. appear in the cmp instruction as part of a reference }
  7011. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7012. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7013. )
  7014. ) then
  7015. Exit;
  7016. end;
  7017. { The instruction can be safely moved }
  7018. asml.Remove(hp1);
  7019. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  7020. if not GetLastInstruction(p, hp2) then
  7021. asml.InsertBefore(hp1, p)
  7022. else
  7023. asml.InsertAfter(hp1, hp2);
  7024. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7025. for X := 0 to taicpu(hp1).ops - 1 do
  7026. case taicpu(hp1).oper[X]^.typ of
  7027. top_reg:
  7028. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7029. top_ref:
  7030. begin
  7031. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7032. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7033. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7034. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7035. end;
  7036. else
  7037. ;
  7038. end;
  7039. if taicpu(hp1).opcode = A_LEA then
  7040. { The flags will be overwritten by the CMP/TEST instruction }
  7041. ConvertLEA(taicpu(hp1));
  7042. Result := True;
  7043. end;
  7044. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7045. function IsXCHGAcceptable: Boolean; inline;
  7046. begin
  7047. { Always accept if optimising for size }
  7048. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7049. (
  7050. {$ifdef x86_64}
  7051. { XCHG takes 3 cycles on AMD Athlon64 }
  7052. (current_settings.optimizecputype >= cpu_core_i)
  7053. {$else x86_64}
  7054. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7055. than 3, so it becomes a saving compared to three MOVs with two of
  7056. them able to execute simultaneously. [Kit] }
  7057. (current_settings.optimizecputype >= cpu_PentiumM)
  7058. {$endif x86_64}
  7059. );
  7060. end;
  7061. var
  7062. NewRef: TReference;
  7063. hp1, hp2, hp3, hp4: Tai;
  7064. {$ifndef x86_64}
  7065. OperIdx: Integer;
  7066. {$endif x86_64}
  7067. NewInstr : Taicpu;
  7068. NewAligh : Tai_align;
  7069. DestLabel: TAsmLabel;
  7070. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7071. var
  7072. NextInstr: tai;
  7073. begin
  7074. Result := False;
  7075. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7076. if not GetNextInstruction(InputInstr, NextInstr) or
  7077. (
  7078. { The FLAGS register isn't always tracked properly, so do not
  7079. perform this optimisation if a conditional statement follows }
  7080. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7081. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7082. ) then
  7083. begin
  7084. reference_reset(NewRef, 1, []);
  7085. NewRef.base := taicpu(p).oper[0]^.reg;
  7086. NewRef.scalefactor := 1;
  7087. if taicpu(InputInstr).opcode = A_ADD then
  7088. begin
  7089. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7090. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7091. end
  7092. else
  7093. begin
  7094. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7095. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7096. end;
  7097. taicpu(p).opcode := A_LEA;
  7098. taicpu(p).loadref(0, NewRef);
  7099. RemoveInstruction(InputInstr);
  7100. Result := True;
  7101. end;
  7102. end;
  7103. begin
  7104. Result:=false;
  7105. { This optimisation adds an instruction, so only do it for speed }
  7106. if not (cs_opt_size in current_settings.optimizerswitches) and
  7107. MatchOpType(taicpu(p), top_const, top_reg) and
  7108. (taicpu(p).oper[0]^.val = 0) then
  7109. begin
  7110. { To avoid compiler warning }
  7111. DestLabel := nil;
  7112. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7113. InternalError(2021040750);
  7114. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7115. Exit;
  7116. case hp1.typ of
  7117. ait_label:
  7118. begin
  7119. { Change:
  7120. mov $0,%reg mov $0,%reg
  7121. @Lbl1: @Lbl1:
  7122. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7123. je @Lbl2 jne @Lbl2
  7124. To: To:
  7125. mov $0,%reg mov $0,%reg
  7126. jmp @Lbl2 jmp @Lbl3
  7127. (align) (align)
  7128. @Lbl1: @Lbl1:
  7129. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7130. je @Lbl2 je @Lbl2
  7131. @Lbl3: <-- Only if label exists
  7132. (Not if it's optimised for size)
  7133. }
  7134. if not GetNextInstruction(hp1, hp2) then
  7135. Exit;
  7136. if not (cs_opt_size in current_settings.optimizerswitches) and
  7137. (hp2.typ = ait_instruction) and
  7138. (
  7139. { Register sizes must exactly match }
  7140. (
  7141. (taicpu(hp2).opcode = A_CMP) and
  7142. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7143. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7144. ) or (
  7145. (taicpu(hp2).opcode = A_TEST) and
  7146. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7147. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7148. )
  7149. ) and GetNextInstruction(hp2, hp3) and
  7150. (hp3.typ = ait_instruction) and
  7151. (taicpu(hp3).opcode = A_JCC) and
  7152. (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
  7153. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7154. begin
  7155. { Check condition of jump }
  7156. { Always true? }
  7157. if condition_in(C_E, taicpu(hp3).condition) then
  7158. begin
  7159. { Copy label symbol and obtain matching label entry for the
  7160. conditional jump, as this will be our destination}
  7161. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7162. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7163. Result := True;
  7164. end
  7165. { Always false? }
  7166. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7167. begin
  7168. { This is only worth it if there's a jump to take }
  7169. case hp2.typ of
  7170. ait_instruction:
  7171. begin
  7172. if taicpu(hp2).opcode = A_JMP then
  7173. begin
  7174. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7175. { An unconditional jump follows the conditional jump which will always be false,
  7176. so use this jump's destination for the new jump }
  7177. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7178. Result := True;
  7179. end
  7180. else if taicpu(hp2).opcode = A_JCC then
  7181. begin
  7182. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7183. if condition_in(C_E, taicpu(hp2).condition) then
  7184. begin
  7185. { A second conditional jump follows the conditional jump which will always be false,
  7186. while the second jump is always True, so use this jump's destination for the new jump }
  7187. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7188. Result := True;
  7189. end;
  7190. { Don't risk it if the jump isn't always true (Result remains False) }
  7191. end;
  7192. end;
  7193. else
  7194. { If anything else don't optimise };
  7195. end;
  7196. end;
  7197. if Result then
  7198. begin
  7199. { Just so we have something to insert as a paremeter}
  7200. reference_reset(NewRef, 1, []);
  7201. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7202. { Now actually load the correct parameter }
  7203. NewInstr.loadsymbol(0, DestLabel, 0);
  7204. { Get instruction before original label (may not be p under -O3) }
  7205. if not GetLastInstruction(hp1, hp2) then
  7206. { Shouldn't fail here }
  7207. InternalError(2021040701);
  7208. DestLabel.increfs;
  7209. AsmL.InsertAfter(NewInstr, hp2);
  7210. { Add new alignment field }
  7211. (* AsmL.InsertAfter(
  7212. cai_align.create_max(
  7213. current_settings.alignment.jumpalign,
  7214. current_settings.alignment.jumpalignskipmax
  7215. ),
  7216. NewInstr
  7217. ); *)
  7218. end;
  7219. Exit;
  7220. end;
  7221. end;
  7222. else
  7223. ;
  7224. end;
  7225. end;
  7226. if not GetNextInstruction(p, hp1) then
  7227. Exit;
  7228. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7229. and DoMovCmpMemOpt(p, hp1, True) then
  7230. begin
  7231. Result := True;
  7232. Exit;
  7233. end
  7234. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7235. begin
  7236. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7237. further, but we can't just put this jump optimisation in pass 1
  7238. because it tends to perform worse when conditional jumps are
  7239. nearby (e.g. when converting CMOV instructions). [Kit] }
  7240. if OptPass2JMP(hp1) then
  7241. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7242. Result := OptPass1MOV(p)
  7243. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7244. returned True and the instruction is still a MOV, thus checking
  7245. the optimisations below }
  7246. { If OptPass2JMP returned False, no optimisations were done to
  7247. the jump and there are no further optimisations that can be done
  7248. to the MOV instruction on this pass }
  7249. end
  7250. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7251. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7252. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7253. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7254. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7255. begin
  7256. { Change:
  7257. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7258. addl/q $x,%reg2 subl/q $x,%reg2
  7259. To:
  7260. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7261. }
  7262. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7263. { be lazy, checking separately for sub would be slightly better }
  7264. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7265. begin
  7266. TransferUsedRegs(TmpUsedRegs);
  7267. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7268. if TryMovArith2Lea(hp1) then
  7269. begin
  7270. Result := True;
  7271. Exit;
  7272. end
  7273. end
  7274. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7275. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7276. { Same as above, but also adds or subtracts to %reg2 in between.
  7277. It's still valid as long as the flags aren't in use }
  7278. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7279. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7280. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7281. { be lazy, checking separately for sub would be slightly better }
  7282. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7283. begin
  7284. TransferUsedRegs(TmpUsedRegs);
  7285. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7286. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7287. if TryMovArith2Lea(hp2) then
  7288. begin
  7289. Result := True;
  7290. Exit;
  7291. end;
  7292. end;
  7293. end
  7294. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7295. {$ifdef x86_64}
  7296. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7297. {$else x86_64}
  7298. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7299. {$endif x86_64}
  7300. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7301. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7302. { mov reg1, reg2 mov reg1, reg2
  7303. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7304. begin
  7305. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7306. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7307. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7308. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7309. TransferUsedRegs(TmpUsedRegs);
  7310. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7311. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7312. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7313. then
  7314. begin
  7315. RemoveCurrentP(p, hp1);
  7316. Result:=true;
  7317. end;
  7318. exit;
  7319. end
  7320. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7321. IsXCHGAcceptable and
  7322. { XCHG doesn't support 8-byte registers }
  7323. (taicpu(p).opsize <> S_B) and
  7324. MatchInstruction(hp1, A_MOV, []) and
  7325. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7326. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7327. GetNextInstruction(hp1, hp2) and
  7328. MatchInstruction(hp2, A_MOV, []) and
  7329. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7330. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7331. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7332. begin
  7333. { mov %reg1,%reg2
  7334. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7335. mov %reg2,%reg3
  7336. (%reg2 not used afterwards)
  7337. Note that xchg takes 3 cycles to execute, and generally mov's take
  7338. only one cycle apiece, but the first two mov's can be executed in
  7339. parallel, only taking 2 cycles overall. Older processors should
  7340. therefore only optimise for size. [Kit]
  7341. }
  7342. TransferUsedRegs(TmpUsedRegs);
  7343. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7344. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7345. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7346. begin
  7347. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7348. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7349. taicpu(hp1).opcode := A_XCHG;
  7350. RemoveCurrentP(p, hp1);
  7351. RemoveInstruction(hp2);
  7352. Result := True;
  7353. Exit;
  7354. end;
  7355. end
  7356. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7357. MatchInstruction(hp1, A_SAR, []) then
  7358. begin
  7359. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7360. begin
  7361. { the use of %edx also covers the opsize being S_L }
  7362. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7363. begin
  7364. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7365. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7366. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7367. begin
  7368. { Change:
  7369. movl %eax,%edx
  7370. sarl $31,%edx
  7371. To:
  7372. cltd
  7373. }
  7374. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7375. RemoveInstruction(hp1);
  7376. taicpu(p).opcode := A_CDQ;
  7377. taicpu(p).opsize := S_NO;
  7378. taicpu(p).clearop(1);
  7379. taicpu(p).clearop(0);
  7380. taicpu(p).ops:=0;
  7381. Result := True;
  7382. end
  7383. else if (cs_opt_size in current_settings.optimizerswitches) and
  7384. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7385. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7386. begin
  7387. { Change:
  7388. movl %edx,%eax
  7389. sarl $31,%edx
  7390. To:
  7391. movl %edx,%eax
  7392. cltd
  7393. Note that this creates a dependency between the two instructions,
  7394. so only perform if optimising for size.
  7395. }
  7396. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7397. taicpu(hp1).opcode := A_CDQ;
  7398. taicpu(hp1).opsize := S_NO;
  7399. taicpu(hp1).clearop(1);
  7400. taicpu(hp1).clearop(0);
  7401. taicpu(hp1).ops:=0;
  7402. end;
  7403. {$ifndef x86_64}
  7404. end
  7405. { Don't bother if CMOV is supported, because a more optimal
  7406. sequence would have been generated for the Abs() intrinsic }
  7407. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7408. { the use of %eax also covers the opsize being S_L }
  7409. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7410. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7411. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7412. GetNextInstruction(hp1, hp2) and
  7413. MatchInstruction(hp2, A_XOR, [S_L]) and
  7414. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7415. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7416. GetNextInstruction(hp2, hp3) and
  7417. MatchInstruction(hp3, A_SUB, [S_L]) and
  7418. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7419. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7420. begin
  7421. { Change:
  7422. movl %eax,%edx
  7423. sarl $31,%eax
  7424. xorl %eax,%edx
  7425. subl %eax,%edx
  7426. (Instruction that uses %edx)
  7427. (%eax deallocated)
  7428. (%edx deallocated)
  7429. To:
  7430. cltd
  7431. xorl %edx,%eax <-- Note the registers have swapped
  7432. subl %edx,%eax
  7433. (Instruction that uses %eax) <-- %eax rather than %edx
  7434. }
  7435. TransferUsedRegs(TmpUsedRegs);
  7436. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7437. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7438. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7439. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7440. begin
  7441. if GetNextInstruction(hp3, hp4) and
  7442. not RegModifiedByInstruction(NR_EDX, hp4) and
  7443. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7444. begin
  7445. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7446. taicpu(p).opcode := A_CDQ;
  7447. taicpu(p).clearop(1);
  7448. taicpu(p).clearop(0);
  7449. taicpu(p).ops:=0;
  7450. RemoveInstruction(hp1);
  7451. taicpu(hp2).loadreg(0, NR_EDX);
  7452. taicpu(hp2).loadreg(1, NR_EAX);
  7453. taicpu(hp3).loadreg(0, NR_EDX);
  7454. taicpu(hp3).loadreg(1, NR_EAX);
  7455. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7456. { Convert references in the following instruction (hp4) from %edx to %eax }
  7457. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7458. with taicpu(hp4).oper[OperIdx]^ do
  7459. case typ of
  7460. top_reg:
  7461. if getsupreg(reg) = RS_EDX then
  7462. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7463. top_ref:
  7464. begin
  7465. if getsupreg(reg) = RS_EDX then
  7466. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7467. if getsupreg(reg) = RS_EDX then
  7468. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7469. end;
  7470. else
  7471. ;
  7472. end;
  7473. end;
  7474. end;
  7475. {$else x86_64}
  7476. end;
  7477. end
  7478. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7479. { the use of %rdx also covers the opsize being S_Q }
  7480. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7481. begin
  7482. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7483. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7484. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7485. begin
  7486. { Change:
  7487. movq %rax,%rdx
  7488. sarq $63,%rdx
  7489. To:
  7490. cqto
  7491. }
  7492. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7493. RemoveInstruction(hp1);
  7494. taicpu(p).opcode := A_CQO;
  7495. taicpu(p).opsize := S_NO;
  7496. taicpu(p).clearop(1);
  7497. taicpu(p).clearop(0);
  7498. taicpu(p).ops:=0;
  7499. Result := True;
  7500. end
  7501. else if (cs_opt_size in current_settings.optimizerswitches) and
  7502. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7503. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7504. begin
  7505. { Change:
  7506. movq %rdx,%rax
  7507. sarq $63,%rdx
  7508. To:
  7509. movq %rdx,%rax
  7510. cqto
  7511. Note that this creates a dependency between the two instructions,
  7512. so only perform if optimising for size.
  7513. }
  7514. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7515. taicpu(hp1).opcode := A_CQO;
  7516. taicpu(hp1).opsize := S_NO;
  7517. taicpu(hp1).clearop(1);
  7518. taicpu(hp1).clearop(0);
  7519. taicpu(hp1).ops:=0;
  7520. {$endif x86_64}
  7521. end;
  7522. end;
  7523. end
  7524. else if MatchInstruction(hp1, A_MOV, []) and
  7525. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7526. { Though "GetNextInstruction" could be factored out, along with
  7527. the instructions that depend on hp2, it is an expensive call that
  7528. should be delayed for as long as possible, hence we do cheaper
  7529. checks first that are likely to be False. [Kit] }
  7530. begin
  7531. if (
  7532. (
  7533. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7534. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7535. (
  7536. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7537. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7538. )
  7539. ) or
  7540. (
  7541. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7542. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7543. (
  7544. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7545. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7546. )
  7547. )
  7548. ) and
  7549. GetNextInstruction(hp1, hp2) and
  7550. MatchInstruction(hp2, A_SAR, []) and
  7551. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7552. begin
  7553. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7554. begin
  7555. { Change:
  7556. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7557. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7558. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7559. To:
  7560. movl r/m,%eax <- Note the change in register
  7561. cltd
  7562. }
  7563. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7564. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7565. taicpu(p).loadreg(1, NR_EAX);
  7566. taicpu(hp1).opcode := A_CDQ;
  7567. taicpu(hp1).clearop(1);
  7568. taicpu(hp1).clearop(0);
  7569. taicpu(hp1).ops:=0;
  7570. RemoveInstruction(hp2);
  7571. (*
  7572. {$ifdef x86_64}
  7573. end
  7574. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7575. { This code sequence does not get generated - however it might become useful
  7576. if and when 128-bit signed integer types make an appearance, so the code
  7577. is kept here for when it is eventually needed. [Kit] }
  7578. (
  7579. (
  7580. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7581. (
  7582. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7583. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7584. )
  7585. ) or
  7586. (
  7587. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7588. (
  7589. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7590. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7591. )
  7592. )
  7593. ) and
  7594. GetNextInstruction(hp1, hp2) and
  7595. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7596. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7597. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7598. begin
  7599. { Change:
  7600. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7601. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7602. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7603. To:
  7604. movq r/m,%rax <- Note the change in register
  7605. cqto
  7606. }
  7607. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7608. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7609. taicpu(p).loadreg(1, NR_RAX);
  7610. taicpu(hp1).opcode := A_CQO;
  7611. taicpu(hp1).clearop(1);
  7612. taicpu(hp1).clearop(0);
  7613. taicpu(hp1).ops:=0;
  7614. RemoveInstruction(hp2);
  7615. {$endif x86_64}
  7616. *)
  7617. end;
  7618. end;
  7619. {$ifdef x86_64}
  7620. end
  7621. else if (taicpu(p).opsize = S_L) and
  7622. (taicpu(p).oper[1]^.typ = top_reg) and
  7623. (
  7624. MatchInstruction(hp1, A_MOV,[]) and
  7625. (taicpu(hp1).opsize = S_L) and
  7626. (taicpu(hp1).oper[1]^.typ = top_reg)
  7627. ) and (
  7628. GetNextInstruction(hp1, hp2) and
  7629. (tai(hp2).typ=ait_instruction) and
  7630. (taicpu(hp2).opsize = S_Q) and
  7631. (
  7632. (
  7633. MatchInstruction(hp2, A_ADD,[]) and
  7634. (taicpu(hp2).opsize = S_Q) and
  7635. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7636. (
  7637. (
  7638. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7639. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7640. ) or (
  7641. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7642. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7643. )
  7644. )
  7645. ) or (
  7646. MatchInstruction(hp2, A_LEA,[]) and
  7647. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7648. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7649. (
  7650. (
  7651. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7652. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7653. ) or (
  7654. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7655. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7656. )
  7657. ) and (
  7658. (
  7659. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7660. ) or (
  7661. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7662. )
  7663. )
  7664. )
  7665. )
  7666. ) and (
  7667. GetNextInstruction(hp2, hp3) and
  7668. MatchInstruction(hp3, A_SHR,[]) and
  7669. (taicpu(hp3).opsize = S_Q) and
  7670. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7671. (taicpu(hp3).oper[0]^.val = 1) and
  7672. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7673. ) then
  7674. begin
  7675. { Change movl x, reg1d movl x, reg1d
  7676. movl y, reg2d movl y, reg2d
  7677. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7678. shrq $1, reg1q shrq $1, reg1q
  7679. ( reg1d and reg2d can be switched around in the first two instructions )
  7680. To movl x, reg1d
  7681. addl y, reg1d
  7682. rcrl $1, reg1d
  7683. This corresponds to the common expression (x + y) shr 1, where
  7684. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7685. smaller code, but won't account for x + y causing an overflow). [Kit]
  7686. }
  7687. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7688. { Change first MOV command to have the same register as the final output }
  7689. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7690. else
  7691. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7692. { Change second MOV command to an ADD command. This is easier than
  7693. converting the existing command because it means we don't have to
  7694. touch 'y', which might be a complicated reference, and also the
  7695. fact that the third command might either be ADD or LEA. [Kit] }
  7696. taicpu(hp1).opcode := A_ADD;
  7697. { Delete old ADD/LEA instruction }
  7698. RemoveInstruction(hp2);
  7699. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7700. taicpu(hp3).opcode := A_RCR;
  7701. taicpu(hp3).changeopsize(S_L);
  7702. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7703. {$endif x86_64}
  7704. end;
  7705. end;
  7706. {$push}
  7707. {$q-}{$r-}
  7708. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7709. var
  7710. ThisReg: TRegister;
  7711. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7712. TargetSubReg: TSubRegister;
  7713. hp1, hp2: tai;
  7714. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7715. { Store list of found instructions so we don't have to call
  7716. GetNextInstructionUsingReg multiple times }
  7717. InstrList: array of taicpu;
  7718. InstrMax, Index: Integer;
  7719. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7720. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7721. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7722. WorkingValue: TCgInt;
  7723. PreMessage: string;
  7724. { Data flow analysis }
  7725. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7726. BitwiseOnly, OrXorUsed,
  7727. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7728. function CheckOverflowConditions: Boolean;
  7729. begin
  7730. Result := True;
  7731. if (TestValSignedMax > SignedUpperLimit) then
  7732. UpperSignedOverflow := True;
  7733. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7734. LowerSignedOverflow := True;
  7735. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7736. LowerUnsignedOverflow := True;
  7737. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7738. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7739. begin
  7740. { Absolute overflow }
  7741. Result := False;
  7742. Exit;
  7743. end;
  7744. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7745. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7746. ShiftDownOverflow := True;
  7747. if (TestValMin < 0) or (TestValMax < 0) then
  7748. begin
  7749. LowerUnsignedOverflow := True;
  7750. UpperUnsignedOverflow := True;
  7751. end;
  7752. end;
  7753. function AdjustInitialLoadAndSize: Boolean;
  7754. begin
  7755. Result := False;
  7756. if not p_removed then
  7757. begin
  7758. if TargetSize = MinSize then
  7759. begin
  7760. { Convert the input MOVZX to a MOV }
  7761. if (taicpu(p).oper[0]^.typ = top_reg) and
  7762. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7763. begin
  7764. { Or remove it completely! }
  7765. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7766. RemoveCurrentP(p);
  7767. p_removed := True;
  7768. end
  7769. else
  7770. begin
  7771. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7772. taicpu(p).opcode := A_MOV;
  7773. taicpu(p).oper[1]^.reg := ThisReg;
  7774. taicpu(p).opsize := TargetSize;
  7775. end;
  7776. Result := True;
  7777. end
  7778. else if TargetSize <> MaxSize then
  7779. begin
  7780. case MaxSize of
  7781. S_L:
  7782. if TargetSize = S_W then
  7783. begin
  7784. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7785. taicpu(p).opsize := S_BW;
  7786. taicpu(p).oper[1]^.reg := ThisReg;
  7787. Result := True;
  7788. end
  7789. else
  7790. InternalError(2020112341);
  7791. S_W:
  7792. if TargetSize = S_L then
  7793. begin
  7794. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7795. taicpu(p).opsize := S_BL;
  7796. taicpu(p).oper[1]^.reg := ThisReg;
  7797. Result := True;
  7798. end
  7799. else
  7800. InternalError(2020112342);
  7801. else
  7802. ;
  7803. end;
  7804. end
  7805. else if not hp1_removed and not RegInUse then
  7806. begin
  7807. { If we have something like:
  7808. movzbl (oper),%regd
  7809. add x, %regd
  7810. movzbl %regb, %regd
  7811. We can reduce the register size to the input of the final
  7812. movzbl instruction. Overflows won't have any effect.
  7813. }
  7814. if (taicpu(p).opsize in [S_BW, S_BL]) and
  7815. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7816. begin
  7817. TargetSize := S_B;
  7818. setsubreg(ThisReg, R_SUBL);
  7819. Result := True;
  7820. end
  7821. else if (taicpu(p).opsize = S_WL) and
  7822. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7823. begin
  7824. TargetSize := S_W;
  7825. setsubreg(ThisReg, R_SUBW);
  7826. Result := True;
  7827. end;
  7828. if Result then
  7829. begin
  7830. { Convert the input MOVZX to a MOV }
  7831. if (taicpu(p).oper[0]^.typ = top_reg) and
  7832. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7833. begin
  7834. { Or remove it completely! }
  7835. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7836. RemoveCurrentP(p);
  7837. p_removed := True;
  7838. end
  7839. else
  7840. begin
  7841. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7842. taicpu(p).opcode := A_MOV;
  7843. taicpu(p).oper[1]^.reg := ThisReg;
  7844. taicpu(p).opsize := TargetSize;
  7845. end;
  7846. end;
  7847. end;
  7848. end;
  7849. end;
  7850. procedure AdjustFinalLoad;
  7851. begin
  7852. if not LowerUnsignedOverflow then
  7853. begin
  7854. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7855. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7856. begin
  7857. { Convert the output MOVZX to a MOV }
  7858. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7859. begin
  7860. { Or remove it completely! }
  7861. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7862. { Be careful; if p = hp1 and p was also removed, p
  7863. will become a dangling pointer }
  7864. if p = hp1 then
  7865. begin
  7866. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7867. p_removed := True;
  7868. end
  7869. else
  7870. RemoveInstruction(hp1);
  7871. hp1_removed := True;
  7872. end
  7873. else
  7874. begin
  7875. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7876. taicpu(hp1).opcode := A_MOV;
  7877. taicpu(hp1).oper[0]^.reg := ThisReg;
  7878. taicpu(hp1).opsize := TargetSize;
  7879. end;
  7880. end
  7881. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7882. begin
  7883. { Need to change the size of the output }
  7884. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7885. taicpu(hp1).oper[0]^.reg := ThisReg;
  7886. taicpu(hp1).opsize := S_BL;
  7887. end;
  7888. end;
  7889. end;
  7890. function CompressInstructions: Boolean;
  7891. var
  7892. LocalIndex: Integer;
  7893. begin
  7894. Result := False;
  7895. { The objective here is to try to find a combination that
  7896. removes one of the MOV/Z instructions. }
  7897. if (
  7898. (taicpu(p).oper[0]^.typ <> top_reg) or
  7899. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7900. ) and
  7901. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7902. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7903. begin
  7904. { Make a preference to remove the second MOVZX instruction }
  7905. case taicpu(hp1).opsize of
  7906. S_BL, S_WL:
  7907. begin
  7908. TargetSize := S_L;
  7909. TargetSubReg := R_SUBD;
  7910. end;
  7911. S_BW:
  7912. begin
  7913. TargetSize := S_W;
  7914. TargetSubReg := R_SUBW;
  7915. end;
  7916. else
  7917. InternalError(2020112302);
  7918. end;
  7919. end
  7920. else
  7921. begin
  7922. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7923. begin
  7924. { Exceeded lower bound but not upper bound }
  7925. TargetSize := MaxSize;
  7926. end
  7927. else if not LowerUnsignedOverflow then
  7928. begin
  7929. { Size didn't exceed lower bound }
  7930. TargetSize := MinSize;
  7931. end
  7932. else
  7933. Exit;
  7934. end;
  7935. case TargetSize of
  7936. S_B:
  7937. TargetSubReg := R_SUBL;
  7938. S_W:
  7939. TargetSubReg := R_SUBW;
  7940. S_L:
  7941. TargetSubReg := R_SUBD;
  7942. else
  7943. InternalError(2020112350);
  7944. end;
  7945. { Update the register to its new size }
  7946. setsubreg(ThisReg, TargetSubReg);
  7947. RegInUse := False;
  7948. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7949. begin
  7950. { Check to see if the active register is used afterwards;
  7951. if not, we can change it and make a saving. }
  7952. TransferUsedRegs(TmpUsedRegs);
  7953. { The target register may be marked as in use to cross
  7954. a jump to a distant label, so exclude it }
  7955. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7956. hp2 := p;
  7957. repeat
  7958. { Explicitly check for the excluded register (don't include the first
  7959. instruction as it may be reading from here }
  7960. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7961. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7962. begin
  7963. RegInUse := True;
  7964. Break;
  7965. end;
  7966. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7967. if not GetNextInstruction(hp2, hp2) then
  7968. InternalError(2020112340);
  7969. until (hp2 = hp1);
  7970. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7971. { We might still be able to get away with this }
  7972. RegInUse := not
  7973. (
  7974. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7975. (hp2.typ = ait_instruction) and
  7976. (
  7977. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7978. instruction that doesn't actually contain ThisReg }
  7979. (cs_opt_level3 in current_settings.optimizerswitches) or
  7980. RegInInstruction(ThisReg, hp2)
  7981. ) and
  7982. RegLoadedWithNewValue(ThisReg, hp2)
  7983. );
  7984. if not RegInUse then
  7985. begin
  7986. { Force the register size to the same as this instruction so it can be removed}
  7987. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7988. begin
  7989. TargetSize := S_L;
  7990. TargetSubReg := R_SUBD;
  7991. end
  7992. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7993. begin
  7994. TargetSize := S_W;
  7995. TargetSubReg := R_SUBW;
  7996. end;
  7997. ThisReg := taicpu(hp1).oper[1]^.reg;
  7998. setsubreg(ThisReg, TargetSubReg);
  7999. RegChanged := True;
  8000. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8001. TransferUsedRegs(TmpUsedRegs);
  8002. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8003. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8004. if p = hp1 then
  8005. begin
  8006. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8007. p_removed := True;
  8008. end
  8009. else
  8010. RemoveInstruction(hp1);
  8011. hp1_removed := True;
  8012. { Instruction will become "mov %reg,%reg" }
  8013. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8014. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8015. begin
  8016. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8017. RemoveCurrentP(p);
  8018. p_removed := True;
  8019. end
  8020. else
  8021. taicpu(p).oper[1]^.reg := ThisReg;
  8022. Result := True;
  8023. end
  8024. else
  8025. begin
  8026. if TargetSize <> MaxSize then
  8027. begin
  8028. { Since the register is in use, we have to force it to
  8029. MaxSize otherwise part of it may become undefined later on }
  8030. TargetSize := MaxSize;
  8031. case TargetSize of
  8032. S_B:
  8033. TargetSubReg := R_SUBL;
  8034. S_W:
  8035. TargetSubReg := R_SUBW;
  8036. S_L:
  8037. TargetSubReg := R_SUBD;
  8038. else
  8039. InternalError(2020112351);
  8040. end;
  8041. setsubreg(ThisReg, TargetSubReg);
  8042. end;
  8043. AdjustFinalLoad;
  8044. end;
  8045. end
  8046. else
  8047. AdjustFinalLoad;
  8048. Result := AdjustInitialLoadAndSize or Result;
  8049. { Now go through every instruction we found and change the
  8050. size. If TargetSize = MaxSize, then almost no changes are
  8051. needed and Result can remain False if it hasn't been set
  8052. yet.
  8053. If RegChanged is True, then the register requires changing
  8054. and so the point about TargetSize = MaxSize doesn't apply. }
  8055. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8056. begin
  8057. for LocalIndex := 0 to InstrMax do
  8058. begin
  8059. { If p_removed is true, then the original MOV/Z was removed
  8060. and removing the AND instruction may not be safe if it
  8061. appears first }
  8062. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8063. InternalError(2020112310);
  8064. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8065. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8066. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8067. InstrList[LocalIndex].opsize := TargetSize;
  8068. end;
  8069. Result := True;
  8070. end;
  8071. end;
  8072. begin
  8073. Result := False;
  8074. p_removed := False;
  8075. hp1_removed := False;
  8076. ThisReg := taicpu(p).oper[1]^.reg;
  8077. { Check for:
  8078. movs/z ###,%ecx (or %cx or %rcx)
  8079. ...
  8080. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8081. (dealloc %ecx)
  8082. Change to:
  8083. mov ###,%cl (if ### = %cl, then remove completely)
  8084. ...
  8085. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8086. }
  8087. if (getsupreg(ThisReg) = RS_ECX) and
  8088. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8089. (hp1.typ = ait_instruction) and
  8090. (
  8091. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8092. instruction that doesn't actually contain ECX }
  8093. (cs_opt_level3 in current_settings.optimizerswitches) or
  8094. RegInInstruction(NR_ECX, hp1) or
  8095. (
  8096. { It's common for the shift/rotate's read/write register to be
  8097. initialised in between, so under -O2 and under, search ahead
  8098. one more instruction
  8099. }
  8100. GetNextInstruction(hp1, hp1) and
  8101. (hp1.typ = ait_instruction) and
  8102. RegInInstruction(NR_ECX, hp1)
  8103. )
  8104. ) and
  8105. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8106. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8107. begin
  8108. TransferUsedRegs(TmpUsedRegs);
  8109. hp2 := p;
  8110. repeat
  8111. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8112. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8113. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8114. begin
  8115. case taicpu(p).opsize of
  8116. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8117. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8118. begin
  8119. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8120. RemoveCurrentP(p);
  8121. end
  8122. else
  8123. begin
  8124. taicpu(p).opcode := A_MOV;
  8125. taicpu(p).opsize := S_B;
  8126. taicpu(p).oper[1]^.reg := NR_CL;
  8127. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8128. end;
  8129. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8130. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8131. begin
  8132. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8133. RemoveCurrentP(p);
  8134. end
  8135. else
  8136. begin
  8137. taicpu(p).opcode := A_MOV;
  8138. taicpu(p).opsize := S_W;
  8139. taicpu(p).oper[1]^.reg := NR_CX;
  8140. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8141. end;
  8142. {$ifdef x86_64}
  8143. S_LQ:
  8144. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8145. begin
  8146. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8147. RemoveCurrentP(p);
  8148. end
  8149. else
  8150. begin
  8151. taicpu(p).opcode := A_MOV;
  8152. taicpu(p).opsize := S_L;
  8153. taicpu(p).oper[1]^.reg := NR_ECX;
  8154. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8155. end;
  8156. {$endif x86_64}
  8157. else
  8158. InternalError(2021120401);
  8159. end;
  8160. Result := True;
  8161. Exit;
  8162. end;
  8163. end;
  8164. { This is anything but quick! }
  8165. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8166. Exit;
  8167. SetLength(InstrList, 0);
  8168. InstrMax := -1;
  8169. case taicpu(p).opsize of
  8170. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8171. begin
  8172. {$if defined(i386) or defined(i8086)}
  8173. { If the target size is 8-bit, make sure we can actually encode it }
  8174. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8175. Exit;
  8176. {$endif i386 or i8086}
  8177. LowerLimit := $FF;
  8178. SignedLowerLimit := $7F;
  8179. SignedLowerLimitBottom := -128;
  8180. MinSize := S_B;
  8181. if taicpu(p).opsize = S_BW then
  8182. begin
  8183. MaxSize := S_W;
  8184. UpperLimit := $FFFF;
  8185. SignedUpperLimit := $7FFF;
  8186. SignedUpperLimitBottom := -32768;
  8187. end
  8188. else
  8189. begin
  8190. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8191. MaxSize := S_L;
  8192. UpperLimit := $FFFFFFFF;
  8193. SignedUpperLimit := $7FFFFFFF;
  8194. SignedUpperLimitBottom := -2147483648;
  8195. end;
  8196. end;
  8197. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8198. begin
  8199. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8200. LowerLimit := $FFFF;
  8201. SignedLowerLimit := $7FFF;
  8202. SignedLowerLimitBottom := -32768;
  8203. UpperLimit := $FFFFFFFF;
  8204. SignedUpperLimit := $7FFFFFFF;
  8205. SignedUpperLimitBottom := -2147483648;
  8206. MinSize := S_W;
  8207. MaxSize := S_L;
  8208. end;
  8209. {$ifdef x86_64}
  8210. S_LQ:
  8211. begin
  8212. { Both the lower and upper limits are set to 32-bit. If a limit
  8213. is breached, then optimisation is impossible }
  8214. LowerLimit := $FFFFFFFF;
  8215. SignedLowerLimit := $7FFFFFFF;
  8216. SignedLowerLimitBottom := -2147483648;
  8217. UpperLimit := $FFFFFFFF;
  8218. SignedUpperLimit := $7FFFFFFF;
  8219. SignedUpperLimitBottom := -2147483648;
  8220. MinSize := S_L;
  8221. MaxSize := S_L;
  8222. end;
  8223. {$endif x86_64}
  8224. else
  8225. InternalError(2020112301);
  8226. end;
  8227. TestValMin := 0;
  8228. TestValMax := LowerLimit;
  8229. TestValSignedMax := SignedLowerLimit;
  8230. TryShiftDownLimit := LowerLimit;
  8231. TryShiftDown := S_NO;
  8232. ShiftDownOverflow := False;
  8233. RegChanged := False;
  8234. BitwiseOnly := True;
  8235. OrXorUsed := False;
  8236. UpperSignedOverflow := False;
  8237. LowerSignedOverflow := False;
  8238. UpperUnsignedOverflow := False;
  8239. LowerUnsignedOverflow := False;
  8240. hp1 := p;
  8241. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8242. (hp1.typ = ait_instruction) and
  8243. (
  8244. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8245. instruction that doesn't actually contain ThisReg }
  8246. (cs_opt_level3 in current_settings.optimizerswitches) or
  8247. { This allows this Movx optimisation to work through the SETcc instructions
  8248. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8249. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8250. skip over these SETcc instructions). }
  8251. (taicpu(hp1).opcode = A_SETcc) or
  8252. RegInInstruction(ThisReg, hp1)
  8253. ) do
  8254. begin
  8255. case taicpu(hp1).opcode of
  8256. A_INC,A_DEC:
  8257. begin
  8258. { Has to be an exact match on the register }
  8259. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8260. Break;
  8261. if taicpu(hp1).opcode = A_INC then
  8262. begin
  8263. Inc(TestValMin);
  8264. Inc(TestValMax);
  8265. Inc(TestValSignedMax);
  8266. end
  8267. else
  8268. begin
  8269. Dec(TestValMin);
  8270. Dec(TestValMax);
  8271. Dec(TestValSignedMax);
  8272. end;
  8273. end;
  8274. A_TEST, A_CMP:
  8275. begin
  8276. if (
  8277. { Too high a risk of non-linear behaviour that breaks DFA
  8278. here, unless it's cmp $0,%reg, which is equivalent to
  8279. test %reg,%reg }
  8280. OrXorUsed and
  8281. (taicpu(hp1).opcode = A_CMP) and
  8282. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8283. ) or
  8284. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8285. { Has to be an exact match on the register }
  8286. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8287. (
  8288. { Permit "test %reg,%reg" }
  8289. (taicpu(hp1).opcode = A_TEST) and
  8290. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8291. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8292. ) or
  8293. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8294. { Make sure the comparison value is not smaller than the
  8295. smallest allowed signed value for the minimum size (e.g.
  8296. -128 for 8-bit) }
  8297. not (
  8298. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8299. { Is it in the negative range? }
  8300. (
  8301. (taicpu(hp1).oper[0]^.val < 0) and
  8302. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8303. )
  8304. ) then
  8305. Break;
  8306. { Check to see if the active register is used afterwards }
  8307. TransferUsedRegs(TmpUsedRegs);
  8308. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8309. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8310. begin
  8311. { Make sure the comparison or any previous instructions
  8312. hasn't pushed the test values outside of the range of
  8313. MinSize }
  8314. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8315. begin
  8316. { Exceeded lower bound but not upper bound }
  8317. Exit;
  8318. end
  8319. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8320. begin
  8321. { Size didn't exceed lower bound }
  8322. TargetSize := MinSize;
  8323. end
  8324. else
  8325. Break;
  8326. case TargetSize of
  8327. S_B:
  8328. TargetSubReg := R_SUBL;
  8329. S_W:
  8330. TargetSubReg := R_SUBW;
  8331. S_L:
  8332. TargetSubReg := R_SUBD;
  8333. else
  8334. InternalError(2021051002);
  8335. end;
  8336. if TargetSize <> MaxSize then
  8337. begin
  8338. { Update the register to its new size }
  8339. setsubreg(ThisReg, TargetSubReg);
  8340. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8341. taicpu(hp1).oper[1]^.reg := ThisReg;
  8342. taicpu(hp1).opsize := TargetSize;
  8343. { Convert the input MOVZX to a MOV if necessary }
  8344. AdjustInitialLoadAndSize;
  8345. if (InstrMax >= 0) then
  8346. begin
  8347. for Index := 0 to InstrMax do
  8348. begin
  8349. { If p_removed is true, then the original MOV/Z was removed
  8350. and removing the AND instruction may not be safe if it
  8351. appears first }
  8352. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8353. InternalError(2020112311);
  8354. if InstrList[Index].oper[0]^.typ = top_reg then
  8355. InstrList[Index].oper[0]^.reg := ThisReg;
  8356. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8357. InstrList[Index].opsize := MinSize;
  8358. end;
  8359. end;
  8360. Result := True;
  8361. end;
  8362. Exit;
  8363. end;
  8364. end;
  8365. A_SETcc:
  8366. begin
  8367. { This allows this Movx optimisation to work through the SETcc instructions
  8368. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8369. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8370. skip over these SETcc instructions). }
  8371. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8372. { Of course, break out if the current register is used }
  8373. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8374. Break
  8375. else
  8376. { We must use Continue so the instruction doesn't get added
  8377. to InstrList }
  8378. Continue;
  8379. end;
  8380. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8381. begin
  8382. if
  8383. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8384. { Has to be an exact match on the register }
  8385. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8386. (
  8387. (
  8388. (taicpu(hp1).oper[0]^.typ = top_const) and
  8389. (
  8390. (
  8391. (taicpu(hp1).opcode = A_SHL) and
  8392. (
  8393. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8394. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8395. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8396. )
  8397. ) or (
  8398. (taicpu(hp1).opcode <> A_SHL) and
  8399. (
  8400. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8401. { Is it in the negative range? }
  8402. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8403. )
  8404. )
  8405. )
  8406. ) or (
  8407. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8408. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8409. )
  8410. ) then
  8411. Break;
  8412. { Only process OR and XOR if there are only bitwise operations,
  8413. since otherwise they can too easily fool the data flow
  8414. analysis (they can cause non-linear behaviour) }
  8415. case taicpu(hp1).opcode of
  8416. A_ADD:
  8417. begin
  8418. if OrXorUsed then
  8419. { Too high a risk of non-linear behaviour that breaks DFA here }
  8420. Break
  8421. else
  8422. BitwiseOnly := False;
  8423. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8424. begin
  8425. TestValMin := TestValMin * 2;
  8426. TestValMax := TestValMax * 2;
  8427. TestValSignedMax := TestValSignedMax * 2;
  8428. end
  8429. else
  8430. begin
  8431. WorkingValue := taicpu(hp1).oper[0]^.val;
  8432. TestValMin := TestValMin + WorkingValue;
  8433. TestValMax := TestValMax + WorkingValue;
  8434. TestValSignedMax := TestValSignedMax + WorkingValue;
  8435. end;
  8436. end;
  8437. A_SUB:
  8438. begin
  8439. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8440. begin
  8441. TestValMin := 0;
  8442. TestValMax := 0;
  8443. TestValSignedMax := 0;
  8444. end
  8445. else
  8446. begin
  8447. if OrXorUsed then
  8448. { Too high a risk of non-linear behaviour that breaks DFA here }
  8449. Break
  8450. else
  8451. BitwiseOnly := False;
  8452. WorkingValue := taicpu(hp1).oper[0]^.val;
  8453. TestValMin := TestValMin - WorkingValue;
  8454. TestValMax := TestValMax - WorkingValue;
  8455. TestValSignedMax := TestValSignedMax - WorkingValue;
  8456. end;
  8457. end;
  8458. A_AND:
  8459. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8460. begin
  8461. { we might be able to go smaller if AND appears first }
  8462. if InstrMax = -1 then
  8463. case MinSize of
  8464. S_B:
  8465. ;
  8466. S_W:
  8467. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8468. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8469. begin
  8470. TryShiftDown := S_B;
  8471. TryShiftDownLimit := $FF;
  8472. end;
  8473. S_L:
  8474. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8475. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8476. begin
  8477. TryShiftDown := S_B;
  8478. TryShiftDownLimit := $FF;
  8479. end
  8480. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8481. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8482. begin
  8483. TryShiftDown := S_W;
  8484. TryShiftDownLimit := $FFFF;
  8485. end;
  8486. else
  8487. InternalError(2020112320);
  8488. end;
  8489. WorkingValue := taicpu(hp1).oper[0]^.val;
  8490. TestValMin := TestValMin and WorkingValue;
  8491. TestValMax := TestValMax and WorkingValue;
  8492. TestValSignedMax := TestValSignedMax and WorkingValue;
  8493. end;
  8494. A_OR:
  8495. begin
  8496. if not BitwiseOnly then
  8497. Break;
  8498. OrXorUsed := True;
  8499. WorkingValue := taicpu(hp1).oper[0]^.val;
  8500. TestValMin := TestValMin or WorkingValue;
  8501. TestValMax := TestValMax or WorkingValue;
  8502. TestValSignedMax := TestValSignedMax or WorkingValue;
  8503. end;
  8504. A_XOR:
  8505. begin
  8506. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8507. begin
  8508. TestValMin := 0;
  8509. TestValMax := 0;
  8510. TestValSignedMax := 0;
  8511. end
  8512. else
  8513. begin
  8514. if not BitwiseOnly then
  8515. Break;
  8516. OrXorUsed := True;
  8517. WorkingValue := taicpu(hp1).oper[0]^.val;
  8518. TestValMin := TestValMin xor WorkingValue;
  8519. TestValMax := TestValMax xor WorkingValue;
  8520. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8521. end;
  8522. end;
  8523. A_SHL:
  8524. begin
  8525. BitwiseOnly := False;
  8526. WorkingValue := taicpu(hp1).oper[0]^.val;
  8527. TestValMin := TestValMin shl WorkingValue;
  8528. TestValMax := TestValMax shl WorkingValue;
  8529. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8530. end;
  8531. A_SHR,
  8532. { The first instruction was MOVZX, so the value won't be negative }
  8533. A_SAR:
  8534. begin
  8535. if InstrMax <> -1 then
  8536. BitwiseOnly := False
  8537. else
  8538. { we might be able to go smaller if SHR appears first }
  8539. case MinSize of
  8540. S_B:
  8541. ;
  8542. S_W:
  8543. if (taicpu(hp1).oper[0]^.val >= 8) then
  8544. begin
  8545. TryShiftDown := S_B;
  8546. TryShiftDownLimit := $FF;
  8547. TryShiftDownSignedLimit := $7F;
  8548. TryShiftDownSignedLimitLower := -128;
  8549. end;
  8550. S_L:
  8551. if (taicpu(hp1).oper[0]^.val >= 24) then
  8552. begin
  8553. TryShiftDown := S_B;
  8554. TryShiftDownLimit := $FF;
  8555. TryShiftDownSignedLimit := $7F;
  8556. TryShiftDownSignedLimitLower := -128;
  8557. end
  8558. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8559. begin
  8560. TryShiftDown := S_W;
  8561. TryShiftDownLimit := $FFFF;
  8562. TryShiftDownSignedLimit := $7FFF;
  8563. TryShiftDownSignedLimitLower := -32768;
  8564. end;
  8565. else
  8566. InternalError(2020112321);
  8567. end;
  8568. WorkingValue := taicpu(hp1).oper[0]^.val;
  8569. if taicpu(hp1).opcode = A_SAR then
  8570. begin
  8571. TestValMin := SarInt64(TestValMin, WorkingValue);
  8572. TestValMax := SarInt64(TestValMax, WorkingValue);
  8573. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8574. end
  8575. else
  8576. begin
  8577. TestValMin := TestValMin shr WorkingValue;
  8578. TestValMax := TestValMax shr WorkingValue;
  8579. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8580. end;
  8581. end;
  8582. else
  8583. InternalError(2020112303);
  8584. end;
  8585. end;
  8586. (*
  8587. A_IMUL:
  8588. case taicpu(hp1).ops of
  8589. 2:
  8590. begin
  8591. if not MatchOpType(hp1, top_reg, top_reg) or
  8592. { Has to be an exact match on the register }
  8593. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8594. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8595. Break;
  8596. TestValMin := TestValMin * TestValMin;
  8597. TestValMax := TestValMax * TestValMax;
  8598. TestValSignedMax := TestValSignedMax * TestValMax;
  8599. end;
  8600. 3:
  8601. begin
  8602. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8603. { Has to be an exact match on the register }
  8604. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8605. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8606. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8607. { Is it in the negative range? }
  8608. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8609. Break;
  8610. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8611. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8612. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8613. end;
  8614. else
  8615. Break;
  8616. end;
  8617. A_IDIV:
  8618. case taicpu(hp1).ops of
  8619. 3:
  8620. begin
  8621. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8622. { Has to be an exact match on the register }
  8623. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8624. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8625. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8626. { Is it in the negative range? }
  8627. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8628. Break;
  8629. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8630. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8631. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8632. end;
  8633. else
  8634. Break;
  8635. end;
  8636. *)
  8637. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8638. begin
  8639. { If there are no instructions in between, then we might be able to make a saving }
  8640. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8641. Break;
  8642. { We have something like:
  8643. movzbw %dl,%dx
  8644. ...
  8645. movswl %dx,%edx
  8646. Change the latter to a zero-extension then enter the
  8647. A_MOVZX case branch.
  8648. }
  8649. {$ifdef x86_64}
  8650. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8651. begin
  8652. { this becomes a zero extension from 32-bit to 64-bit, but
  8653. the upper 32 bits are already zero, so just delete the
  8654. instruction }
  8655. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8656. RemoveInstruction(hp1);
  8657. Result := True;
  8658. Exit;
  8659. end
  8660. else
  8661. {$endif x86_64}
  8662. begin
  8663. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8664. taicpu(hp1).opcode := A_MOVZX;
  8665. {$ifdef x86_64}
  8666. case taicpu(hp1).opsize of
  8667. S_BQ:
  8668. begin
  8669. taicpu(hp1).opsize := S_BL;
  8670. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8671. end;
  8672. S_WQ:
  8673. begin
  8674. taicpu(hp1).opsize := S_WL;
  8675. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8676. end;
  8677. S_LQ:
  8678. begin
  8679. taicpu(hp1).opcode := A_MOV;
  8680. taicpu(hp1).opsize := S_L;
  8681. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8682. { In this instance, we need to break out because the
  8683. instruction is no longer MOVZX or MOVSXD }
  8684. Result := True;
  8685. Exit;
  8686. end;
  8687. else
  8688. ;
  8689. end;
  8690. {$endif x86_64}
  8691. Result := CompressInstructions;
  8692. Exit;
  8693. end;
  8694. end;
  8695. A_MOVZX:
  8696. begin
  8697. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8698. Break;
  8699. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8700. begin
  8701. if (InstrMax = -1) and
  8702. { Will return false if the second parameter isn't ThisReg
  8703. (can happen on -O2 and under) }
  8704. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8705. begin
  8706. { The two MOVZX instructions are adjacent, so remove the first one }
  8707. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8708. RemoveCurrentP(p);
  8709. Result := True;
  8710. Exit;
  8711. end;
  8712. Break;
  8713. end;
  8714. Result := CompressInstructions;
  8715. Exit;
  8716. end;
  8717. else
  8718. { This includes ADC, SBB and IDIV }
  8719. Break;
  8720. end;
  8721. if not CheckOverflowConditions then
  8722. Break;
  8723. { Contains highest index (so instruction count - 1) }
  8724. Inc(InstrMax);
  8725. if InstrMax > High(InstrList) then
  8726. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8727. InstrList[InstrMax] := taicpu(hp1);
  8728. end;
  8729. end;
  8730. {$pop}
  8731. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8732. var
  8733. hp1 : tai;
  8734. begin
  8735. Result:=false;
  8736. if (taicpu(p).ops >= 2) and
  8737. ((taicpu(p).oper[0]^.typ = top_const) or
  8738. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8739. (taicpu(p).oper[1]^.typ = top_reg) and
  8740. ((taicpu(p).ops = 2) or
  8741. ((taicpu(p).oper[2]^.typ = top_reg) and
  8742. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8743. GetLastInstruction(p,hp1) and
  8744. MatchInstruction(hp1,A_MOV,[]) and
  8745. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8746. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8747. begin
  8748. TransferUsedRegs(TmpUsedRegs);
  8749. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8750. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8751. { change
  8752. mov reg1,reg2
  8753. imul y,reg2 to imul y,reg1,reg2 }
  8754. begin
  8755. taicpu(p).ops := 3;
  8756. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8757. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8758. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8759. RemoveInstruction(hp1);
  8760. result:=true;
  8761. end;
  8762. end;
  8763. end;
  8764. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8765. var
  8766. ThisLabel: TAsmLabel;
  8767. begin
  8768. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8769. ThisLabel.decrefs;
  8770. taicpu(p).opcode := A_RET;
  8771. taicpu(p).is_jmp := false;
  8772. taicpu(p).ops := taicpu(ret_p).ops;
  8773. case taicpu(ret_p).ops of
  8774. 0:
  8775. taicpu(p).clearop(0);
  8776. 1:
  8777. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8778. else
  8779. internalerror(2016041301);
  8780. end;
  8781. { If the original label is now dead, it might turn out that the label
  8782. immediately follows p. As a result, everything beyond it, which will
  8783. be just some final register configuration and a RET instruction, is
  8784. now dead code. [Kit] }
  8785. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8786. running RemoveDeadCodeAfterJump for each RET instruction, because
  8787. this optimisation rarely happens and most RETs appear at the end of
  8788. routines where there is nothing that can be stripped. [Kit] }
  8789. if not ThisLabel.is_used then
  8790. RemoveDeadCodeAfterJump(p);
  8791. end;
  8792. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8793. var
  8794. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8795. Unconditional, PotentialModified: Boolean;
  8796. OperPtr: POper;
  8797. NewRef: TReference;
  8798. InstrList: array of taicpu;
  8799. InstrMax, Index: Integer;
  8800. const
  8801. {$ifdef DEBUG_AOPTCPU}
  8802. SNoFlags: shortstring = ' so the flags aren''t modified';
  8803. {$else DEBUG_AOPTCPU}
  8804. SNoFlags = '';
  8805. {$endif DEBUG_AOPTCPU}
  8806. begin
  8807. Result:=false;
  8808. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8809. begin
  8810. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8811. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8812. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8813. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8814. GetNextInstruction(hp1, hp2) and
  8815. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8816. { Change from: To:
  8817. set(C) %reg j(~C) label
  8818. test %reg,%reg/cmp $0,%reg
  8819. je label
  8820. set(C) %reg j(C) label
  8821. test %reg,%reg/cmp $0,%reg
  8822. jne label
  8823. (Also do something similar with sete/setne instead of je/jne)
  8824. }
  8825. begin
  8826. { Before we do anything else, we need to check the instructions
  8827. in between SETcc and TEST to make sure they don't modify the
  8828. FLAGS register - if -O2 or under, there won't be any
  8829. instructions between SET and TEST }
  8830. TransferUsedRegs(TmpUsedRegs);
  8831. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8832. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8833. begin
  8834. next := p;
  8835. SetLength(InstrList, 0);
  8836. InstrMax := -1;
  8837. PotentialModified := False;
  8838. { Make a note of every instruction that modifies the FLAGS
  8839. register }
  8840. while GetNextInstruction(next, next) and (next <> hp1) do
  8841. begin
  8842. if next.typ <> ait_instruction then
  8843. { GetNextInstructionUsingReg should have returned False }
  8844. InternalError(2021051701);
  8845. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8846. begin
  8847. case taicpu(next).opcode of
  8848. A_SETcc,
  8849. A_CMOVcc,
  8850. A_Jcc:
  8851. begin
  8852. if PotentialModified then
  8853. { Not safe because the flags were modified earlier }
  8854. Exit
  8855. else
  8856. { Condition is the same as the initial SETcc, so this is safe
  8857. (don't add to instruction list though) }
  8858. Continue;
  8859. end;
  8860. A_ADD:
  8861. begin
  8862. if (taicpu(next).opsize = S_B) or
  8863. { LEA doesn't support 8-bit operands }
  8864. (taicpu(next).oper[1]^.typ <> top_reg) or
  8865. { Must write to a register }
  8866. (taicpu(next).oper[0]^.typ = top_ref) then
  8867. { Require a constant or a register }
  8868. Exit;
  8869. PotentialModified := True;
  8870. end;
  8871. A_SUB:
  8872. begin
  8873. if (taicpu(next).opsize = S_B) or
  8874. { LEA doesn't support 8-bit operands }
  8875. (taicpu(next).oper[1]^.typ <> top_reg) or
  8876. { Must write to a register }
  8877. (taicpu(next).oper[0]^.typ <> top_const) or
  8878. (taicpu(next).oper[0]^.val = $80000000) then
  8879. { Can't subtract a register with LEA - also
  8880. check that the value isn't -2^31, as this
  8881. can't be negated }
  8882. Exit;
  8883. PotentialModified := True;
  8884. end;
  8885. A_SAL,
  8886. A_SHL:
  8887. begin
  8888. if (taicpu(next).opsize = S_B) or
  8889. { LEA doesn't support 8-bit operands }
  8890. (taicpu(next).oper[1]^.typ <> top_reg) or
  8891. { Must write to a register }
  8892. (taicpu(next).oper[0]^.typ <> top_const) or
  8893. (taicpu(next).oper[0]^.val < 0) or
  8894. (taicpu(next).oper[0]^.val > 3) then
  8895. Exit;
  8896. PotentialModified := True;
  8897. end;
  8898. A_IMUL:
  8899. begin
  8900. if (taicpu(next).ops <> 3) or
  8901. (taicpu(next).oper[1]^.typ <> top_reg) or
  8902. { Must write to a register }
  8903. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8904. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8905. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8906. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8907. Exit
  8908. else
  8909. PotentialModified := True;
  8910. end;
  8911. else
  8912. { Don't know how to change this, so abort }
  8913. Exit;
  8914. end;
  8915. { Contains highest index (so instruction count - 1) }
  8916. Inc(InstrMax);
  8917. if InstrMax > High(InstrList) then
  8918. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8919. InstrList[InstrMax] := taicpu(next);
  8920. end;
  8921. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8922. end;
  8923. if not Assigned(next) or (next <> hp1) then
  8924. { It should be equal to hp1 }
  8925. InternalError(2021051702);
  8926. { Cycle through each instruction and check to see if we can
  8927. change them to versions that don't modify the flags }
  8928. if (InstrMax >= 0) then
  8929. begin
  8930. for Index := 0 to InstrMax do
  8931. case InstrList[Index].opcode of
  8932. A_ADD:
  8933. begin
  8934. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8935. InstrList[Index].opcode := A_LEA;
  8936. reference_reset(NewRef, 1, []);
  8937. NewRef.base := InstrList[Index].oper[1]^.reg;
  8938. if InstrList[Index].oper[0]^.typ = top_reg then
  8939. begin
  8940. NewRef.index := InstrList[Index].oper[0]^.reg;
  8941. NewRef.scalefactor := 1;
  8942. end
  8943. else
  8944. NewRef.offset := InstrList[Index].oper[0]^.val;
  8945. InstrList[Index].loadref(0, NewRef);
  8946. end;
  8947. A_SUB:
  8948. begin
  8949. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8950. InstrList[Index].opcode := A_LEA;
  8951. reference_reset(NewRef, 1, []);
  8952. NewRef.base := InstrList[Index].oper[1]^.reg;
  8953. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8954. InstrList[Index].loadref(0, NewRef);
  8955. end;
  8956. A_SHL,
  8957. A_SAL:
  8958. begin
  8959. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8960. InstrList[Index].opcode := A_LEA;
  8961. reference_reset(NewRef, 1, []);
  8962. NewRef.index := InstrList[Index].oper[1]^.reg;
  8963. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8964. InstrList[Index].loadref(0, NewRef);
  8965. end;
  8966. A_IMUL:
  8967. begin
  8968. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8969. InstrList[Index].opcode := A_LEA;
  8970. reference_reset(NewRef, 1, []);
  8971. NewRef.index := InstrList[Index].oper[1]^.reg;
  8972. case InstrList[Index].oper[0]^.val of
  8973. 2, 4, 8:
  8974. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8975. else {3, 5 and 9}
  8976. begin
  8977. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8978. NewRef.base := InstrList[Index].oper[1]^.reg;
  8979. end;
  8980. end;
  8981. InstrList[Index].loadref(0, NewRef);
  8982. end;
  8983. else
  8984. InternalError(2021051710);
  8985. end;
  8986. end;
  8987. { Mark the FLAGS register as used across this whole block }
  8988. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8989. end;
  8990. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8991. JumpC := taicpu(hp2).condition;
  8992. Unconditional := False;
  8993. if conditions_equal(JumpC, C_E) then
  8994. SetC := inverse_cond(taicpu(p).condition)
  8995. else if conditions_equal(JumpC, C_NE) then
  8996. SetC := taicpu(p).condition
  8997. else
  8998. { We've got something weird here (and inefficent) }
  8999. begin
  9000. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9001. SetC := C_NONE;
  9002. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9003. if condition_in(C_AE, JumpC) then
  9004. Unconditional := True
  9005. else
  9006. { Not sure what to do with this jump - drop out }
  9007. Exit;
  9008. end;
  9009. RemoveInstruction(hp1);
  9010. if Unconditional then
  9011. MakeUnconditional(taicpu(hp2))
  9012. else
  9013. begin
  9014. if SetC = C_NONE then
  9015. InternalError(2018061402);
  9016. taicpu(hp2).SetCondition(SetC);
  9017. end;
  9018. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9019. TmpUsedRegs }
  9020. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9021. begin
  9022. RemoveCurrentp(p, hp2);
  9023. if taicpu(hp2).opcode = A_SETcc then
  9024. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9025. else
  9026. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9027. end
  9028. else
  9029. if taicpu(hp2).opcode = A_SETcc then
  9030. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9031. else
  9032. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9033. Result := True;
  9034. end
  9035. else if
  9036. { Make sure the instructions are adjacent }
  9037. (
  9038. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9039. GetNextInstruction(p, hp1)
  9040. ) and
  9041. MatchInstruction(hp1, A_MOV, [S_B]) and
  9042. { Writing to memory is allowed }
  9043. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9044. begin
  9045. {
  9046. Watch out for sequences such as:
  9047. set(c)b %regb
  9048. movb %regb,(ref)
  9049. movb $0,1(ref)
  9050. movb $0,2(ref)
  9051. movb $0,3(ref)
  9052. Much more efficient to turn it into:
  9053. movl $0,%regl
  9054. set(c)b %regb
  9055. movl %regl,(ref)
  9056. Or:
  9057. set(c)b %regb
  9058. movzbl %regb,%regl
  9059. movl %regl,(ref)
  9060. }
  9061. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9062. GetNextInstruction(hp1, hp2) and
  9063. MatchInstruction(hp2, A_MOV, [S_B]) and
  9064. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9065. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9066. begin
  9067. { Don't do anything else except set Result to True }
  9068. end
  9069. else
  9070. begin
  9071. if taicpu(p).oper[0]^.typ = top_reg then
  9072. begin
  9073. TransferUsedRegs(TmpUsedRegs);
  9074. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9075. end;
  9076. { If it's not a register, it's a memory address }
  9077. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9078. begin
  9079. { Even if the register is still in use, we can minimise the
  9080. pipeline stall by changing the MOV into another SETcc. }
  9081. taicpu(hp1).opcode := A_SETcc;
  9082. taicpu(hp1).condition := taicpu(p).condition;
  9083. if taicpu(hp1).oper[1]^.typ = top_ref then
  9084. begin
  9085. { Swapping the operand pointers like this is probably a
  9086. bit naughty, but it is far faster than using loadoper
  9087. to transfer the reference from oper[1] to oper[0] if
  9088. you take into account the extra procedure calls and
  9089. the memory allocation and deallocation required }
  9090. OperPtr := taicpu(hp1).oper[1];
  9091. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9092. taicpu(hp1).oper[0] := OperPtr;
  9093. end
  9094. else
  9095. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9096. taicpu(hp1).clearop(1);
  9097. taicpu(hp1).ops := 1;
  9098. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9099. end
  9100. else
  9101. begin
  9102. if taicpu(hp1).oper[1]^.typ = top_reg then
  9103. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9104. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9105. RemoveInstruction(hp1);
  9106. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9107. end
  9108. end;
  9109. Result := True;
  9110. end;
  9111. end;
  9112. end;
  9113. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9114. var
  9115. hp1: tai;
  9116. Count: Integer;
  9117. OrigLabel: TAsmLabel;
  9118. begin
  9119. result := False;
  9120. { Sometimes, the optimisations below can permit this }
  9121. RemoveDeadCodeAfterJump(p);
  9122. 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
  9123. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9124. begin
  9125. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9126. { Also a side-effect of optimisations }
  9127. if CollapseZeroDistJump(p, OrigLabel) then
  9128. begin
  9129. Result := True;
  9130. Exit;
  9131. end;
  9132. hp1 := GetLabelWithSym(OrigLabel);
  9133. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9134. begin
  9135. case taicpu(hp1).opcode of
  9136. A_RET:
  9137. {
  9138. change
  9139. jmp .L1
  9140. ...
  9141. .L1:
  9142. ret
  9143. into
  9144. ret
  9145. }
  9146. begin
  9147. ConvertJumpToRET(p, hp1);
  9148. result:=true;
  9149. end;
  9150. { Check any kind of direct assignment instruction }
  9151. A_MOV,
  9152. A_MOVD,
  9153. A_MOVQ,
  9154. A_MOVSX,
  9155. {$ifdef x86_64}
  9156. A_MOVSXD,
  9157. {$endif x86_64}
  9158. A_MOVZX,
  9159. A_MOVAPS,
  9160. A_MOVUPS,
  9161. A_MOVSD,
  9162. A_MOVAPD,
  9163. A_MOVUPD,
  9164. A_MOVDQA,
  9165. A_MOVDQU,
  9166. A_VMOVSS,
  9167. A_VMOVAPS,
  9168. A_VMOVUPS,
  9169. A_VMOVSD,
  9170. A_VMOVAPD,
  9171. A_VMOVUPD,
  9172. A_VMOVDQA,
  9173. A_VMOVDQU:
  9174. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9175. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9176. begin
  9177. Result := True;
  9178. Exit;
  9179. end;
  9180. else
  9181. ;
  9182. end;
  9183. end;
  9184. end;
  9185. end;
  9186. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9187. begin
  9188. CanBeCMOV:=assigned(p) and
  9189. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9190. { we can't use cmov ref,reg because
  9191. ref could be nil and cmov still throws an exception
  9192. if ref=nil but the mov isn't done (FK)
  9193. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9194. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9195. }
  9196. (taicpu(p).oper[1]^.typ = top_reg) and
  9197. (
  9198. (taicpu(p).oper[0]^.typ = top_reg) or
  9199. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9200. it is not expected that this can cause a seg. violation }
  9201. (
  9202. (taicpu(p).oper[0]^.typ = top_ref) and
  9203. IsRefSafe(taicpu(p).oper[0]^.ref)
  9204. )
  9205. );
  9206. end;
  9207. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9208. var
  9209. hp1,hp2: tai;
  9210. {$ifndef i8086}
  9211. hp3,hp4,hpmov2, hp5: tai;
  9212. l : Longint;
  9213. condition : TAsmCond;
  9214. {$endif i8086}
  9215. carryadd_opcode : TAsmOp;
  9216. symbol: TAsmSymbol;
  9217. increg, tmpreg: TRegister;
  9218. begin
  9219. result:=false;
  9220. if GetNextInstruction(p,hp1) then
  9221. begin
  9222. if (hp1.typ=ait_label) then
  9223. begin
  9224. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9225. Exit;
  9226. end
  9227. else if (hp1.typ<>ait_instruction) then
  9228. Exit;
  9229. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9230. if (
  9231. (
  9232. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9233. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9234. (Taicpu(hp1).oper[0]^.val=1)
  9235. ) or
  9236. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9237. ) and
  9238. GetNextInstruction(hp1,hp2) and
  9239. SkipAligns(hp2, hp2) and
  9240. (hp2.typ = ait_label) and
  9241. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9242. { jb @@1 cmc
  9243. inc/dec operand --> adc/sbb operand,0
  9244. @@1:
  9245. ... and ...
  9246. jnb @@1
  9247. inc/dec operand --> adc/sbb operand,0
  9248. @@1: }
  9249. begin
  9250. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9251. begin
  9252. case taicpu(hp1).opcode of
  9253. A_INC,
  9254. A_ADD:
  9255. carryadd_opcode:=A_ADC;
  9256. A_DEC,
  9257. A_SUB:
  9258. carryadd_opcode:=A_SBB;
  9259. else
  9260. InternalError(2021011001);
  9261. end;
  9262. Taicpu(p).clearop(0);
  9263. Taicpu(p).ops:=0;
  9264. Taicpu(p).is_jmp:=false;
  9265. Taicpu(p).opcode:=A_CMC;
  9266. Taicpu(p).condition:=C_NONE;
  9267. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9268. Taicpu(hp1).ops:=2;
  9269. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9270. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9271. else
  9272. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9273. Taicpu(hp1).loadconst(0,0);
  9274. Taicpu(hp1).opcode:=carryadd_opcode;
  9275. result:=true;
  9276. exit;
  9277. end
  9278. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9279. begin
  9280. case taicpu(hp1).opcode of
  9281. A_INC,
  9282. A_ADD:
  9283. carryadd_opcode:=A_ADC;
  9284. A_DEC,
  9285. A_SUB:
  9286. carryadd_opcode:=A_SBB;
  9287. else
  9288. InternalError(2021011002);
  9289. end;
  9290. Taicpu(hp1).ops:=2;
  9291. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9292. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9293. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9294. else
  9295. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9296. Taicpu(hp1).loadconst(0,0);
  9297. Taicpu(hp1).opcode:=carryadd_opcode;
  9298. RemoveCurrentP(p, hp1);
  9299. result:=true;
  9300. exit;
  9301. end
  9302. {
  9303. jcc @@1 setcc tmpreg
  9304. inc/dec/add/sub operand -> (movzx tmpreg)
  9305. @@1: add/sub tmpreg,operand
  9306. While this increases code size slightly, it makes the code much faster if the
  9307. jump is unpredictable
  9308. }
  9309. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9310. begin
  9311. { search for an available register which is volatile }
  9312. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9313. if increg <> NR_NO then
  9314. begin
  9315. { We don't need to check if tmpreg is in hp1 or not, because
  9316. it will be marked as in use at p (if not, this is
  9317. indictive of a compiler bug). }
  9318. TAsmLabel(symbol).decrefs;
  9319. Taicpu(p).clearop(0);
  9320. Taicpu(p).ops:=1;
  9321. Taicpu(p).is_jmp:=false;
  9322. Taicpu(p).opcode:=A_SETcc;
  9323. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9324. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9325. Taicpu(p).loadreg(0,increg);
  9326. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9327. begin
  9328. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9329. R_SUBW:
  9330. begin
  9331. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9332. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9333. end;
  9334. R_SUBD:
  9335. begin
  9336. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9337. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9338. end;
  9339. {$ifdef x86_64}
  9340. R_SUBQ:
  9341. begin
  9342. { MOVZX doesn't have a 64-bit variant, because
  9343. the 32-bit version implicitly zeroes the
  9344. upper 32-bits of the destination register }
  9345. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9346. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9347. setsubreg(tmpreg, R_SUBQ);
  9348. end;
  9349. {$endif x86_64}
  9350. else
  9351. Internalerror(2020030601);
  9352. end;
  9353. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9354. asml.InsertAfter(hp2,p);
  9355. end
  9356. else
  9357. tmpreg := increg;
  9358. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9359. begin
  9360. Taicpu(hp1).ops:=2;
  9361. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9362. end;
  9363. Taicpu(hp1).loadreg(0,tmpreg);
  9364. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9365. Result := True;
  9366. { p is no longer a Jcc instruction, so exit }
  9367. Exit;
  9368. end;
  9369. end;
  9370. end;
  9371. { Detect the following:
  9372. jmp<cond> @Lbl1
  9373. jmp @Lbl2
  9374. ...
  9375. @Lbl1:
  9376. ret
  9377. Change to:
  9378. jmp<inv_cond> @Lbl2
  9379. ret
  9380. }
  9381. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9382. begin
  9383. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9384. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9385. MatchInstruction(hp2,A_RET,[S_NO]) then
  9386. begin
  9387. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9388. { Change label address to that of the unconditional jump }
  9389. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9390. TAsmLabel(symbol).DecRefs;
  9391. taicpu(hp1).opcode := A_RET;
  9392. taicpu(hp1).is_jmp := false;
  9393. taicpu(hp1).ops := taicpu(hp2).ops;
  9394. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9395. case taicpu(hp2).ops of
  9396. 0:
  9397. taicpu(hp1).clearop(0);
  9398. 1:
  9399. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9400. else
  9401. internalerror(2016041302);
  9402. end;
  9403. end;
  9404. {$ifndef i8086}
  9405. end
  9406. {
  9407. convert
  9408. j<c> .L1
  9409. mov 1,reg
  9410. jmp .L2
  9411. .L1
  9412. mov 0,reg
  9413. .L2
  9414. into
  9415. mov 0,reg
  9416. set<not(c)> reg
  9417. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9418. would destroy the flag contents
  9419. }
  9420. else if MatchInstruction(hp1,A_MOV,[]) and
  9421. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9422. {$ifdef i386}
  9423. (
  9424. { Under i386, ESI, EDI, EBP and ESP
  9425. don't have an 8-bit representation }
  9426. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9427. ) and
  9428. {$endif i386}
  9429. (taicpu(hp1).oper[0]^.val=1) and
  9430. GetNextInstruction(hp1,hp2) and
  9431. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9432. GetNextInstruction(hp2,hp3) and
  9433. { skip align }
  9434. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9435. (hp3.typ=ait_label) and
  9436. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9437. (tai_label(hp3).labsym.getrefs=1) and
  9438. GetNextInstruction(hp3,hp4) and
  9439. MatchInstruction(hp4,A_MOV,[]) and
  9440. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9441. (taicpu(hp4).oper[0]^.val=0) and
  9442. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9443. GetNextInstruction(hp4,hp5) and
  9444. (hp5.typ=ait_label) and
  9445. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9446. (tai_label(hp5).labsym.getrefs=1) then
  9447. begin
  9448. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9449. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9450. { remove last label }
  9451. RemoveInstruction(hp5);
  9452. { remove second label }
  9453. RemoveInstruction(hp3);
  9454. { if align is present remove it }
  9455. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9456. RemoveInstruction(hp3);
  9457. { remove jmp }
  9458. RemoveInstruction(hp2);
  9459. if taicpu(hp1).opsize=S_B then
  9460. RemoveInstruction(hp1)
  9461. else
  9462. taicpu(hp1).loadconst(0,0);
  9463. taicpu(hp4).opcode:=A_SETcc;
  9464. taicpu(hp4).opsize:=S_B;
  9465. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9466. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9467. taicpu(hp4).opercnt:=1;
  9468. taicpu(hp4).ops:=1;
  9469. taicpu(hp4).freeop(1);
  9470. RemoveCurrentP(p);
  9471. Result:=true;
  9472. exit;
  9473. end
  9474. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9475. begin
  9476. { check for
  9477. jCC xxx
  9478. <several movs>
  9479. xxx:
  9480. Also spot:
  9481. Jcc xxx
  9482. <several movs>
  9483. jmp xxx
  9484. Change to:
  9485. <several cmovs with inverted condition>
  9486. jmp xxx
  9487. }
  9488. l:=0;
  9489. while assigned(hp1) and
  9490. CanBeCMOV(hp1) and
  9491. { stop on labels }
  9492. not(hp1.typ=ait_label) do
  9493. begin
  9494. inc(l);
  9495. hp5 := hp1;
  9496. GetNextInstruction(hp1,hp1);
  9497. end;
  9498. if assigned(hp1) then
  9499. begin
  9500. TransferUsedRegs(TmpUsedRegs);
  9501. if (
  9502. MatchInstruction(hp1, A_JMP, []) and
  9503. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9504. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9505. ) or
  9506. FindLabel(tasmlabel(symbol),hp1) then
  9507. begin
  9508. if (l<=4) and (l>0) then
  9509. begin
  9510. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9511. condition:=inverse_cond(taicpu(p).condition);
  9512. UpdateUsedRegs(tai(p.next));
  9513. GetNextInstruction(p,hp1);
  9514. repeat
  9515. if not Assigned(hp1) then
  9516. InternalError(2018062900);
  9517. taicpu(hp1).opcode:=A_CMOVcc;
  9518. taicpu(hp1).condition:=condition;
  9519. UpdateUsedRegs(tai(hp1.next));
  9520. GetNextInstruction(hp1,hp1);
  9521. until not(CanBeCMOV(hp1));
  9522. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9523. hp2 := hp1;
  9524. repeat
  9525. if not Assigned(hp2) then
  9526. InternalError(2018062910);
  9527. case hp2.typ of
  9528. ait_label:
  9529. { What we expected - break out of the loop (it won't be a dead label at the top of
  9530. a cluster because that was optimised at an earlier stage) }
  9531. Break;
  9532. ait_align:
  9533. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9534. begin
  9535. hp2 := tai(hp2.Next);
  9536. Continue;
  9537. end;
  9538. ait_instruction:
  9539. begin
  9540. if taicpu(hp2).opcode<>A_JMP then
  9541. InternalError(2018062912);
  9542. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9543. Break;
  9544. end
  9545. else
  9546. begin
  9547. { Might be a comment or temporary allocation entry }
  9548. if not (hp2.typ in SkipInstr) then
  9549. InternalError(2018062911);
  9550. hp2 := tai(hp2.Next);
  9551. Continue;
  9552. end;
  9553. end;
  9554. until False;
  9555. { Now we can safely decrement the reference count }
  9556. tasmlabel(symbol).decrefs;
  9557. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9558. { Remove the original jump }
  9559. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9560. if hp2.typ=ait_instruction then
  9561. begin
  9562. p:=hp2;
  9563. Result:=True;
  9564. end
  9565. else
  9566. begin
  9567. UpdateUsedRegs(tai(hp2.next));
  9568. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9569. { Remove the label if this is its final reference }
  9570. if (tasmlabel(symbol).getrefs=0) then
  9571. StripLabelFast(hp1);
  9572. end;
  9573. exit;
  9574. end;
  9575. end
  9576. else
  9577. begin
  9578. { check further for
  9579. jCC xxx
  9580. <several movs 1>
  9581. jmp yyy
  9582. xxx:
  9583. <several movs 2>
  9584. yyy:
  9585. }
  9586. { hp2 points to jmp yyy }
  9587. hp2:=hp1;
  9588. { skip hp1 to xxx (or an align right before it) }
  9589. GetNextInstruction(hp1, hp1);
  9590. if assigned(hp2) and
  9591. assigned(hp1) and
  9592. (l<=3) and
  9593. (hp2.typ=ait_instruction) and
  9594. (taicpu(hp2).is_jmp) and
  9595. (taicpu(hp2).condition=C_None) and
  9596. { real label and jump, no further references to the
  9597. label are allowed }
  9598. (tasmlabel(symbol).getrefs=1) and
  9599. FindLabel(tasmlabel(symbol),hp1) then
  9600. begin
  9601. l:=0;
  9602. { skip hp1 to <several moves 2> }
  9603. if (hp1.typ = ait_align) then
  9604. GetNextInstruction(hp1, hp1);
  9605. GetNextInstruction(hp1, hpmov2);
  9606. hp1 := hpmov2;
  9607. while assigned(hp1) and
  9608. CanBeCMOV(hp1) do
  9609. begin
  9610. inc(l);
  9611. hp5 := hp1;
  9612. GetNextInstruction(hp1, hp1);
  9613. end;
  9614. { hp1 points to yyy (or an align right before it) }
  9615. hp3 := hp1;
  9616. if assigned(hp1) and
  9617. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9618. begin
  9619. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9620. condition:=inverse_cond(taicpu(p).condition);
  9621. UpdateUsedRegs(tai(p.next));
  9622. GetNextInstruction(p,hp1);
  9623. repeat
  9624. taicpu(hp1).opcode:=A_CMOVcc;
  9625. taicpu(hp1).condition:=condition;
  9626. UpdateUsedRegs(tai(hp1.next));
  9627. GetNextInstruction(hp1,hp1);
  9628. until not(assigned(hp1)) or
  9629. not(CanBeCMOV(hp1));
  9630. condition:=inverse_cond(condition);
  9631. if GetLastInstruction(hpmov2,hp1) then
  9632. UpdateUsedRegs(tai(hp1.next));
  9633. hp1 := hpmov2;
  9634. { hp1 is now at <several movs 2> }
  9635. while Assigned(hp1) and CanBeCMOV(hp1) do
  9636. begin
  9637. taicpu(hp1).opcode:=A_CMOVcc;
  9638. taicpu(hp1).condition:=condition;
  9639. UpdateUsedRegs(tai(hp1.next));
  9640. GetNextInstruction(hp1,hp1);
  9641. end;
  9642. hp1 := p;
  9643. { Get first instruction after label }
  9644. UpdateUsedRegs(tai(hp3.next));
  9645. GetNextInstruction(hp3, p);
  9646. if assigned(p) and (hp3.typ = ait_align) then
  9647. GetNextInstruction(p, p);
  9648. { Don't dereference yet, as doing so will cause
  9649. GetNextInstruction to skip the label and
  9650. optional align marker. [Kit] }
  9651. GetNextInstruction(hp2, hp4);
  9652. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9653. { remove jCC }
  9654. RemoveInstruction(hp1);
  9655. { Now we can safely decrement it }
  9656. tasmlabel(symbol).decrefs;
  9657. { Remove label xxx (it will have a ref of zero due to the initial check }
  9658. StripLabelFast(hp4);
  9659. { remove jmp }
  9660. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9661. RemoveInstruction(hp2);
  9662. { As before, now we can safely decrement it }
  9663. tasmlabel(symbol).decrefs;
  9664. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9665. if tasmlabel(symbol).getrefs = 0 then
  9666. StripLabelFast(hp3);
  9667. if Assigned(p) then
  9668. result:=true;
  9669. exit;
  9670. end;
  9671. end;
  9672. end;
  9673. end;
  9674. {$endif i8086}
  9675. end;
  9676. end;
  9677. end;
  9678. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9679. var
  9680. hp1,hp2,hp3: tai;
  9681. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9682. NewSize: TOpSize;
  9683. NewRegSize: TSubRegister;
  9684. Limit: TCgInt;
  9685. SwapOper: POper;
  9686. begin
  9687. result:=false;
  9688. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9689. GetNextInstruction(p,hp1) and
  9690. (hp1.typ = ait_instruction);
  9691. if reg_and_hp1_is_instr and
  9692. (
  9693. (taicpu(hp1).opcode <> A_LEA) or
  9694. { If the LEA instruction can be converted into an arithmetic instruction,
  9695. it may be possible to then fold it. }
  9696. (
  9697. { If the flags register is in use, don't change the instruction
  9698. to an ADD otherwise this will scramble the flags. [Kit] }
  9699. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9700. ConvertLEA(taicpu(hp1))
  9701. )
  9702. ) and
  9703. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9704. GetNextInstruction(hp1,hp2) and
  9705. MatchInstruction(hp2,A_MOV,[]) and
  9706. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9707. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9708. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9709. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9710. {$ifdef i386}
  9711. { not all registers have byte size sub registers on i386 }
  9712. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9713. {$endif i386}
  9714. (((taicpu(hp1).ops=2) and
  9715. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9716. ((taicpu(hp1).ops=1) and
  9717. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9718. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9719. begin
  9720. { change movsX/movzX reg/ref, reg2
  9721. add/sub/or/... reg3/$const, reg2
  9722. mov reg2 reg/ref
  9723. to add/sub/or/... reg3/$const, reg/ref }
  9724. { by example:
  9725. movswl %si,%eax movswl %si,%eax p
  9726. decl %eax addl %edx,%eax hp1
  9727. movw %ax,%si movw %ax,%si hp2
  9728. ->
  9729. movswl %si,%eax movswl %si,%eax p
  9730. decw %eax addw %edx,%eax hp1
  9731. movw %ax,%si movw %ax,%si hp2
  9732. }
  9733. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9734. {
  9735. ->
  9736. movswl %si,%eax movswl %si,%eax p
  9737. decw %si addw %dx,%si hp1
  9738. movw %ax,%si movw %ax,%si hp2
  9739. }
  9740. case taicpu(hp1).ops of
  9741. 1:
  9742. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9743. 2:
  9744. begin
  9745. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9746. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9747. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9748. end;
  9749. else
  9750. internalerror(2008042702);
  9751. end;
  9752. {
  9753. ->
  9754. decw %si addw %dx,%si p
  9755. }
  9756. DebugMsg(SPeepholeOptimization + 'var3',p);
  9757. RemoveCurrentP(p, hp1);
  9758. RemoveInstruction(hp2);
  9759. Result := True;
  9760. Exit;
  9761. end;
  9762. if reg_and_hp1_is_instr and
  9763. (taicpu(hp1).opcode = A_MOV) and
  9764. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9765. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9766. {$ifdef x86_64}
  9767. { check for implicit extension to 64 bit }
  9768. or
  9769. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9770. (taicpu(hp1).opsize=S_Q) and
  9771. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9772. )
  9773. {$endif x86_64}
  9774. )
  9775. then
  9776. begin
  9777. { change
  9778. movx %reg1,%reg2
  9779. mov %reg2,%reg3
  9780. dealloc %reg2
  9781. into
  9782. movx %reg,%reg3
  9783. }
  9784. TransferUsedRegs(TmpUsedRegs);
  9785. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9786. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9787. begin
  9788. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9789. {$ifdef x86_64}
  9790. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9791. (taicpu(hp1).opsize=S_Q) then
  9792. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9793. else
  9794. {$endif x86_64}
  9795. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9796. RemoveInstruction(hp1);
  9797. Result := True;
  9798. Exit;
  9799. end;
  9800. end;
  9801. if reg_and_hp1_is_instr and
  9802. ((taicpu(hp1).opcode=A_MOV) or
  9803. (taicpu(hp1).opcode=A_ADD) or
  9804. (taicpu(hp1).opcode=A_SUB) or
  9805. (taicpu(hp1).opcode=A_CMP) or
  9806. (taicpu(hp1).opcode=A_OR) or
  9807. (taicpu(hp1).opcode=A_XOR) or
  9808. (taicpu(hp1).opcode=A_AND)
  9809. ) and
  9810. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9811. begin
  9812. AndTest := (taicpu(hp1).opcode=A_AND) and
  9813. GetNextInstruction(hp1, hp2) and
  9814. (hp2.typ = ait_instruction) and
  9815. (
  9816. (
  9817. (taicpu(hp2).opcode=A_TEST) and
  9818. (
  9819. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9820. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9821. (
  9822. { If the AND and TEST instructions share a constant, this is also valid }
  9823. (taicpu(hp1).oper[0]^.typ = top_const) and
  9824. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9825. )
  9826. ) and
  9827. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9828. ) or
  9829. (
  9830. (taicpu(hp2).opcode=A_CMP) and
  9831. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9832. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9833. )
  9834. );
  9835. { change
  9836. movx (oper),%reg2
  9837. and $x,%reg2
  9838. test %reg2,%reg2
  9839. dealloc %reg2
  9840. into
  9841. op %reg1,%reg3
  9842. if the second op accesses only the bits stored in reg1
  9843. }
  9844. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9845. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9846. (taicpu(hp1).oper[0]^.typ = top_const) and
  9847. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9848. AndTest then
  9849. begin
  9850. { Check if the AND constant is in range }
  9851. case taicpu(p).opsize of
  9852. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9853. begin
  9854. NewSize := S_B;
  9855. Limit := $FF;
  9856. end;
  9857. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9858. begin
  9859. NewSize := S_W;
  9860. Limit := $FFFF;
  9861. end;
  9862. {$ifdef x86_64}
  9863. S_LQ:
  9864. begin
  9865. NewSize := S_L;
  9866. Limit := $FFFFFFFF;
  9867. end;
  9868. {$endif x86_64}
  9869. else
  9870. InternalError(2021120303);
  9871. end;
  9872. if (
  9873. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9874. { Check for negative operands }
  9875. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9876. ) and
  9877. GetNextInstruction(hp2,hp3) and
  9878. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9879. (taicpu(hp3).condition in [C_E,C_NE]) then
  9880. begin
  9881. TransferUsedRegs(TmpUsedRegs);
  9882. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9883. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9884. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9885. begin
  9886. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9887. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9888. taicpu(hp1).opcode := A_TEST;
  9889. taicpu(hp1).opsize := NewSize;
  9890. RemoveInstruction(hp2);
  9891. RemoveCurrentP(p, hp1);
  9892. Result:=true;
  9893. exit;
  9894. end;
  9895. end;
  9896. end;
  9897. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9898. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9899. (taicpu(hp1).opsize=S_B)) or
  9900. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9901. (taicpu(hp1).opsize=S_W))
  9902. {$ifdef x86_64}
  9903. or ((taicpu(p).opsize=S_LQ) and
  9904. (taicpu(hp1).opsize=S_L))
  9905. {$endif x86_64}
  9906. ) and
  9907. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9908. begin
  9909. { change
  9910. movx %reg1,%reg2
  9911. op %reg2,%reg3
  9912. dealloc %reg2
  9913. into
  9914. op %reg1,%reg3
  9915. if the second op accesses only the bits stored in reg1
  9916. }
  9917. TransferUsedRegs(TmpUsedRegs);
  9918. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9919. if AndTest then
  9920. begin
  9921. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9922. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9923. end
  9924. else
  9925. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9926. if not RegUsed then
  9927. begin
  9928. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9929. if taicpu(p).oper[0]^.typ=top_reg then
  9930. begin
  9931. case taicpu(hp1).opsize of
  9932. S_B:
  9933. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9934. S_W:
  9935. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9936. S_L:
  9937. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9938. else
  9939. Internalerror(2020102301);
  9940. end;
  9941. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9942. end
  9943. else
  9944. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9945. RemoveCurrentP(p);
  9946. if AndTest then
  9947. RemoveInstruction(hp2);
  9948. result:=true;
  9949. exit;
  9950. end;
  9951. end
  9952. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9953. (
  9954. { Bitwise operations only }
  9955. (taicpu(hp1).opcode=A_AND) or
  9956. (taicpu(hp1).opcode=A_TEST) or
  9957. (
  9958. (taicpu(hp1).oper[0]^.typ = top_const) and
  9959. (
  9960. (taicpu(hp1).opcode=A_OR) or
  9961. (taicpu(hp1).opcode=A_XOR)
  9962. )
  9963. )
  9964. ) and
  9965. (
  9966. (taicpu(hp1).oper[0]^.typ = top_const) or
  9967. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9968. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9969. ) then
  9970. begin
  9971. { change
  9972. movx %reg2,%reg2
  9973. op const,%reg2
  9974. into
  9975. op const,%reg2 (smaller version)
  9976. movx %reg2,%reg2
  9977. also change
  9978. movx %reg1,%reg2
  9979. and/test (oper),%reg2
  9980. dealloc %reg2
  9981. into
  9982. and/test (oper),%reg1
  9983. }
  9984. case taicpu(p).opsize of
  9985. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9986. begin
  9987. NewSize := S_B;
  9988. NewRegSize := R_SUBL;
  9989. Limit := $FF;
  9990. end;
  9991. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9992. begin
  9993. NewSize := S_W;
  9994. NewRegSize := R_SUBW;
  9995. Limit := $FFFF;
  9996. end;
  9997. {$ifdef x86_64}
  9998. S_LQ:
  9999. begin
  10000. NewSize := S_L;
  10001. NewRegSize := R_SUBD;
  10002. Limit := $FFFFFFFF;
  10003. end;
  10004. {$endif x86_64}
  10005. else
  10006. Internalerror(2021120302);
  10007. end;
  10008. TransferUsedRegs(TmpUsedRegs);
  10009. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10010. if AndTest then
  10011. begin
  10012. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10013. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10014. end
  10015. else
  10016. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10017. if
  10018. (
  10019. (taicpu(p).opcode = A_MOVZX) and
  10020. (
  10021. (taicpu(hp1).opcode=A_AND) or
  10022. (taicpu(hp1).opcode=A_TEST)
  10023. ) and
  10024. not (
  10025. { If both are references, then the final instruction will have
  10026. both operands as references, which is not allowed }
  10027. (taicpu(p).oper[0]^.typ = top_ref) and
  10028. (taicpu(hp1).oper[0]^.typ = top_ref)
  10029. ) and
  10030. not RegUsed
  10031. ) or
  10032. (
  10033. (
  10034. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10035. not RegUsed
  10036. ) and
  10037. (taicpu(p).oper[0]^.typ = top_reg) and
  10038. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10039. (taicpu(hp1).oper[0]^.typ = top_const) and
  10040. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10041. ) then
  10042. begin
  10043. {$if defined(i386) or defined(i8086)}
  10044. { If the target size is 8-bit, make sure we can actually encode it }
  10045. 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
  10046. Exit;
  10047. {$endif i386 or i8086}
  10048. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10049. taicpu(hp1).opsize := NewSize;
  10050. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10051. if AndTest then
  10052. begin
  10053. RemoveInstruction(hp2);
  10054. if not RegUsed then
  10055. begin
  10056. taicpu(hp1).opcode := A_TEST;
  10057. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10058. begin
  10059. { Make sure the reference is the second operand }
  10060. SwapOper := taicpu(hp1).oper[0];
  10061. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10062. taicpu(hp1).oper[1] := SwapOper;
  10063. end;
  10064. end;
  10065. end;
  10066. case taicpu(hp1).oper[0]^.typ of
  10067. top_reg:
  10068. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10069. top_const:
  10070. { For the AND/TEST case }
  10071. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10072. else
  10073. ;
  10074. end;
  10075. if RegUsed then
  10076. begin
  10077. AsmL.Remove(p);
  10078. AsmL.InsertAfter(p, hp1);
  10079. p := hp1;
  10080. end
  10081. else
  10082. RemoveCurrentP(p, hp1);
  10083. result:=true;
  10084. exit;
  10085. end;
  10086. end;
  10087. end;
  10088. if reg_and_hp1_is_instr and
  10089. (taicpu(p).oper[0]^.typ = top_reg) and
  10090. (
  10091. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10092. ) and
  10093. (taicpu(hp1).oper[0]^.typ = top_const) and
  10094. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10095. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10096. { Minimum shift value allowed is the bit difference between the sizes }
  10097. (taicpu(hp1).oper[0]^.val >=
  10098. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10099. 8 * (
  10100. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10101. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10102. )
  10103. ) then
  10104. begin
  10105. { For:
  10106. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10107. shl/sal ##, %reg1
  10108. Remove the movsx/movzx instruction if the shift overwrites the
  10109. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10110. }
  10111. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10112. RemoveCurrentP(p, hp1);
  10113. Result := True;
  10114. Exit;
  10115. end
  10116. else if reg_and_hp1_is_instr and
  10117. (taicpu(p).oper[0]^.typ = top_reg) and
  10118. (
  10119. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10120. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10121. ) and
  10122. (taicpu(hp1).oper[0]^.typ = top_const) and
  10123. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10124. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10125. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10126. (taicpu(hp1).oper[0]^.val <
  10127. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10128. 8 * (
  10129. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10130. )
  10131. ) then
  10132. begin
  10133. { For:
  10134. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10135. sar ##, %reg1 shr ##, %reg1
  10136. Move the shift to before the movx instruction if the shift value
  10137. is not too large.
  10138. }
  10139. asml.Remove(hp1);
  10140. asml.InsertBefore(hp1, p);
  10141. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10142. case taicpu(p).opsize of
  10143. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10144. taicpu(hp1).opsize := S_B;
  10145. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10146. taicpu(hp1).opsize := S_W;
  10147. {$ifdef x86_64}
  10148. S_LQ:
  10149. taicpu(hp1).opsize := S_L;
  10150. {$endif}
  10151. else
  10152. InternalError(2020112401);
  10153. end;
  10154. if (taicpu(hp1).opcode = A_SHR) then
  10155. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10156. else
  10157. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10158. Result := True;
  10159. end;
  10160. if reg_and_hp1_is_instr and
  10161. (taicpu(p).oper[0]^.typ = top_reg) and
  10162. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10163. (
  10164. (taicpu(hp1).opcode = taicpu(p).opcode)
  10165. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10166. {$ifdef x86_64}
  10167. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10168. {$endif x86_64}
  10169. ) then
  10170. begin
  10171. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10172. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10173. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10174. begin
  10175. {
  10176. For example:
  10177. movzbw %al,%ax
  10178. movzwl %ax,%eax
  10179. Compress into:
  10180. movzbl %al,%eax
  10181. }
  10182. RegUsed := False;
  10183. case taicpu(p).opsize of
  10184. S_BW:
  10185. case taicpu(hp1).opsize of
  10186. S_WL:
  10187. begin
  10188. taicpu(p).opsize := S_BL;
  10189. RegUsed := True;
  10190. end;
  10191. {$ifdef x86_64}
  10192. S_WQ:
  10193. begin
  10194. if taicpu(p).opcode = A_MOVZX then
  10195. begin
  10196. taicpu(p).opsize := S_BL;
  10197. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10198. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10199. end
  10200. else
  10201. taicpu(p).opsize := S_BQ;
  10202. RegUsed := True;
  10203. end;
  10204. {$endif x86_64}
  10205. else
  10206. ;
  10207. end;
  10208. {$ifdef x86_64}
  10209. S_BL:
  10210. case taicpu(hp1).opsize of
  10211. S_LQ:
  10212. begin
  10213. if taicpu(p).opcode = A_MOVZX then
  10214. begin
  10215. taicpu(p).opsize := S_BL;
  10216. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10217. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10218. end
  10219. else
  10220. taicpu(p).opsize := S_BQ;
  10221. RegUsed := True;
  10222. end;
  10223. else
  10224. ;
  10225. end;
  10226. S_WL:
  10227. case taicpu(hp1).opsize of
  10228. S_LQ:
  10229. begin
  10230. if taicpu(p).opcode = A_MOVZX then
  10231. begin
  10232. taicpu(p).opsize := S_WL;
  10233. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10234. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10235. end
  10236. else
  10237. taicpu(p).opsize := S_WQ;
  10238. RegUsed := True;
  10239. end;
  10240. else
  10241. ;
  10242. end;
  10243. {$endif x86_64}
  10244. else
  10245. ;
  10246. end;
  10247. if RegUsed then
  10248. begin
  10249. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10250. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10251. RemoveInstruction(hp1);
  10252. Result := True;
  10253. Exit;
  10254. end;
  10255. end;
  10256. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10257. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10258. GetNextInstruction(hp1, hp2) and
  10259. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10260. (
  10261. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10262. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10263. {$ifdef x86_64}
  10264. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10265. {$endif x86_64}
  10266. ) and
  10267. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10268. (
  10269. (
  10270. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10271. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10272. ) or
  10273. (
  10274. { Only allow the operands in reverse order for TEST instructions }
  10275. (taicpu(hp2).opcode = A_TEST) and
  10276. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10277. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10278. )
  10279. ) then
  10280. begin
  10281. {
  10282. For example:
  10283. movzbl %al,%eax
  10284. movzbl (ref),%edx
  10285. andl %edx,%eax
  10286. (%edx deallocated)
  10287. Change to:
  10288. andb (ref),%al
  10289. movzbl %al,%eax
  10290. Rules are:
  10291. - First two instructions have the same opcode and opsize
  10292. - First instruction's operands are the same super-register
  10293. - Second instruction operates on a different register
  10294. - Third instruction is AND, OR, XOR or TEST
  10295. - Third instruction's operands are the destination registers of the first two instructions
  10296. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10297. - Second instruction's destination register is deallocated afterwards
  10298. }
  10299. TransferUsedRegs(TmpUsedRegs);
  10300. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10301. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10302. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10303. begin
  10304. case taicpu(p).opsize of
  10305. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10306. NewSize := S_B;
  10307. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10308. NewSize := S_W;
  10309. {$ifdef x86_64}
  10310. S_LQ:
  10311. NewSize := S_L;
  10312. {$endif x86_64}
  10313. else
  10314. InternalError(2021120301);
  10315. end;
  10316. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10317. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10318. taicpu(hp2).opsize := NewSize;
  10319. RemoveInstruction(hp1);
  10320. { With TEST, it's best to keep the MOVX instruction at the top }
  10321. if (taicpu(hp2).opcode <> A_TEST) then
  10322. begin
  10323. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10324. asml.Remove(p);
  10325. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10326. asml.InsertAfter(p, hp2);
  10327. p := hp2;
  10328. end
  10329. else
  10330. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10331. Result := True;
  10332. Exit;
  10333. end;
  10334. end;
  10335. end;
  10336. if taicpu(p).opcode=A_MOVZX then
  10337. begin
  10338. { removes superfluous And's after movzx's }
  10339. if reg_and_hp1_is_instr and
  10340. (taicpu(hp1).opcode = A_AND) and
  10341. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10342. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10343. {$ifdef x86_64}
  10344. { check for implicit extension to 64 bit }
  10345. or
  10346. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10347. (taicpu(hp1).opsize=S_Q) and
  10348. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10349. )
  10350. {$endif x86_64}
  10351. )
  10352. then
  10353. begin
  10354. case taicpu(p).opsize Of
  10355. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10356. if (taicpu(hp1).oper[0]^.val = $ff) then
  10357. begin
  10358. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10359. RemoveInstruction(hp1);
  10360. Result:=true;
  10361. exit;
  10362. end;
  10363. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10364. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10365. begin
  10366. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10367. RemoveInstruction(hp1);
  10368. Result:=true;
  10369. exit;
  10370. end;
  10371. {$ifdef x86_64}
  10372. S_LQ:
  10373. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10374. begin
  10375. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10376. RemoveInstruction(hp1);
  10377. Result:=true;
  10378. exit;
  10379. end;
  10380. {$endif x86_64}
  10381. else
  10382. ;
  10383. end;
  10384. { we cannot get rid of the and, but can we get rid of the movz ?}
  10385. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10386. begin
  10387. case taicpu(p).opsize Of
  10388. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10389. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10390. begin
  10391. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10392. RemoveCurrentP(p,hp1);
  10393. Result:=true;
  10394. exit;
  10395. end;
  10396. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10397. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10398. begin
  10399. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10400. RemoveCurrentP(p,hp1);
  10401. Result:=true;
  10402. exit;
  10403. end;
  10404. {$ifdef x86_64}
  10405. S_LQ:
  10406. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10407. begin
  10408. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10409. RemoveCurrentP(p,hp1);
  10410. Result:=true;
  10411. exit;
  10412. end;
  10413. {$endif x86_64}
  10414. else
  10415. ;
  10416. end;
  10417. end;
  10418. end;
  10419. { changes some movzx constructs to faster synonyms (all examples
  10420. are given with eax/ax, but are also valid for other registers)}
  10421. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10422. begin
  10423. case taicpu(p).opsize of
  10424. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10425. (the machine code is equivalent to movzbl %al,%eax), but the
  10426. code generator still generates that assembler instruction and
  10427. it is silently converted. This should probably be checked.
  10428. [Kit] }
  10429. S_BW:
  10430. begin
  10431. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10432. (
  10433. not IsMOVZXAcceptable
  10434. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10435. or (
  10436. (cs_opt_size in current_settings.optimizerswitches) and
  10437. (taicpu(p).oper[1]^.reg = NR_AX)
  10438. )
  10439. ) then
  10440. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10441. begin
  10442. DebugMsg(SPeepholeOptimization + 'var7',p);
  10443. taicpu(p).opcode := A_AND;
  10444. taicpu(p).changeopsize(S_W);
  10445. taicpu(p).loadConst(0,$ff);
  10446. Result := True;
  10447. end
  10448. else if not IsMOVZXAcceptable and
  10449. GetNextInstruction(p, hp1) and
  10450. (tai(hp1).typ = ait_instruction) and
  10451. (taicpu(hp1).opcode = A_AND) and
  10452. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10453. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10454. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10455. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10456. begin
  10457. DebugMsg(SPeepholeOptimization + 'var8',p);
  10458. taicpu(p).opcode := A_MOV;
  10459. taicpu(p).changeopsize(S_W);
  10460. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10461. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10462. Result := True;
  10463. end;
  10464. end;
  10465. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10466. S_BL:
  10467. begin
  10468. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10469. (
  10470. not IsMOVZXAcceptable
  10471. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10472. or (
  10473. (cs_opt_size in current_settings.optimizerswitches) and
  10474. (taicpu(p).oper[1]^.reg = NR_EAX)
  10475. )
  10476. ) then
  10477. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10478. begin
  10479. DebugMsg(SPeepholeOptimization + 'var9',p);
  10480. taicpu(p).opcode := A_AND;
  10481. taicpu(p).changeopsize(S_L);
  10482. taicpu(p).loadConst(0,$ff);
  10483. Result := True;
  10484. end
  10485. else if not IsMOVZXAcceptable and
  10486. GetNextInstruction(p, hp1) and
  10487. (tai(hp1).typ = ait_instruction) and
  10488. (taicpu(hp1).opcode = A_AND) and
  10489. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10490. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10491. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10492. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10493. begin
  10494. DebugMsg(SPeepholeOptimization + 'var10',p);
  10495. taicpu(p).opcode := A_MOV;
  10496. taicpu(p).changeopsize(S_L);
  10497. { do not use R_SUBWHOLE
  10498. as movl %rdx,%eax
  10499. is invalid in assembler PM }
  10500. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10501. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10502. Result := True;
  10503. end;
  10504. end;
  10505. {$endif i8086}
  10506. S_WL:
  10507. if not IsMOVZXAcceptable then
  10508. begin
  10509. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10510. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10511. begin
  10512. DebugMsg(SPeepholeOptimization + 'var11',p);
  10513. taicpu(p).opcode := A_AND;
  10514. taicpu(p).changeopsize(S_L);
  10515. taicpu(p).loadConst(0,$ffff);
  10516. Result := True;
  10517. end
  10518. else if GetNextInstruction(p, hp1) and
  10519. (tai(hp1).typ = ait_instruction) and
  10520. (taicpu(hp1).opcode = A_AND) and
  10521. (taicpu(hp1).oper[0]^.typ = top_const) and
  10522. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10523. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10524. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10525. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10526. begin
  10527. DebugMsg(SPeepholeOptimization + 'var12',p);
  10528. taicpu(p).opcode := A_MOV;
  10529. taicpu(p).changeopsize(S_L);
  10530. { do not use R_SUBWHOLE
  10531. as movl %rdx,%eax
  10532. is invalid in assembler PM }
  10533. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10534. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10535. Result := True;
  10536. end;
  10537. end;
  10538. else
  10539. InternalError(2017050705);
  10540. end;
  10541. end
  10542. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10543. begin
  10544. if GetNextInstruction(p, hp1) and
  10545. (tai(hp1).typ = ait_instruction) and
  10546. (taicpu(hp1).opcode = A_AND) and
  10547. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10548. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10549. begin
  10550. //taicpu(p).opcode := A_MOV;
  10551. case taicpu(p).opsize Of
  10552. S_BL:
  10553. begin
  10554. DebugMsg(SPeepholeOptimization + 'var13',p);
  10555. taicpu(hp1).changeopsize(S_L);
  10556. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10557. end;
  10558. S_WL:
  10559. begin
  10560. DebugMsg(SPeepholeOptimization + 'var14',p);
  10561. taicpu(hp1).changeopsize(S_L);
  10562. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10563. end;
  10564. S_BW:
  10565. begin
  10566. DebugMsg(SPeepholeOptimization + 'var15',p);
  10567. taicpu(hp1).changeopsize(S_W);
  10568. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10569. end;
  10570. else
  10571. Internalerror(2017050704)
  10572. end;
  10573. Result := True;
  10574. end;
  10575. end;
  10576. end;
  10577. end;
  10578. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10579. var
  10580. hp1, hp2 : tai;
  10581. MaskLength : Cardinal;
  10582. MaskedBits : TCgInt;
  10583. ActiveReg : TRegister;
  10584. begin
  10585. Result:=false;
  10586. { There are no optimisations for reference targets }
  10587. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10588. Exit;
  10589. while GetNextInstruction(p, hp1) and
  10590. (hp1.typ = ait_instruction) do
  10591. begin
  10592. if (taicpu(p).oper[0]^.typ = top_const) then
  10593. begin
  10594. case taicpu(hp1).opcode of
  10595. A_AND:
  10596. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10597. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10598. { the second register must contain the first one, so compare their subreg types }
  10599. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10600. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10601. { change
  10602. and const1, reg
  10603. and const2, reg
  10604. to
  10605. and (const1 and const2), reg
  10606. }
  10607. begin
  10608. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10609. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10610. RemoveCurrentP(p, hp1);
  10611. Result:=true;
  10612. exit;
  10613. end;
  10614. A_CMP:
  10615. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10616. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10617. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10618. { Just check that the condition on the next instruction is compatible }
  10619. GetNextInstruction(hp1, hp2) and
  10620. (hp2.typ = ait_instruction) and
  10621. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10622. then
  10623. { change
  10624. and 2^n, reg
  10625. cmp 2^n, reg
  10626. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10627. to
  10628. and 2^n, reg
  10629. test reg, reg
  10630. j(~c) / set(~c) / cmov(~c)
  10631. }
  10632. begin
  10633. { Keep TEST instruction in, rather than remove it, because
  10634. it may trigger other optimisations such as MovAndTest2Test }
  10635. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10636. taicpu(hp1).opcode := A_TEST;
  10637. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10638. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10639. Result := True;
  10640. Exit;
  10641. end;
  10642. A_MOVZX:
  10643. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10644. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10645. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10646. (
  10647. (
  10648. (taicpu(p).opsize=S_W) and
  10649. (taicpu(hp1).opsize=S_BW)
  10650. ) or
  10651. (
  10652. (taicpu(p).opsize=S_L) and
  10653. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10654. )
  10655. {$ifdef x86_64}
  10656. or
  10657. (
  10658. (taicpu(p).opsize=S_Q) and
  10659. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10660. )
  10661. {$endif x86_64}
  10662. ) then
  10663. begin
  10664. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10665. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10666. ) or
  10667. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10668. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10669. then
  10670. begin
  10671. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10672. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10673. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10674. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10675. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10676. }
  10677. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10678. RemoveInstruction(hp1);
  10679. { See if there are other optimisations possible }
  10680. Continue;
  10681. end;
  10682. end;
  10683. A_SHL:
  10684. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10685. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10686. begin
  10687. {$ifopt R+}
  10688. {$define RANGE_WAS_ON}
  10689. {$R-}
  10690. {$endif}
  10691. { get length of potential and mask }
  10692. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10693. { really a mask? }
  10694. {$ifdef RANGE_WAS_ON}
  10695. {$R+}
  10696. {$endif}
  10697. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10698. { unmasked part shifted out? }
  10699. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10700. begin
  10701. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10702. RemoveCurrentP(p, hp1);
  10703. Result:=true;
  10704. exit;
  10705. end;
  10706. end;
  10707. A_SHR:
  10708. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10709. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10710. (taicpu(hp1).oper[0]^.val <= 63) then
  10711. begin
  10712. { Does SHR combined with the AND cover all the bits?
  10713. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10714. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10715. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10716. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10717. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10718. begin
  10719. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10720. RemoveCurrentP(p, hp1);
  10721. Result := True;
  10722. Exit;
  10723. end;
  10724. end;
  10725. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10726. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10727. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10728. begin
  10729. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10730. (
  10731. (
  10732. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10733. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10734. ) or (
  10735. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10736. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10737. {$ifdef x86_64}
  10738. ) or (
  10739. (taicpu(hp1).opsize = S_LQ) and
  10740. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10741. {$endif x86_64}
  10742. )
  10743. ) then
  10744. begin
  10745. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10746. begin
  10747. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10748. RemoveInstruction(hp1);
  10749. { See if there are other optimisations possible }
  10750. Continue;
  10751. end;
  10752. { The super-registers are the same though.
  10753. Note that this change by itself doesn't improve
  10754. code speed, but it opens up other optimisations. }
  10755. {$ifdef x86_64}
  10756. { Convert 64-bit register to 32-bit }
  10757. case taicpu(hp1).opsize of
  10758. S_BQ:
  10759. begin
  10760. taicpu(hp1).opsize := S_BL;
  10761. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10762. end;
  10763. S_WQ:
  10764. begin
  10765. taicpu(hp1).opsize := S_WL;
  10766. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10767. end
  10768. else
  10769. ;
  10770. end;
  10771. {$endif x86_64}
  10772. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10773. taicpu(hp1).opcode := A_MOVZX;
  10774. { See if there are other optimisations possible }
  10775. Continue;
  10776. end;
  10777. end;
  10778. else
  10779. ;
  10780. end;
  10781. end
  10782. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10783. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10784. begin
  10785. {$ifdef x86_64}
  10786. if (taicpu(p).opsize = S_Q) then
  10787. begin
  10788. { Never necessary }
  10789. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10790. RemoveCurrentP(p, hp1);
  10791. Result := True;
  10792. Exit;
  10793. end;
  10794. {$endif x86_64}
  10795. { Forward check to determine necessity of and %reg,%reg }
  10796. TransferUsedRegs(TmpUsedRegs);
  10797. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10798. { Saves on a bunch of dereferences }
  10799. ActiveReg := taicpu(p).oper[1]^.reg;
  10800. case taicpu(hp1).opcode of
  10801. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10802. if (
  10803. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10804. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10805. ) and
  10806. (
  10807. (taicpu(hp1).opcode <> A_MOV) or
  10808. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10809. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10810. ) and
  10811. not (
  10812. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10813. (taicpu(hp1).opcode = A_MOV) and
  10814. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10815. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10816. ) and
  10817. (
  10818. (
  10819. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10820. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10821. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10822. ) or
  10823. (
  10824. {$ifdef x86_64}
  10825. (
  10826. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10827. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10828. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10829. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10830. ) and
  10831. {$endif x86_64}
  10832. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10833. )
  10834. ) then
  10835. begin
  10836. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10837. RemoveCurrentP(p, hp1);
  10838. Result := True;
  10839. Exit;
  10840. end;
  10841. A_ADD,
  10842. A_AND,
  10843. A_BSF,
  10844. A_BSR,
  10845. A_BTC,
  10846. A_BTR,
  10847. A_BTS,
  10848. A_OR,
  10849. A_SUB,
  10850. A_XOR:
  10851. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10852. if (
  10853. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10854. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10855. ) and
  10856. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10857. begin
  10858. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10859. RemoveCurrentP(p, hp1);
  10860. Result := True;
  10861. Exit;
  10862. end;
  10863. A_CMP,
  10864. A_TEST:
  10865. if (
  10866. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10867. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10868. ) and
  10869. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10870. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10871. begin
  10872. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10873. RemoveCurrentP(p, hp1);
  10874. Result := True;
  10875. Exit;
  10876. end;
  10877. A_BSWAP,
  10878. A_NEG,
  10879. A_NOT:
  10880. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10881. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10882. begin
  10883. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10884. RemoveCurrentP(p, hp1);
  10885. Result := True;
  10886. Exit;
  10887. end;
  10888. else
  10889. ;
  10890. end;
  10891. end;
  10892. if (taicpu(hp1).is_jmp) and
  10893. (taicpu(hp1).opcode<>A_JMP) and
  10894. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10895. begin
  10896. { change
  10897. and x, reg
  10898. jxx
  10899. to
  10900. test x, reg
  10901. jxx
  10902. if reg is deallocated before the
  10903. jump, but only if it's a conditional jump (PFV)
  10904. }
  10905. taicpu(p).opcode := A_TEST;
  10906. Exit;
  10907. end;
  10908. Break;
  10909. end;
  10910. { Lone AND tests }
  10911. if (taicpu(p).oper[0]^.typ = top_const) then
  10912. begin
  10913. {
  10914. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10915. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10916. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10917. }
  10918. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10919. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10920. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10921. begin
  10922. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10923. if taicpu(p).opsize = S_L then
  10924. begin
  10925. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10926. Result := True;
  10927. end;
  10928. end;
  10929. end;
  10930. { Backward check to determine necessity of and %reg,%reg }
  10931. if (taicpu(p).oper[0]^.typ = top_reg) and
  10932. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10933. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10934. GetLastInstruction(p, hp2) and
  10935. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10936. { Check size of adjacent instruction to determine if the AND is
  10937. effectively a null operation }
  10938. (
  10939. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10940. { Note: Don't include S_Q }
  10941. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10942. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10943. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10944. ) then
  10945. begin
  10946. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10947. { If GetNextInstruction returned False, hp1 will be nil }
  10948. RemoveCurrentP(p, hp1);
  10949. Result := True;
  10950. Exit;
  10951. end;
  10952. end;
  10953. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10954. var
  10955. hp1: tai; NewRef: TReference;
  10956. { This entire nested function is used in an if-statement below, but we
  10957. want to avoid all the used reg transfers and GetNextInstruction calls
  10958. until we really have to check }
  10959. function MemRegisterNotUsedLater: Boolean; inline;
  10960. var
  10961. hp2: tai;
  10962. begin
  10963. TransferUsedRegs(TmpUsedRegs);
  10964. hp2 := p;
  10965. repeat
  10966. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10967. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10968. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10969. end;
  10970. begin
  10971. Result := False;
  10972. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10973. Exit;
  10974. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10975. begin
  10976. { Change:
  10977. add %reg2,%reg1
  10978. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10979. To:
  10980. mov/s/z #(%reg1,%reg2),%reg1
  10981. }
  10982. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10983. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10984. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10985. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10986. (
  10987. (
  10988. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10989. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10990. { r/esp cannot be an index }
  10991. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10992. ) or (
  10993. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10994. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10995. )
  10996. ) and (
  10997. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10998. (
  10999. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11000. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11001. MemRegisterNotUsedLater
  11002. )
  11003. ) then
  11004. begin
  11005. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11006. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11007. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11008. RemoveCurrentp(p, hp1);
  11009. Result := True;
  11010. Exit;
  11011. end;
  11012. { Change:
  11013. addl/q $x,%reg1
  11014. movl/q %reg1,%reg2
  11015. To:
  11016. leal/q $x(%reg1),%reg2
  11017. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11018. Breaks the dependency chain.
  11019. }
  11020. if MatchOpType(taicpu(p),top_const,top_reg) and
  11021. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11022. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11023. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11024. (
  11025. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11026. not (cs_opt_size in current_settings.optimizerswitches) or
  11027. (
  11028. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11029. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11030. )
  11031. ) then
  11032. begin
  11033. { Change the MOV instruction to a LEA instruction, and update the
  11034. first operand }
  11035. reference_reset(NewRef, 1, []);
  11036. NewRef.base := taicpu(p).oper[1]^.reg;
  11037. NewRef.scalefactor := 1;
  11038. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11039. taicpu(hp1).opcode := A_LEA;
  11040. taicpu(hp1).loadref(0, NewRef);
  11041. TransferUsedRegs(TmpUsedRegs);
  11042. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11043. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11044. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11045. begin
  11046. { Move what is now the LEA instruction to before the SUB instruction }
  11047. Asml.Remove(hp1);
  11048. Asml.InsertBefore(hp1, p);
  11049. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11050. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11051. p := hp1;
  11052. end
  11053. else
  11054. begin
  11055. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11056. RemoveCurrentP(p, hp1);
  11057. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11058. end;
  11059. Result := True;
  11060. end;
  11061. end;
  11062. end;
  11063. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11064. var
  11065. SubReg: TSubRegister;
  11066. begin
  11067. Result:=false;
  11068. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11069. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11070. with taicpu(p).oper[0]^.ref^ do
  11071. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11072. begin
  11073. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11074. begin
  11075. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11076. taicpu(p).opcode := A_ADD;
  11077. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11078. Result := True;
  11079. end
  11080. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11081. begin
  11082. if (base <> NR_NO) then
  11083. begin
  11084. if (scalefactor <= 1) then
  11085. begin
  11086. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11087. taicpu(p).opcode := A_ADD;
  11088. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11089. Result := True;
  11090. end;
  11091. end
  11092. else
  11093. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11094. if (scalefactor in [2, 4, 8]) then
  11095. begin
  11096. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11097. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11098. taicpu(p).opcode := A_SHL;
  11099. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11100. Result := True;
  11101. end;
  11102. end;
  11103. end;
  11104. end;
  11105. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11106. var
  11107. hp1: tai; NewRef: TReference;
  11108. begin
  11109. { Change:
  11110. subl/q $x,%reg1
  11111. movl/q %reg1,%reg2
  11112. To:
  11113. leal/q $-x(%reg1),%reg2
  11114. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11115. Breaks the dependency chain and potentially permits the removal of
  11116. a CMP instruction if one follows.
  11117. }
  11118. Result := False;
  11119. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11120. MatchOpType(taicpu(p),top_const,top_reg) and
  11121. GetNextInstruction(p, hp1) and
  11122. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11123. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11124. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11125. (
  11126. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11127. not (cs_opt_size in current_settings.optimizerswitches) or
  11128. (
  11129. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11130. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11131. )
  11132. ) then
  11133. begin
  11134. { Change the MOV instruction to a LEA instruction, and update the
  11135. first operand }
  11136. reference_reset(NewRef, 1, []);
  11137. NewRef.base := taicpu(p).oper[1]^.reg;
  11138. NewRef.scalefactor := 1;
  11139. NewRef.offset := -taicpu(p).oper[0]^.val;
  11140. taicpu(hp1).opcode := A_LEA;
  11141. taicpu(hp1).loadref(0, NewRef);
  11142. TransferUsedRegs(TmpUsedRegs);
  11143. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11144. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11145. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11146. begin
  11147. { Move what is now the LEA instruction to before the SUB instruction }
  11148. Asml.Remove(hp1);
  11149. Asml.InsertBefore(hp1, p);
  11150. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11151. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11152. p := hp1;
  11153. end
  11154. else
  11155. begin
  11156. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11157. RemoveCurrentP(p, hp1);
  11158. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11159. end;
  11160. Result := True;
  11161. end;
  11162. end;
  11163. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11164. begin
  11165. { we can skip all instructions not messing with the stack pointer }
  11166. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11167. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11168. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11169. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11170. ({(taicpu(hp1).ops=0) or }
  11171. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11172. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11173. ) and }
  11174. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11175. )
  11176. ) do
  11177. GetNextInstruction(hp1,hp1);
  11178. Result:=assigned(hp1);
  11179. end;
  11180. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11181. var
  11182. hp1, hp2, hp3, hp4, hp5: tai;
  11183. begin
  11184. Result:=false;
  11185. hp5:=nil;
  11186. { replace
  11187. leal(q) x(<stackpointer>),<stackpointer>
  11188. call procname
  11189. leal(q) -x(<stackpointer>),<stackpointer>
  11190. ret
  11191. by
  11192. jmp procname
  11193. but do it only on level 4 because it destroys stack back traces
  11194. }
  11195. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11196. MatchOpType(taicpu(p),top_ref,top_reg) and
  11197. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11198. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11199. { the -8 or -24 are not required, but bail out early if possible,
  11200. higher values are unlikely }
  11201. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11202. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11203. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11204. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11205. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11206. GetNextInstruction(p, hp1) and
  11207. { Take a copy of hp1 }
  11208. SetAndTest(hp1, hp4) and
  11209. { trick to skip label }
  11210. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11211. SkipSimpleInstructions(hp1) and
  11212. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11213. GetNextInstruction(hp1, hp2) and
  11214. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11215. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11216. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11217. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11218. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11219. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11220. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11221. { Segment register will be NR_NO }
  11222. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11223. GetNextInstruction(hp2, hp3) and
  11224. { trick to skip label }
  11225. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11226. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11227. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11228. SetAndTest(hp3,hp5) and
  11229. GetNextInstruction(hp3,hp3) and
  11230. MatchInstruction(hp3,A_RET,[S_NO])
  11231. )
  11232. ) and
  11233. (taicpu(hp3).ops=0) then
  11234. begin
  11235. taicpu(hp1).opcode := A_JMP;
  11236. taicpu(hp1).is_jmp := true;
  11237. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11238. RemoveCurrentP(p, hp4);
  11239. RemoveInstruction(hp2);
  11240. RemoveInstruction(hp3);
  11241. if Assigned(hp5) then
  11242. begin
  11243. AsmL.Remove(hp5);
  11244. ASmL.InsertBefore(hp5,hp1)
  11245. end;
  11246. Result:=true;
  11247. end;
  11248. end;
  11249. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11250. {$ifdef x86_64}
  11251. var
  11252. hp1, hp2, hp3, hp4, hp5: tai;
  11253. {$endif x86_64}
  11254. begin
  11255. Result:=false;
  11256. {$ifdef x86_64}
  11257. hp5:=nil;
  11258. { replace
  11259. push %rax
  11260. call procname
  11261. pop %rcx
  11262. ret
  11263. by
  11264. jmp procname
  11265. but do it only on level 4 because it destroys stack back traces
  11266. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11267. for all supported calling conventions
  11268. }
  11269. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11270. MatchOpType(taicpu(p),top_reg) and
  11271. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11272. GetNextInstruction(p, hp1) and
  11273. { Take a copy of hp1 }
  11274. SetAndTest(hp1, hp4) and
  11275. { trick to skip label }
  11276. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11277. SkipSimpleInstructions(hp1) and
  11278. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11279. GetNextInstruction(hp1, hp2) and
  11280. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11281. MatchOpType(taicpu(hp2),top_reg) and
  11282. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11283. GetNextInstruction(hp2, hp3) and
  11284. { trick to skip label }
  11285. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11286. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11287. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11288. SetAndTest(hp3,hp5) and
  11289. GetNextInstruction(hp3,hp3) and
  11290. MatchInstruction(hp3,A_RET,[S_NO])
  11291. )
  11292. ) and
  11293. (taicpu(hp3).ops=0) then
  11294. begin
  11295. taicpu(hp1).opcode := A_JMP;
  11296. taicpu(hp1).is_jmp := true;
  11297. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11298. RemoveCurrentP(p, hp4);
  11299. RemoveInstruction(hp2);
  11300. RemoveInstruction(hp3);
  11301. if Assigned(hp5) then
  11302. begin
  11303. AsmL.Remove(hp5);
  11304. ASmL.InsertBefore(hp5,hp1)
  11305. end;
  11306. Result:=true;
  11307. end;
  11308. {$endif x86_64}
  11309. end;
  11310. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11311. var
  11312. Value, RegName: string;
  11313. begin
  11314. Result:=false;
  11315. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11316. begin
  11317. case taicpu(p).oper[0]^.val of
  11318. 0:
  11319. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11320. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11321. begin
  11322. { change "mov $0,%reg" into "xor %reg,%reg" }
  11323. taicpu(p).opcode := A_XOR;
  11324. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11325. Result := True;
  11326. {$ifdef x86_64}
  11327. end
  11328. else if (taicpu(p).opsize = S_Q) then
  11329. begin
  11330. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11331. { The actual optimization }
  11332. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11333. taicpu(p).changeopsize(S_L);
  11334. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11335. Result := True;
  11336. end;
  11337. $1..$FFFFFFFF:
  11338. begin
  11339. { Code size reduction by J. Gareth "Kit" Moreton }
  11340. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11341. case taicpu(p).opsize of
  11342. S_Q:
  11343. begin
  11344. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11345. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11346. { The actual optimization }
  11347. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11348. taicpu(p).changeopsize(S_L);
  11349. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11350. Result := True;
  11351. end;
  11352. else
  11353. { Do nothing };
  11354. end;
  11355. {$endif x86_64}
  11356. end;
  11357. -1:
  11358. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11359. if (cs_opt_size in current_settings.optimizerswitches) and
  11360. (taicpu(p).opsize <> S_B) and
  11361. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11362. begin
  11363. { change "mov $-1,%reg" into "or $-1,%reg" }
  11364. { NOTES:
  11365. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11366. - This operation creates a false dependency on the register, so only do it when optimising for size
  11367. - 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
  11368. }
  11369. taicpu(p).opcode := A_OR;
  11370. Result := True;
  11371. end;
  11372. else
  11373. { Do nothing };
  11374. end;
  11375. end;
  11376. end;
  11377. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11378. var
  11379. hp1: tai;
  11380. begin
  11381. { Detect:
  11382. andw x, %ax (0 <= x < $8000)
  11383. ...
  11384. movzwl %ax,%eax
  11385. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11386. }
  11387. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11388. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11389. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11390. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11391. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11392. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11393. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11394. begin
  11395. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11396. taicpu(hp1).opcode := A_CWDE;
  11397. taicpu(hp1).clearop(0);
  11398. taicpu(hp1).clearop(1);
  11399. taicpu(hp1).ops := 0;
  11400. { A change was made, but not with p, so move forward 1 }
  11401. p := tai(p.Next);
  11402. Result := True;
  11403. end;
  11404. end;
  11405. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11406. begin
  11407. Result := False;
  11408. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11409. Exit;
  11410. { Convert:
  11411. movswl %ax,%eax -> cwtl
  11412. movslq %eax,%rax -> cdqe
  11413. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11414. refer to the same opcode and depends only on the assembler's
  11415. current operand-size attribute. [Kit]
  11416. }
  11417. with taicpu(p) do
  11418. case opsize of
  11419. S_WL:
  11420. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11421. begin
  11422. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11423. opcode := A_CWDE;
  11424. clearop(0);
  11425. clearop(1);
  11426. ops := 0;
  11427. Result := True;
  11428. end;
  11429. {$ifdef x86_64}
  11430. S_LQ:
  11431. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11432. begin
  11433. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11434. opcode := A_CDQE;
  11435. clearop(0);
  11436. clearop(1);
  11437. ops := 0;
  11438. Result := True;
  11439. end;
  11440. {$endif x86_64}
  11441. else
  11442. ;
  11443. end;
  11444. end;
  11445. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11446. var
  11447. hp1: tai;
  11448. begin
  11449. { Detect:
  11450. shr x, %ax (x > 0)
  11451. ...
  11452. movzwl %ax,%eax
  11453. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11454. }
  11455. Result := False;
  11456. if MatchOpType(taicpu(p), top_const, top_reg) and
  11457. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11458. (taicpu(p).oper[0]^.val > 0) and
  11459. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11460. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11461. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11462. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11463. begin
  11464. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11465. taicpu(hp1).opcode := A_CWDE;
  11466. taicpu(hp1).clearop(0);
  11467. taicpu(hp1).clearop(1);
  11468. taicpu(hp1).ops := 0;
  11469. { A change was made, but not with p, so move forward 1 }
  11470. p := tai(p.Next);
  11471. Result := True;
  11472. end;
  11473. end;
  11474. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11475. var
  11476. hp1, hp2: tai;
  11477. Opposite, SecondOpposite: TAsmOp;
  11478. NewCond: TAsmCond;
  11479. begin
  11480. Result := False;
  11481. { Change:
  11482. add/sub 128,(dest)
  11483. To:
  11484. sub/add -128,(dest)
  11485. This generaally takes fewer bytes to encode because -128 can be stored
  11486. in a signed byte, whereas +128 cannot.
  11487. }
  11488. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11489. begin
  11490. if taicpu(p).opcode = A_ADD then
  11491. Opposite := A_SUB
  11492. else
  11493. Opposite := A_ADD;
  11494. { Be careful if the flags are in use, because the CF flag inverts
  11495. when changing from ADD to SUB and vice versa }
  11496. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11497. GetNextInstruction(p, hp1) then
  11498. begin
  11499. TransferUsedRegs(TmpUsedRegs);
  11500. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11501. hp2 := hp1;
  11502. { Scan ahead to check if everything's safe }
  11503. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11504. begin
  11505. if (hp1.typ <> ait_instruction) then
  11506. { Probably unsafe since the flags are still in use }
  11507. Exit;
  11508. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11509. { Stop searching at an unconditional jump }
  11510. Break;
  11511. if not
  11512. (
  11513. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11514. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11515. ) and
  11516. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11517. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11518. Exit;
  11519. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11520. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11521. { Move to the next instruction }
  11522. GetNextInstruction(hp1, hp1);
  11523. end;
  11524. while Assigned(hp2) and (hp2 <> hp1) do
  11525. begin
  11526. NewCond := C_None;
  11527. case taicpu(hp2).condition of
  11528. C_A, C_NBE:
  11529. NewCond := C_BE;
  11530. C_B, C_C, C_NAE:
  11531. NewCond := C_AE;
  11532. C_AE, C_NB, C_NC:
  11533. NewCond := C_B;
  11534. C_BE, C_NA:
  11535. NewCond := C_A;
  11536. else
  11537. { No change needed };
  11538. end;
  11539. if NewCond <> C_None then
  11540. begin
  11541. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11542. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11543. taicpu(hp2).condition := NewCond;
  11544. end
  11545. else
  11546. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11547. begin
  11548. { Because of the flipping of the carry bit, to ensure
  11549. the operation remains equivalent, ADC becomes SBB
  11550. and vice versa, and the constant is not-inverted.
  11551. If multiple ADCs or SBBs appear in a row, each one
  11552. changed causes the carry bit to invert, so they all
  11553. need to be flipped }
  11554. if taicpu(hp2).opcode = A_ADC then
  11555. SecondOpposite := A_SBB
  11556. else
  11557. SecondOpposite := A_ADC;
  11558. if taicpu(hp2).oper[0]^.typ <> top_const then
  11559. { Should have broken out of this optimisation already }
  11560. InternalError(2021112901);
  11561. 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]^) + ' -> ' +
  11562. 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);
  11563. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11564. taicpu(hp2).opcode := SecondOpposite;
  11565. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11566. end;
  11567. { Move to the next instruction }
  11568. GetNextInstruction(hp2, hp2);
  11569. end;
  11570. if (hp2 <> hp1) then
  11571. InternalError(2021111501);
  11572. end;
  11573. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11574. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11575. taicpu(p).opcode := Opposite;
  11576. taicpu(p).oper[0]^.val := -128;
  11577. { No further optimisations can be made on this instruction, so move
  11578. onto the next one to save time }
  11579. p := tai(p.Next);
  11580. UpdateUsedRegs(p);
  11581. Result := True;
  11582. Exit;
  11583. end;
  11584. { Detect:
  11585. add/sub %reg2,(dest)
  11586. add/sub x, (dest)
  11587. (dest can be a register or a reference)
  11588. Swap the instructions to minimise a pipeline stall. This reverses the
  11589. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11590. optimisations could be made.
  11591. }
  11592. if (taicpu(p).oper[0]^.typ = top_reg) and
  11593. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11594. (
  11595. (
  11596. (taicpu(p).oper[1]^.typ = top_reg) and
  11597. { We can try searching further ahead if we're writing to a register }
  11598. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11599. ) or
  11600. (
  11601. (taicpu(p).oper[1]^.typ = top_ref) and
  11602. GetNextInstruction(p, hp1)
  11603. )
  11604. ) and
  11605. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11606. (taicpu(hp1).oper[0]^.typ = top_const) and
  11607. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11608. begin
  11609. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11610. TransferUsedRegs(TmpUsedRegs);
  11611. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11612. hp2 := p;
  11613. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11614. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11615. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11616. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11617. begin
  11618. asml.remove(hp1);
  11619. asml.InsertBefore(hp1, p);
  11620. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11621. Result := True;
  11622. end;
  11623. end;
  11624. end;
  11625. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11626. begin
  11627. Result:=false;
  11628. { change "cmp $0, %reg" to "test %reg, %reg" }
  11629. if MatchOpType(taicpu(p),top_const,top_reg) and
  11630. (taicpu(p).oper[0]^.val = 0) then
  11631. begin
  11632. taicpu(p).opcode := A_TEST;
  11633. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11634. Result:=true;
  11635. end;
  11636. end;
  11637. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11638. var
  11639. IsTestConstX : Boolean;
  11640. hp1,hp2 : tai;
  11641. begin
  11642. Result:=false;
  11643. { removes the line marked with (x) from the sequence
  11644. and/or/xor/add/sub/... $x, %y
  11645. test/or %y, %y | test $-1, %y (x)
  11646. j(n)z _Label
  11647. as the first instruction already adjusts the ZF
  11648. %y operand may also be a reference }
  11649. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11650. MatchOperand(taicpu(p).oper[0]^,-1);
  11651. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11652. GetLastInstruction(p, hp1) and
  11653. (tai(hp1).typ = ait_instruction) and
  11654. GetNextInstruction(p,hp2) and
  11655. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11656. case taicpu(hp1).opcode Of
  11657. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11658. { These two instructions set the zero flag if the result is zero }
  11659. A_POPCNT, A_LZCNT:
  11660. begin
  11661. if (
  11662. { With POPCNT, an input of zero will set the zero flag
  11663. because the population count of zero is zero }
  11664. (taicpu(hp1).opcode = A_POPCNT) and
  11665. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11666. (
  11667. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11668. { Faster than going through the second half of the 'or'
  11669. condition below }
  11670. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11671. )
  11672. ) or (
  11673. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11674. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11675. { and in case of carry for A(E)/B(E)/C/NC }
  11676. (
  11677. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11678. (
  11679. (taicpu(hp1).opcode <> A_ADD) and
  11680. (taicpu(hp1).opcode <> A_SUB) and
  11681. (taicpu(hp1).opcode <> A_LZCNT)
  11682. )
  11683. )
  11684. ) then
  11685. begin
  11686. RemoveCurrentP(p, hp2);
  11687. Result:=true;
  11688. Exit;
  11689. end;
  11690. end;
  11691. A_SHL, A_SAL, A_SHR, A_SAR:
  11692. begin
  11693. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11694. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11695. { therefore, it's only safe to do this optimization for }
  11696. { shifts by a (nonzero) constant }
  11697. (taicpu(hp1).oper[0]^.typ = top_const) and
  11698. (taicpu(hp1).oper[0]^.val <> 0) and
  11699. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11700. { and in case of carry for A(E)/B(E)/C/NC }
  11701. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11702. begin
  11703. RemoveCurrentP(p, hp2);
  11704. Result:=true;
  11705. Exit;
  11706. end;
  11707. end;
  11708. A_DEC, A_INC, A_NEG:
  11709. begin
  11710. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11711. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11712. { and in case of carry for A(E)/B(E)/C/NC }
  11713. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11714. begin
  11715. RemoveCurrentP(p, hp2);
  11716. Result:=true;
  11717. Exit;
  11718. end;
  11719. end
  11720. else
  11721. ;
  11722. end; { case }
  11723. { change "test $-1,%reg" into "test %reg,%reg" }
  11724. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11725. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11726. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11727. if MatchInstruction(p, A_OR, []) and
  11728. { Can only match if they're both registers }
  11729. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11730. begin
  11731. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11732. taicpu(p).opcode := A_TEST;
  11733. { No need to set Result to True, as we've done all the optimisations we can }
  11734. end;
  11735. end;
  11736. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11737. var
  11738. hp1,hp3 : tai;
  11739. {$ifndef x86_64}
  11740. hp2 : taicpu;
  11741. {$endif x86_64}
  11742. begin
  11743. Result:=false;
  11744. hp3:=nil;
  11745. {$ifndef x86_64}
  11746. { don't do this on modern CPUs, this really hurts them due to
  11747. broken call/ret pairing }
  11748. if (current_settings.optimizecputype < cpu_Pentium2) and
  11749. not(cs_create_pic in current_settings.moduleswitches) and
  11750. GetNextInstruction(p, hp1) and
  11751. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11752. MatchOpType(taicpu(hp1),top_ref) and
  11753. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11754. begin
  11755. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11756. InsertLLItem(p.previous, p, hp2);
  11757. taicpu(p).opcode := A_JMP;
  11758. taicpu(p).is_jmp := true;
  11759. RemoveInstruction(hp1);
  11760. Result:=true;
  11761. end
  11762. else
  11763. {$endif x86_64}
  11764. { replace
  11765. call procname
  11766. ret
  11767. by
  11768. jmp procname
  11769. but do it only on level 4 because it destroys stack back traces
  11770. else if the subroutine is marked as no return, remove the ret
  11771. }
  11772. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11773. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11774. GetNextInstruction(p, hp1) and
  11775. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11776. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11777. SetAndTest(hp1,hp3) and
  11778. GetNextInstruction(hp1,hp1) and
  11779. MatchInstruction(hp1,A_RET,[S_NO])
  11780. )
  11781. ) and
  11782. (taicpu(hp1).ops=0) then
  11783. begin
  11784. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11785. { we might destroy stack alignment here if we do not do a call }
  11786. (target_info.stackalign<=sizeof(SizeUInt)) then
  11787. begin
  11788. taicpu(p).opcode := A_JMP;
  11789. taicpu(p).is_jmp := true;
  11790. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11791. end
  11792. else
  11793. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11794. RemoveInstruction(hp1);
  11795. if Assigned(hp3) then
  11796. begin
  11797. AsmL.Remove(hp3);
  11798. AsmL.InsertBefore(hp3,p)
  11799. end;
  11800. Result:=true;
  11801. end;
  11802. end;
  11803. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11804. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11805. begin
  11806. case OpSize of
  11807. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11808. Result := (Val <= $FF) and (Val >= -128);
  11809. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11810. Result := (Val <= $FFFF) and (Val >= -32768);
  11811. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11812. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11813. else
  11814. Result := True;
  11815. end;
  11816. end;
  11817. var
  11818. hp1, hp2 : tai;
  11819. SizeChange: Boolean;
  11820. PreMessage: string;
  11821. begin
  11822. Result := False;
  11823. if (taicpu(p).oper[0]^.typ = top_reg) and
  11824. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11825. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11826. begin
  11827. { Change (using movzbl %al,%eax as an example):
  11828. movzbl %al, %eax movzbl %al, %eax
  11829. cmpl x, %eax testl %eax,%eax
  11830. To:
  11831. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11832. movzbl %al, %eax movzbl %al, %eax
  11833. Smaller instruction and minimises pipeline stall as the CPU
  11834. doesn't have to wait for the register to get zero-extended. [Kit]
  11835. Also allow if the smaller of the two registers is being checked,
  11836. as this still removes the false dependency.
  11837. }
  11838. if
  11839. (
  11840. (
  11841. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11842. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11843. ) or (
  11844. { If MatchOperand returns True, they must both be registers }
  11845. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11846. )
  11847. ) and
  11848. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11849. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11850. begin
  11851. 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);
  11852. asml.Remove(hp1);
  11853. asml.InsertBefore(hp1, p);
  11854. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11855. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11856. begin
  11857. taicpu(hp1).opcode := A_TEST;
  11858. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11859. end;
  11860. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11861. case taicpu(p).opsize of
  11862. S_BW, S_BL:
  11863. begin
  11864. SizeChange := taicpu(hp1).opsize <> S_B;
  11865. taicpu(hp1).changeopsize(S_B);
  11866. end;
  11867. S_WL:
  11868. begin
  11869. SizeChange := taicpu(hp1).opsize <> S_W;
  11870. taicpu(hp1).changeopsize(S_W);
  11871. end
  11872. else
  11873. InternalError(2020112701);
  11874. end;
  11875. UpdateUsedRegs(tai(p.Next));
  11876. { Check if the register is used aferwards - if not, we can
  11877. remove the movzx instruction completely }
  11878. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11879. begin
  11880. { Hp1 is a better position than p for debugging purposes }
  11881. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11882. RemoveCurrentp(p, hp1);
  11883. Result := True;
  11884. end;
  11885. if SizeChange then
  11886. DebugMsg(SPeepholeOptimization + PreMessage +
  11887. 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)
  11888. else
  11889. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11890. Exit;
  11891. end;
  11892. { Change (using movzwl %ax,%eax as an example):
  11893. movzwl %ax, %eax
  11894. movb %al, (dest) (Register is smaller than read register in movz)
  11895. To:
  11896. movb %al, (dest) (Move one back to avoid a false dependency)
  11897. movzwl %ax, %eax
  11898. }
  11899. if (taicpu(hp1).opcode = A_MOV) and
  11900. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11901. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11902. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11903. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11904. begin
  11905. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11906. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11907. asml.Remove(hp1);
  11908. asml.InsertBefore(hp1, p);
  11909. if taicpu(hp1).oper[1]^.typ = top_reg then
  11910. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11911. { Check if the register is used aferwards - if not, we can
  11912. remove the movzx instruction completely }
  11913. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11914. begin
  11915. { Hp1 is a better position than p for debugging purposes }
  11916. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11917. RemoveCurrentp(p, hp1);
  11918. Result := True;
  11919. end;
  11920. Exit;
  11921. end;
  11922. end;
  11923. end;
  11924. {$ifdef x86_64}
  11925. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11926. var
  11927. PreMessage, RegName: string;
  11928. begin
  11929. { Code size reduction by J. Gareth "Kit" Moreton }
  11930. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11931. as this removes the REX prefix }
  11932. Result := False;
  11933. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11934. Exit;
  11935. if taicpu(p).oper[0]^.typ <> top_reg then
  11936. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11937. InternalError(2018011500);
  11938. case taicpu(p).opsize of
  11939. S_Q:
  11940. begin
  11941. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11942. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11943. { The actual optimization }
  11944. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11945. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11946. taicpu(p).changeopsize(S_L);
  11947. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11948. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11949. end;
  11950. else
  11951. ;
  11952. end;
  11953. end;
  11954. {$endif}
  11955. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11956. var
  11957. XReg: TRegister;
  11958. begin
  11959. Result := False;
  11960. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11961. Smaller encoding and slightly faster on some platforms (also works for
  11962. ZMM-sized registers) }
  11963. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11964. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11965. begin
  11966. XReg := taicpu(p).oper[0]^.reg;
  11967. if (taicpu(p).oper[1]^.reg = XReg) then
  11968. begin
  11969. taicpu(p).changeopsize(S_XMM);
  11970. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11971. if (cs_opt_size in current_settings.optimizerswitches) then
  11972. begin
  11973. { Change input registers to %xmm0 to reduce size. Note that
  11974. there's a risk of a false dependency doing this, so only
  11975. optimise for size here }
  11976. XReg := NR_XMM0;
  11977. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11978. end
  11979. else
  11980. begin
  11981. setsubreg(XReg, R_SUBMMX);
  11982. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11983. end;
  11984. taicpu(p).oper[0]^.reg := XReg;
  11985. taicpu(p).oper[1]^.reg := XReg;
  11986. Result := True;
  11987. end;
  11988. end;
  11989. end;
  11990. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11991. var
  11992. OperIdx: Integer;
  11993. begin
  11994. for OperIdx := 0 to p.ops - 1 do
  11995. if p.oper[OperIdx]^.typ = top_ref then
  11996. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11997. end;
  11998. end.