aoptx86.pas 575 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1, hp2 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1418. asml.InsertAfter(hp1, p);
  1419. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1420. RemoveCurrentP(p, hp1);
  1421. Result := True;
  1422. end
  1423. else if ((taicpu(p).ops <= 2) or
  1424. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1425. not(cs_opt_size in current_settings.optimizerswitches) and
  1426. (not(GetNextInstruction(p, hp1)) or
  1427. not((tai(hp1).typ = ait_instruction) and
  1428. ((taicpu(hp1).opcode=A_Jcc) and
  1429. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1430. begin
  1431. {
  1432. imul X, reg1, reg2 to
  1433. lea (reg1,reg1,Y), reg2
  1434. shl ZZ,reg2
  1435. imul XX, reg1 to
  1436. lea (reg1,reg1,YY), reg1
  1437. shl ZZ,reg2
  1438. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1439. it does not exist as a separate optimization target in FPC though.
  1440. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1441. at most two zeros
  1442. }
  1443. reference_reset(tmpref,1,[]);
  1444. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1445. begin
  1446. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1447. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1448. TmpRef.base := taicpu(p).oper[1]^.reg;
  1449. TmpRef.index := taicpu(p).oper[1]^.reg;
  1450. if not(BaseValue in [3,5,9]) then
  1451. Internalerror(2018110101);
  1452. TmpRef.ScaleFactor := BaseValue-1;
  1453. if (taicpu(p).ops = 2) then
  1454. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1455. else
  1456. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1457. AsmL.InsertAfter(hp1,p);
  1458. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1459. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1460. RemoveCurrentP(p, hp1);
  1461. if ShiftValue>0 then
  1462. begin
  1463. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1464. AsmL.InsertAfter(hp2,hp1);
  1465. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1466. end;
  1467. Result := True;
  1468. end;
  1469. end;
  1470. end;
  1471. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1472. begin
  1473. Result := False;
  1474. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1475. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1476. begin
  1477. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1478. taicpu(p).opcode := A_MOV;
  1479. Result := True;
  1480. end;
  1481. end;
  1482. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1483. var
  1484. p: taicpu absolute hp; { Implicit typecast }
  1485. i: Integer;
  1486. begin
  1487. Result := False;
  1488. if not assigned(hp) or
  1489. (hp.typ <> ait_instruction) then
  1490. Exit;
  1491. Prefetch(insprop[p.opcode]);
  1492. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1493. with insprop[p.opcode] do
  1494. begin
  1495. case getsubreg(reg) of
  1496. R_SUBW,R_SUBD,R_SUBQ:
  1497. Result:=
  1498. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1499. uncommon flags are checked first }
  1500. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1501. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1502. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1503. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1504. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1505. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1506. R_SUBFLAGCARRY:
  1507. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGPARITY:
  1509. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGAUXILIARY:
  1511. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGZERO:
  1513. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGSIGN:
  1515. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1516. R_SUBFLAGOVERFLOW:
  1517. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1518. R_SUBFLAGINTERRUPT:
  1519. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1520. R_SUBFLAGDIRECTION:
  1521. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1522. else
  1523. internalerror(2017050501);
  1524. end;
  1525. exit;
  1526. end;
  1527. { Handle special cases first }
  1528. case p.opcode of
  1529. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1530. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1531. begin
  1532. Result :=
  1533. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1534. (p.oper[1]^.typ = top_reg) and
  1535. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1536. (
  1537. (p.oper[0]^.typ = top_const) or
  1538. (
  1539. (p.oper[0]^.typ = top_reg) and
  1540. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1541. ) or (
  1542. (p.oper[0]^.typ = top_ref) and
  1543. not RegInRef(reg,p.oper[0]^.ref^)
  1544. )
  1545. );
  1546. end;
  1547. A_MUL, A_IMUL:
  1548. Result :=
  1549. (
  1550. (p.ops=3) and { IMUL only }
  1551. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1552. (
  1553. (
  1554. (p.oper[1]^.typ=top_reg) and
  1555. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1556. ) or (
  1557. (p.oper[1]^.typ=top_ref) and
  1558. not RegInRef(reg,p.oper[1]^.ref^)
  1559. )
  1560. )
  1561. ) or (
  1562. (
  1563. (p.ops=1) and
  1564. (
  1565. (
  1566. (
  1567. (p.oper[0]^.typ=top_reg) and
  1568. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1569. )
  1570. ) or (
  1571. (p.oper[0]^.typ=top_ref) and
  1572. not RegInRef(reg,p.oper[0]^.ref^)
  1573. )
  1574. ) and (
  1575. (
  1576. (p.opsize=S_B) and
  1577. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1578. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1579. ) or (
  1580. (p.opsize=S_W) and
  1581. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1582. ) or (
  1583. (p.opsize=S_L) and
  1584. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1585. {$ifdef x86_64}
  1586. ) or (
  1587. (p.opsize=S_Q) and
  1588. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1589. {$endif x86_64}
  1590. )
  1591. )
  1592. )
  1593. );
  1594. A_CBW:
  1595. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1596. {$ifndef x86_64}
  1597. A_LDS:
  1598. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1599. A_LES:
  1600. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1601. {$endif not x86_64}
  1602. A_LFS:
  1603. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1604. A_LGS:
  1605. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1606. A_LSS:
  1607. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1608. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1609. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1610. A_LODSB:
  1611. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1612. A_LODSW:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1614. {$ifdef x86_64}
  1615. A_LODSQ:
  1616. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1617. {$endif x86_64}
  1618. A_LODSD:
  1619. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1620. A_FSTSW, A_FNSTSW:
  1621. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1622. else
  1623. begin
  1624. with insprop[p.opcode] do
  1625. begin
  1626. if (
  1627. { xor %reg,%reg etc. is classed as a new value }
  1628. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1629. MatchOpType(p, top_reg, top_reg) and
  1630. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1631. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1632. ) then
  1633. begin
  1634. Result := True;
  1635. Exit;
  1636. end;
  1637. { Make sure the entire register is overwritten }
  1638. if (getregtype(reg) = R_INTREGISTER) then
  1639. begin
  1640. if (p.ops > 0) then
  1641. begin
  1642. if RegInOp(reg, p.oper[0]^) then
  1643. begin
  1644. if (p.oper[0]^.typ = top_ref) then
  1645. begin
  1646. if RegInRef(reg, p.oper[0]^.ref^) then
  1647. begin
  1648. Result := False;
  1649. Exit;
  1650. end;
  1651. end
  1652. else if (p.oper[0]^.typ = top_reg) then
  1653. begin
  1654. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1655. begin
  1656. Result := False;
  1657. Exit;
  1658. end
  1659. else if ([Ch_WOp1]*Ch<>[]) then
  1660. begin
  1661. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1662. Result := True
  1663. else
  1664. begin
  1665. Result := False;
  1666. Exit;
  1667. end;
  1668. end;
  1669. end;
  1670. end;
  1671. if (p.ops > 1) then
  1672. begin
  1673. if RegInOp(reg, p.oper[1]^) then
  1674. begin
  1675. if (p.oper[1]^.typ = top_ref) then
  1676. begin
  1677. if RegInRef(reg, p.oper[1]^.ref^) then
  1678. begin
  1679. Result := False;
  1680. Exit;
  1681. end;
  1682. end
  1683. else if (p.oper[1]^.typ = top_reg) then
  1684. begin
  1685. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1686. begin
  1687. Result := False;
  1688. Exit;
  1689. end
  1690. else if ([Ch_WOp2]*Ch<>[]) then
  1691. begin
  1692. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1693. Result := True
  1694. else
  1695. begin
  1696. Result := False;
  1697. Exit;
  1698. end;
  1699. end;
  1700. end;
  1701. end;
  1702. if (p.ops > 2) then
  1703. begin
  1704. if RegInOp(reg, p.oper[2]^) then
  1705. begin
  1706. if (p.oper[2]^.typ = top_ref) then
  1707. begin
  1708. if RegInRef(reg, p.oper[2]^.ref^) then
  1709. begin
  1710. Result := False;
  1711. Exit;
  1712. end;
  1713. end
  1714. else if (p.oper[2]^.typ = top_reg) then
  1715. begin
  1716. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1717. begin
  1718. Result := False;
  1719. Exit;
  1720. end
  1721. else if ([Ch_WOp3]*Ch<>[]) then
  1722. begin
  1723. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1724. Result := True
  1725. else
  1726. begin
  1727. Result := False;
  1728. Exit;
  1729. end;
  1730. end;
  1731. end;
  1732. end;
  1733. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1734. begin
  1735. if (p.oper[3]^.typ = top_ref) then
  1736. begin
  1737. if RegInRef(reg, p.oper[3]^.ref^) then
  1738. begin
  1739. Result := False;
  1740. Exit;
  1741. end;
  1742. end
  1743. else if (p.oper[3]^.typ = top_reg) then
  1744. begin
  1745. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1746. begin
  1747. Result := False;
  1748. Exit;
  1749. end
  1750. else if ([Ch_WOp4]*Ch<>[]) then
  1751. begin
  1752. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1753. Result := True
  1754. else
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end;
  1759. end;
  1760. end;
  1761. end;
  1762. end;
  1763. end;
  1764. end;
  1765. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1766. case getsupreg(reg) of
  1767. RS_EAX:
  1768. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_ECX:
  1774. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EDX:
  1780. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_EBX:
  1786. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_ESP:
  1792. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_EBP:
  1798. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_ESI:
  1804. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. RS_EDI:
  1810. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1811. begin
  1812. Result := True;
  1813. Exit;
  1814. end;
  1815. else
  1816. ;
  1817. end;
  1818. end;
  1819. end;
  1820. end;
  1821. end;
  1822. end;
  1823. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1824. var
  1825. hp2,hp3 : tai;
  1826. begin
  1827. { some x86-64 issue a NOP before the real exit code }
  1828. if MatchInstruction(p,A_NOP,[]) then
  1829. GetNextInstruction(p,p);
  1830. result:=assigned(p) and (p.typ=ait_instruction) and
  1831. ((taicpu(p).opcode = A_RET) or
  1832. ((taicpu(p).opcode=A_LEAVE) and
  1833. GetNextInstruction(p,hp2) and
  1834. MatchInstruction(hp2,A_RET,[S_NO])
  1835. ) or
  1836. (((taicpu(p).opcode=A_LEA) and
  1837. MatchOpType(taicpu(p),top_ref,top_reg) and
  1838. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1839. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1840. ) and
  1841. GetNextInstruction(p,hp2) and
  1842. MatchInstruction(hp2,A_RET,[S_NO])
  1843. ) or
  1844. ((((taicpu(p).opcode=A_MOV) and
  1845. MatchOpType(taicpu(p),top_reg,top_reg) and
  1846. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1847. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1848. ((taicpu(p).opcode=A_LEA) and
  1849. MatchOpType(taicpu(p),top_ref,top_reg) and
  1850. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1851. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1852. )
  1853. ) and
  1854. GetNextInstruction(p,hp2) and
  1855. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1856. MatchOpType(taicpu(hp2),top_reg) and
  1857. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1858. GetNextInstruction(hp2,hp3) and
  1859. MatchInstruction(hp3,A_RET,[S_NO])
  1860. )
  1861. );
  1862. end;
  1863. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1864. begin
  1865. isFoldableArithOp := False;
  1866. case hp1.opcode of
  1867. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1868. isFoldableArithOp :=
  1869. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1870. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1872. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1873. (taicpu(hp1).oper[1]^.reg = reg);
  1874. A_INC,A_DEC,A_NEG,A_NOT:
  1875. isFoldableArithOp :=
  1876. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1877. (taicpu(hp1).oper[0]^.reg = reg);
  1878. else
  1879. ;
  1880. end;
  1881. end;
  1882. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1883. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1884. var
  1885. hp2: tai;
  1886. begin
  1887. hp2 := p;
  1888. repeat
  1889. hp2 := tai(hp2.previous);
  1890. if assigned(hp2) and
  1891. (hp2.typ = ait_regalloc) and
  1892. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1893. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1894. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1895. begin
  1896. RemoveInstruction(hp2);
  1897. break;
  1898. end;
  1899. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1900. end;
  1901. begin
  1902. case current_procinfo.procdef.returndef.typ of
  1903. arraydef,recorddef,pointerdef,
  1904. stringdef,enumdef,procdef,objectdef,errordef,
  1905. filedef,setdef,procvardef,
  1906. classrefdef,forwarddef:
  1907. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1908. orddef:
  1909. if current_procinfo.procdef.returndef.size <> 0 then
  1910. begin
  1911. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1912. { for int64/qword }
  1913. if current_procinfo.procdef.returndef.size = 8 then
  1914. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1915. end;
  1916. else
  1917. ;
  1918. end;
  1919. end;
  1920. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1921. var
  1922. hp1,hp2 : tai;
  1923. begin
  1924. result:=false;
  1925. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1926. begin
  1927. { vmova* reg1,reg1
  1928. =>
  1929. <nop> }
  1930. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1931. begin
  1932. RemoveCurrentP(p);
  1933. result:=true;
  1934. exit;
  1935. end
  1936. else if GetNextInstruction(p,hp1) then
  1937. begin
  1938. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1939. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1940. begin
  1941. { vmova* reg1,reg2
  1942. vmova* reg2,reg3
  1943. dealloc reg2
  1944. =>
  1945. vmova* reg1,reg3 }
  1946. TransferUsedRegs(TmpUsedRegs);
  1947. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1948. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1949. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1950. begin
  1951. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1952. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1953. RemoveInstruction(hp1);
  1954. result:=true;
  1955. exit;
  1956. end
  1957. { special case:
  1958. vmova* reg1,<op>
  1959. vmova* <op>,reg1
  1960. =>
  1961. vmova* reg1,<op> }
  1962. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1963. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1964. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1965. ) then
  1966. begin
  1967. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1968. RemoveInstruction(hp1);
  1969. result:=true;
  1970. exit;
  1971. end
  1972. end
  1973. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1974. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1975. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1976. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1977. ) and
  1978. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1979. begin
  1980. { vmova* reg1,reg2
  1981. vmovs* reg2,<op>
  1982. dealloc reg2
  1983. =>
  1984. vmovs* reg1,reg3 }
  1985. TransferUsedRegs(TmpUsedRegs);
  1986. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1987. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1988. begin
  1989. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1990. taicpu(p).opcode:=taicpu(hp1).opcode;
  1991. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1992. RemoveInstruction(hp1);
  1993. result:=true;
  1994. exit;
  1995. end
  1996. end;
  1997. end;
  1998. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1999. begin
  2000. if MatchInstruction(hp1,[A_VFMADDPD,
  2001. A_VFMADD132PD,
  2002. A_VFMADD132PS,
  2003. A_VFMADD132SD,
  2004. A_VFMADD132SS,
  2005. A_VFMADD213PD,
  2006. A_VFMADD213PS,
  2007. A_VFMADD213SD,
  2008. A_VFMADD213SS,
  2009. A_VFMADD231PD,
  2010. A_VFMADD231PS,
  2011. A_VFMADD231SD,
  2012. A_VFMADD231SS,
  2013. A_VFMADDSUB132PD,
  2014. A_VFMADDSUB132PS,
  2015. A_VFMADDSUB213PD,
  2016. A_VFMADDSUB213PS,
  2017. A_VFMADDSUB231PD,
  2018. A_VFMADDSUB231PS,
  2019. A_VFMSUB132PD,
  2020. A_VFMSUB132PS,
  2021. A_VFMSUB132SD,
  2022. A_VFMSUB132SS,
  2023. A_VFMSUB213PD,
  2024. A_VFMSUB213PS,
  2025. A_VFMSUB213SD,
  2026. A_VFMSUB213SS,
  2027. A_VFMSUB231PD,
  2028. A_VFMSUB231PS,
  2029. A_VFMSUB231SD,
  2030. A_VFMSUB231SS,
  2031. A_VFMSUBADD132PD,
  2032. A_VFMSUBADD132PS,
  2033. A_VFMSUBADD213PD,
  2034. A_VFMSUBADD213PS,
  2035. A_VFMSUBADD231PD,
  2036. A_VFMSUBADD231PS,
  2037. A_VFNMADD132PD,
  2038. A_VFNMADD132PS,
  2039. A_VFNMADD132SD,
  2040. A_VFNMADD132SS,
  2041. A_VFNMADD213PD,
  2042. A_VFNMADD213PS,
  2043. A_VFNMADD213SD,
  2044. A_VFNMADD213SS,
  2045. A_VFNMADD231PD,
  2046. A_VFNMADD231PS,
  2047. A_VFNMADD231SD,
  2048. A_VFNMADD231SS,
  2049. A_VFNMSUB132PD,
  2050. A_VFNMSUB132PS,
  2051. A_VFNMSUB132SD,
  2052. A_VFNMSUB132SS,
  2053. A_VFNMSUB213PD,
  2054. A_VFNMSUB213PS,
  2055. A_VFNMSUB213SD,
  2056. A_VFNMSUB213SS,
  2057. A_VFNMSUB231PD,
  2058. A_VFNMSUB231PS,
  2059. A_VFNMSUB231SD,
  2060. A_VFNMSUB231SS],[S_NO]) and
  2061. { we mix single and double opperations here because we assume that the compiler
  2062. generates vmovapd only after double operations and vmovaps only after single operations }
  2063. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2064. GetNextInstruction(hp1,hp2) and
  2065. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2066. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2067. begin
  2068. TransferUsedRegs(TmpUsedRegs);
  2069. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2070. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2071. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2072. begin
  2073. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2074. RemoveCurrentP(p);
  2075. RemoveInstruction(hp2);
  2076. end;
  2077. end
  2078. else if (hp1.typ = ait_instruction) and
  2079. GetNextInstruction(hp1, hp2) and
  2080. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2081. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2082. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2083. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2084. (((taicpu(p).opcode=A_MOVAPS) and
  2085. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2086. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2087. ((taicpu(p).opcode=A_MOVAPD) and
  2088. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2089. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2090. ) then
  2091. { change
  2092. movapX reg,reg2
  2093. addsX/subsX/... reg3, reg2
  2094. movapX reg2,reg
  2095. to
  2096. addsX/subsX/... reg3,reg
  2097. }
  2098. begin
  2099. TransferUsedRegs(TmpUsedRegs);
  2100. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2101. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2102. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2103. begin
  2104. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2105. debug_op2str(taicpu(p).opcode)+' '+
  2106. debug_op2str(taicpu(hp1).opcode)+' '+
  2107. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2108. { we cannot eliminate the first move if
  2109. the operations uses the same register for source and dest }
  2110. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2111. { Remember that hp1 is not necessarily the immediate
  2112. next instruction }
  2113. RemoveCurrentP(p);
  2114. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2115. RemoveInstruction(hp2);
  2116. result:=true;
  2117. end;
  2118. end
  2119. else if (hp1.typ = ait_instruction) and
  2120. (((taicpu(p).opcode=A_VMOVAPD) and
  2121. (taicpu(hp1).opcode=A_VCOMISD)) or
  2122. ((taicpu(p).opcode=A_VMOVAPS) and
  2123. ((taicpu(hp1).opcode=A_VCOMISS))
  2124. )
  2125. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2126. { change
  2127. movapX reg,reg1
  2128. vcomisX reg1,reg1
  2129. to
  2130. vcomisX reg,reg
  2131. }
  2132. begin
  2133. TransferUsedRegs(TmpUsedRegs);
  2134. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2135. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2136. begin
  2137. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2138. debug_op2str(taicpu(p).opcode)+' '+
  2139. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2140. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2141. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2142. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2143. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2144. RemoveCurrentP(p);
  2145. result:=true;
  2146. exit;
  2147. end;
  2148. end
  2149. end;
  2150. end;
  2151. end;
  2152. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2153. var
  2154. hp1 : tai;
  2155. begin
  2156. result:=false;
  2157. { replace
  2158. V<Op>X %mreg1,%mreg2,%mreg3
  2159. VMovX %mreg3,%mreg4
  2160. dealloc %mreg3
  2161. by
  2162. V<Op>X %mreg1,%mreg2,%mreg4
  2163. ?
  2164. }
  2165. if GetNextInstruction(p,hp1) and
  2166. { we mix single and double operations here because we assume that the compiler
  2167. generates vmovapd only after double operations and vmovaps only after single operations }
  2168. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2169. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2170. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2171. begin
  2172. TransferUsedRegs(TmpUsedRegs);
  2173. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2174. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2175. begin
  2176. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2177. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2178. RemoveInstruction(hp1);
  2179. result:=true;
  2180. end;
  2181. end;
  2182. end;
  2183. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2184. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2185. begin
  2186. Result := False;
  2187. { For safety reasons, only check for exact register matches }
  2188. { Check base register }
  2189. if (ref.base = AOldReg) then
  2190. begin
  2191. ref.base := ANewReg;
  2192. Result := True;
  2193. end;
  2194. { Check index register }
  2195. if (ref.index = AOldReg) then
  2196. begin
  2197. ref.index := ANewReg;
  2198. Result := True;
  2199. end;
  2200. end;
  2201. { Replaces all references to AOldReg in an operand to ANewReg }
  2202. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2203. var
  2204. OldSupReg, NewSupReg: TSuperRegister;
  2205. OldSubReg, NewSubReg: TSubRegister;
  2206. OldRegType: TRegisterType;
  2207. ThisOper: POper;
  2208. begin
  2209. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2210. Result := False;
  2211. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2212. InternalError(2020011801);
  2213. OldSupReg := getsupreg(AOldReg);
  2214. OldSubReg := getsubreg(AOldReg);
  2215. OldRegType := getregtype(AOldReg);
  2216. NewSupReg := getsupreg(ANewReg);
  2217. NewSubReg := getsubreg(ANewReg);
  2218. if OldRegType <> getregtype(ANewReg) then
  2219. InternalError(2020011802);
  2220. if OldSubReg <> NewSubReg then
  2221. InternalError(2020011803);
  2222. case ThisOper^.typ of
  2223. top_reg:
  2224. if (
  2225. (ThisOper^.reg = AOldReg) or
  2226. (
  2227. (OldRegType = R_INTREGISTER) and
  2228. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2229. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2230. (
  2231. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2232. {$ifndef x86_64}
  2233. and (
  2234. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2235. don't have an 8-bit representation }
  2236. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2237. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2238. )
  2239. {$endif x86_64}
  2240. )
  2241. )
  2242. ) then
  2243. begin
  2244. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2245. Result := True;
  2246. end;
  2247. top_ref:
  2248. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2249. Result := True;
  2250. else
  2251. ;
  2252. end;
  2253. end;
  2254. { Replaces all references to AOldReg in an instruction to ANewReg }
  2255. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2256. const
  2257. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2258. var
  2259. OperIdx: Integer;
  2260. begin
  2261. Result := False;
  2262. for OperIdx := 0 to p.ops - 1 do
  2263. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2264. begin
  2265. { The shift and rotate instructions can only use CL }
  2266. if not (
  2267. (OperIdx = 0) and
  2268. { This second condition just helps to avoid unnecessarily
  2269. calling MatchInstruction for 10 different opcodes }
  2270. (p.oper[0]^.reg = NR_CL) and
  2271. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2272. ) then
  2273. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2274. end
  2275. else if p.oper[OperIdx]^.typ = top_ref then
  2276. { It's okay to replace registers in references that get written to }
  2277. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2278. end;
  2279. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2280. begin
  2281. with ref^ do
  2282. Result :=
  2283. (index = NR_NO) and
  2284. (
  2285. {$ifdef x86_64}
  2286. (
  2287. (base = NR_RIP) and
  2288. (refaddr in [addr_pic, addr_pic_no_got])
  2289. ) or
  2290. {$endif x86_64}
  2291. (base = NR_STACK_POINTER_REG) or
  2292. (base = current_procinfo.framepointer)
  2293. );
  2294. end;
  2295. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2296. var
  2297. l: asizeint;
  2298. begin
  2299. Result := False;
  2300. { Should have been checked previously }
  2301. if p.opcode <> A_LEA then
  2302. InternalError(2020072501);
  2303. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2304. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2305. not(cs_opt_size in current_settings.optimizerswitches) then
  2306. exit;
  2307. with p.oper[0]^.ref^ do
  2308. begin
  2309. if (base <> p.oper[1]^.reg) or
  2310. (index <> NR_NO) or
  2311. assigned(symbol) then
  2312. exit;
  2313. l:=offset;
  2314. if (l=1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_INC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2320. end
  2321. else if (l=-1) and UseIncDec then
  2322. begin
  2323. p.opcode:=A_DEC;
  2324. p.loadreg(0,p.oper[1]^.reg);
  2325. p.ops:=1;
  2326. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2327. end
  2328. else
  2329. begin
  2330. if (l<0) and (l<>-2147483648) then
  2331. begin
  2332. p.opcode:=A_SUB;
  2333. p.loadConst(0,-l);
  2334. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2335. end
  2336. else
  2337. begin
  2338. p.opcode:=A_ADD;
  2339. p.loadConst(0,l);
  2340. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2341. end;
  2342. end;
  2343. end;
  2344. Result := True;
  2345. end;
  2346. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2347. var
  2348. CurrentReg, ReplaceReg: TRegister;
  2349. begin
  2350. Result := False;
  2351. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2352. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2353. case hp.opcode of
  2354. A_FSTSW, A_FNSTSW,
  2355. A_IN, A_INS, A_OUT, A_OUTS,
  2356. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2357. { These routines have explicit operands, but they are restricted in
  2358. what they can be (e.g. IN and OUT can only read from AL, AX or
  2359. EAX. }
  2360. Exit;
  2361. A_IMUL:
  2362. begin
  2363. { The 1-operand version writes to implicit registers
  2364. The 2-operand version reads from the first operator, and reads
  2365. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2366. the 3-operand version reads from a register that it doesn't write to
  2367. }
  2368. case hp.ops of
  2369. 1:
  2370. if (
  2371. (
  2372. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2373. ) or
  2374. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2375. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2376. begin
  2377. Result := True;
  2378. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2379. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2380. end;
  2381. 2:
  2382. { Only modify the first parameter }
  2383. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2384. begin
  2385. Result := True;
  2386. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2387. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2388. end;
  2389. 3:
  2390. { Only modify the second parameter }
  2391. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2392. begin
  2393. Result := True;
  2394. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2395. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2396. end;
  2397. else
  2398. InternalError(2020012901);
  2399. end;
  2400. end;
  2401. else
  2402. if (hp.ops > 0) and
  2403. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2404. begin
  2405. Result := True;
  2406. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2407. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2408. end;
  2409. end;
  2410. end;
  2411. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2412. var
  2413. hp1, hp2, hp3: tai;
  2414. DoOptimisation, TempBool: Boolean;
  2415. {$ifdef x86_64}
  2416. NewConst: TCGInt;
  2417. {$endif x86_64}
  2418. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2419. begin
  2420. if taicpu(hp1).opcode = signed_movop then
  2421. begin
  2422. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2423. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2424. end
  2425. else
  2426. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2427. end;
  2428. function TryConstMerge(var p1, p2: tai): Boolean;
  2429. var
  2430. ThisRef: TReference;
  2431. begin
  2432. Result := False;
  2433. ThisRef := taicpu(p2).oper[1]^.ref^;
  2434. { Only permit writes to the stack, since we can guarantee alignment with that }
  2435. if (ThisRef.index = NR_NO) and
  2436. (
  2437. (ThisRef.base = NR_STACK_POINTER_REG) or
  2438. (ThisRef.base = current_procinfo.framepointer)
  2439. ) then
  2440. begin
  2441. case taicpu(p).opsize of
  2442. S_B:
  2443. begin
  2444. { Word writes must be on a 2-byte boundary }
  2445. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2446. begin
  2447. { Reduce offset of second reference to see if it is sequential with the first }
  2448. Dec(ThisRef.offset, 1);
  2449. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2450. begin
  2451. { Make sure the constants aren't represented as a
  2452. negative number, as these won't merge properly }
  2453. taicpu(p1).opsize := S_W;
  2454. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2455. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2456. RemoveInstruction(p2);
  2457. Result := True;
  2458. end;
  2459. end;
  2460. end;
  2461. S_W:
  2462. begin
  2463. { Longword writes must be on a 4-byte boundary }
  2464. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2465. begin
  2466. { Reduce offset of second reference to see if it is sequential with the first }
  2467. Dec(ThisRef.offset, 2);
  2468. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2469. begin
  2470. { Make sure the constants aren't represented as a
  2471. negative number, as these won't merge properly }
  2472. taicpu(p1).opsize := S_L;
  2473. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2474. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2475. RemoveInstruction(p2);
  2476. Result := True;
  2477. end;
  2478. end;
  2479. end;
  2480. {$ifdef x86_64}
  2481. S_L:
  2482. begin
  2483. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2484. see if the constants can be encoded this way. }
  2485. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2486. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2487. { Quadword writes must be on an 8-byte boundary }
  2488. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2489. begin
  2490. { Reduce offset of second reference to see if it is sequential with the first }
  2491. Dec(ThisRef.offset, 4);
  2492. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2493. begin
  2494. { Make sure the constants aren't represented as a
  2495. negative number, as these won't merge properly }
  2496. taicpu(p1).opsize := S_Q;
  2497. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2498. taicpu(p1).oper[0]^.val := NewConst;
  2499. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2500. RemoveInstruction(p2);
  2501. Result := True;
  2502. end;
  2503. end;
  2504. end;
  2505. {$endif x86_64}
  2506. else
  2507. ;
  2508. end;
  2509. end;
  2510. end;
  2511. var
  2512. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2513. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2514. NewSize: topsize;
  2515. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2516. SourceRef, TargetRef: TReference;
  2517. MovAligned, MovUnaligned: TAsmOp;
  2518. ThisRef: TReference;
  2519. JumpTracking: TLinkedList;
  2520. begin
  2521. Result:=false;
  2522. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2523. { remove mov reg1,reg1? }
  2524. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2525. then
  2526. begin
  2527. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2528. { take care of the register (de)allocs following p }
  2529. RemoveCurrentP(p, hp1);
  2530. Result:=true;
  2531. exit;
  2532. end;
  2533. { All the next optimisations require a next instruction }
  2534. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2535. Exit;
  2536. { Prevent compiler warnings }
  2537. p_TargetReg := NR_NO;
  2538. if taicpu(p).oper[1]^.typ = top_reg then
  2539. begin
  2540. { Saves on a large number of dereferences }
  2541. p_TargetReg := taicpu(p).oper[1]^.reg;
  2542. { Look for:
  2543. mov %reg1,%reg2
  2544. ??? %reg2,r/m
  2545. Change to:
  2546. mov %reg1,%reg2
  2547. ??? %reg1,r/m
  2548. }
  2549. if taicpu(p).oper[0]^.typ = top_reg then
  2550. begin
  2551. if RegReadByInstruction(p_TargetReg, hp1) and
  2552. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2553. begin
  2554. { A change has occurred, just not in p }
  2555. Result := True;
  2556. TransferUsedRegs(TmpUsedRegs);
  2557. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2558. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2559. { Just in case something didn't get modified (e.g. an
  2560. implicit register) }
  2561. not RegReadByInstruction(p_TargetReg, hp1) then
  2562. begin
  2563. { We can remove the original MOV }
  2564. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2565. RemoveCurrentp(p, hp1);
  2566. { UsedRegs got updated by RemoveCurrentp }
  2567. Result := True;
  2568. Exit;
  2569. end;
  2570. { If we know a MOV instruction has become a null operation, we might as well
  2571. get rid of it now to save time. }
  2572. if (taicpu(hp1).opcode = A_MOV) and
  2573. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2574. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2575. { Just being a register is enough to confirm it's a null operation }
  2576. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2577. begin
  2578. Result := True;
  2579. { Speed-up to reduce a pipeline stall... if we had something like...
  2580. movl %eax,%edx
  2581. movw %dx,%ax
  2582. ... the second instruction would change to movw %ax,%ax, but
  2583. given that it is now %ax that's active rather than %eax,
  2584. penalties might occur due to a partial register write, so instead,
  2585. change it to a MOVZX instruction when optimising for speed.
  2586. }
  2587. if not (cs_opt_size in current_settings.optimizerswitches) and
  2588. IsMOVZXAcceptable and
  2589. (taicpu(hp1).opsize < taicpu(p).opsize)
  2590. {$ifdef x86_64}
  2591. { operations already implicitly set the upper 64 bits to zero }
  2592. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2593. {$endif x86_64}
  2594. then
  2595. begin
  2596. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2597. case taicpu(p).opsize of
  2598. S_W:
  2599. if taicpu(hp1).opsize = S_B then
  2600. taicpu(hp1).opsize := S_BL
  2601. else
  2602. InternalError(2020012911);
  2603. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2604. case taicpu(hp1).opsize of
  2605. S_B:
  2606. taicpu(hp1).opsize := S_BL;
  2607. S_W:
  2608. taicpu(hp1).opsize := S_WL;
  2609. else
  2610. InternalError(2020012912);
  2611. end;
  2612. else
  2613. InternalError(2020012910);
  2614. end;
  2615. taicpu(hp1).opcode := A_MOVZX;
  2616. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2617. end
  2618. else
  2619. begin
  2620. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2621. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2622. RemoveInstruction(hp1);
  2623. { The instruction after what was hp1 is now the immediate next instruction,
  2624. so we can continue to make optimisations if it's present }
  2625. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2626. Exit;
  2627. hp1 := hp2;
  2628. end;
  2629. end;
  2630. end;
  2631. end;
  2632. end;
  2633. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2634. overwrites the original destination register. e.g.
  2635. movl ###,%reg2d
  2636. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2637. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2638. }
  2639. if (taicpu(p).oper[1]^.typ = top_reg) and
  2640. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2641. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2642. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2643. begin
  2644. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2645. begin
  2646. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2647. case taicpu(p).oper[0]^.typ of
  2648. top_const:
  2649. { We have something like:
  2650. movb $x, %regb
  2651. movzbl %regb,%regd
  2652. Change to:
  2653. movl $x, %regd
  2654. }
  2655. begin
  2656. case taicpu(hp1).opsize of
  2657. S_BW:
  2658. begin
  2659. convert_mov_value(A_MOVSX, $FF);
  2660. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2661. taicpu(p).opsize := S_W;
  2662. end;
  2663. S_BL:
  2664. begin
  2665. convert_mov_value(A_MOVSX, $FF);
  2666. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2667. taicpu(p).opsize := S_L;
  2668. end;
  2669. S_WL:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FFFF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2673. taicpu(p).opsize := S_L;
  2674. end;
  2675. {$ifdef x86_64}
  2676. S_BQ:
  2677. begin
  2678. convert_mov_value(A_MOVSX, $FF);
  2679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2680. taicpu(p).opsize := S_Q;
  2681. end;
  2682. S_WQ:
  2683. begin
  2684. convert_mov_value(A_MOVSX, $FFFF);
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2686. taicpu(p).opsize := S_Q;
  2687. end;
  2688. S_LQ:
  2689. begin
  2690. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2692. taicpu(p).opsize := S_Q;
  2693. end;
  2694. {$endif x86_64}
  2695. else
  2696. { If hp1 was a MOV instruction, it should have been
  2697. optimised already }
  2698. InternalError(2020021001);
  2699. end;
  2700. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2701. RemoveInstruction(hp1);
  2702. Result := True;
  2703. Exit;
  2704. end;
  2705. top_ref:
  2706. begin
  2707. { We have something like:
  2708. movb mem, %regb
  2709. movzbl %regb,%regd
  2710. Change to:
  2711. movzbl mem, %regd
  2712. }
  2713. ThisRef := taicpu(p).oper[0]^.ref^;
  2714. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2715. begin
  2716. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2717. taicpu(hp1).loadref(0, ThisRef);
  2718. { Make sure any registers in the references are properly tracked }
  2719. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2720. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2721. if (ThisRef.index <> NR_NO) then
  2722. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2723. RemoveCurrentP(p, hp1);
  2724. Result := True;
  2725. Exit;
  2726. end;
  2727. end;
  2728. else
  2729. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2730. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2731. Exit;
  2732. end;
  2733. end
  2734. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2735. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2736. optimised }
  2737. else
  2738. begin
  2739. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2740. RemoveCurrentP(p, hp1);
  2741. Result := True;
  2742. Exit;
  2743. end;
  2744. end;
  2745. if (taicpu(hp1).opcode = A_AND) and
  2746. (taicpu(p).oper[1]^.typ = top_reg) and
  2747. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2748. begin
  2749. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2750. begin
  2751. case taicpu(p).opsize of
  2752. S_L:
  2753. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2754. begin
  2755. { Optimize out:
  2756. mov x, %reg
  2757. and ffffffffh, %reg
  2758. }
  2759. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2760. RemoveInstruction(hp1);
  2761. Result:=true;
  2762. exit;
  2763. end;
  2764. S_Q: { TODO: Confirm if this is even possible }
  2765. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2766. begin
  2767. { Optimize out:
  2768. mov x, %reg
  2769. and ffffffffffffffffh, %reg
  2770. }
  2771. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2772. RemoveInstruction(hp1);
  2773. Result:=true;
  2774. exit;
  2775. end;
  2776. else
  2777. ;
  2778. end;
  2779. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2780. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2781. GetNextInstruction(hp1,hp2) and
  2782. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2783. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2784. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2785. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2786. GetNextInstruction(hp2,hp3) and
  2787. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2788. (taicpu(hp3).condition in [C_E,C_NE]) then
  2789. begin
  2790. TransferUsedRegs(TmpUsedRegs);
  2791. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2792. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2793. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2794. begin
  2795. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2796. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2797. taicpu(hp1).opcode:=A_TEST;
  2798. RemoveInstruction(hp2);
  2799. RemoveCurrentP(p, hp1);
  2800. Result:=true;
  2801. exit;
  2802. end;
  2803. end;
  2804. end
  2805. else if IsMOVZXAcceptable and
  2806. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2807. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2808. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2809. then
  2810. begin
  2811. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2812. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2813. case taicpu(p).opsize of
  2814. S_B:
  2815. if (taicpu(hp1).oper[0]^.val = $ff) then
  2816. begin
  2817. { Convert:
  2818. movb x, %regl movb x, %regl
  2819. andw ffh, %regw andl ffh, %regd
  2820. To:
  2821. movzbw x, %regd movzbl x, %regd
  2822. (Identical registers, just different sizes)
  2823. }
  2824. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2825. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2826. case taicpu(hp1).opsize of
  2827. S_W: NewSize := S_BW;
  2828. S_L: NewSize := S_BL;
  2829. {$ifdef x86_64}
  2830. S_Q: NewSize := S_BQ;
  2831. {$endif x86_64}
  2832. else
  2833. InternalError(2018011510);
  2834. end;
  2835. end
  2836. else
  2837. NewSize := S_NO;
  2838. S_W:
  2839. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2840. begin
  2841. { Convert:
  2842. movw x, %regw
  2843. andl ffffh, %regd
  2844. To:
  2845. movzwl x, %regd
  2846. (Identical registers, just different sizes)
  2847. }
  2848. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2849. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2850. case taicpu(hp1).opsize of
  2851. S_L: NewSize := S_WL;
  2852. {$ifdef x86_64}
  2853. S_Q: NewSize := S_WQ;
  2854. {$endif x86_64}
  2855. else
  2856. InternalError(2018011511);
  2857. end;
  2858. end
  2859. else
  2860. NewSize := S_NO;
  2861. else
  2862. NewSize := S_NO;
  2863. end;
  2864. if NewSize <> S_NO then
  2865. begin
  2866. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2867. { The actual optimization }
  2868. taicpu(p).opcode := A_MOVZX;
  2869. taicpu(p).changeopsize(NewSize);
  2870. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2871. { Safeguard if "and" is followed by a conditional command }
  2872. TransferUsedRegs(TmpUsedRegs);
  2873. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2874. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2875. begin
  2876. { At this point, the "and" command is effectively equivalent to
  2877. "test %reg,%reg". This will be handled separately by the
  2878. Peephole Optimizer. [Kit] }
  2879. DebugMsg(SPeepholeOptimization + PreMessage +
  2880. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2881. end
  2882. else
  2883. begin
  2884. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2885. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2886. RemoveInstruction(hp1);
  2887. end;
  2888. Result := True;
  2889. Exit;
  2890. end;
  2891. end;
  2892. end;
  2893. if (taicpu(hp1).opcode = A_OR) and
  2894. (taicpu(p).oper[1]^.typ = top_reg) and
  2895. MatchOperand(taicpu(p).oper[0]^, 0) and
  2896. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2897. begin
  2898. { mov 0, %reg
  2899. or ###,%reg
  2900. Change to (only if the flags are not used):
  2901. mov ###,%reg
  2902. }
  2903. TransferUsedRegs(TmpUsedRegs);
  2904. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2905. DoOptimisation := True;
  2906. { Even if the flags are used, we might be able to do the optimisation
  2907. if the conditions are predictable }
  2908. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2909. begin
  2910. { Only perform if ### = %reg (the same register) or equal to 0,
  2911. so %reg is guaranteed to still have a value of zero }
  2912. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2913. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2914. begin
  2915. hp2 := hp1;
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2917. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2918. GetNextInstruction(hp2, hp3) do
  2919. begin
  2920. { Don't continue modifying if the flags state is getting changed }
  2921. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2922. Break;
  2923. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2924. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2925. begin
  2926. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2927. begin
  2928. { Condition is always true }
  2929. case taicpu(hp3).opcode of
  2930. A_Jcc:
  2931. begin
  2932. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2933. { Check for jump shortcuts before we destroy the condition }
  2934. DoJumpOptimizations(hp3, TempBool);
  2935. MakeUnconditional(taicpu(hp3));
  2936. Result := True;
  2937. end;
  2938. A_CMOVcc:
  2939. begin
  2940. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2941. taicpu(hp3).opcode := A_MOV;
  2942. taicpu(hp3).condition := C_None;
  2943. Result := True;
  2944. end;
  2945. A_SETcc:
  2946. begin
  2947. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2948. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2949. taicpu(hp3).opcode := A_MOV;
  2950. taicpu(hp3).ops := 2;
  2951. taicpu(hp3).condition := C_None;
  2952. taicpu(hp3).opsize := S_B;
  2953. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2954. taicpu(hp3).loadconst(0, 1);
  2955. Result := True;
  2956. end;
  2957. else
  2958. InternalError(2021090701);
  2959. end;
  2960. end
  2961. 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
  2962. begin
  2963. { Condition is always false }
  2964. case taicpu(hp3).opcode of
  2965. A_Jcc:
  2966. begin
  2967. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2968. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2969. RemoveInstruction(hp3);
  2970. Result := True;
  2971. { Since hp3 was deleted, hp2 must not be updated }
  2972. Continue;
  2973. end;
  2974. A_CMOVcc:
  2975. begin
  2976. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2977. RemoveInstruction(hp3);
  2978. Result := True;
  2979. { Since hp3 was deleted, hp2 must not be updated }
  2980. Continue;
  2981. end;
  2982. A_SETcc:
  2983. begin
  2984. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2985. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2986. taicpu(hp3).opcode := A_MOV;
  2987. taicpu(hp3).ops := 2;
  2988. taicpu(hp3).condition := C_None;
  2989. taicpu(hp3).opsize := S_B;
  2990. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2991. taicpu(hp3).loadconst(0, 0);
  2992. Result := True;
  2993. end;
  2994. else
  2995. InternalError(2021090702);
  2996. end;
  2997. end
  2998. else
  2999. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3000. DoOptimisation := False;
  3001. end;
  3002. hp2 := hp3;
  3003. end;
  3004. { Flags are still in use - don't optimise }
  3005. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3006. DoOptimisation := False;
  3007. end
  3008. else
  3009. DoOptimisation := False;
  3010. end;
  3011. if DoOptimisation then
  3012. begin
  3013. {$ifdef x86_64}
  3014. { OR only supports 32-bit sign-extended constants for 64-bit
  3015. instructions, so compensate for this if the constant is
  3016. encoded as a value greater than or equal to 2^31 }
  3017. if (taicpu(hp1).opsize = S_Q) and
  3018. (taicpu(hp1).oper[0]^.typ = top_const) and
  3019. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3020. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3021. {$endif x86_64}
  3022. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3023. taicpu(hp1).opcode := A_MOV;
  3024. RemoveCurrentP(p, hp1);
  3025. Result := True;
  3026. Exit;
  3027. end;
  3028. end;
  3029. { Next instruction is also a MOV ? }
  3030. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3031. begin
  3032. if MatchOpType(taicpu(p), top_const, top_ref) and
  3033. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3034. TryConstMerge(p, hp1) then
  3035. begin
  3036. Result := True;
  3037. { In case we have four byte writes in a row, check for 2 more
  3038. right now so we don't have to wait for another iteration of
  3039. pass 1
  3040. }
  3041. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3042. case taicpu(p).opsize of
  3043. S_W:
  3044. begin
  3045. if GetNextInstruction(p, hp1) and
  3046. MatchInstruction(hp1, A_MOV, [S_B]) and
  3047. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3048. GetNextInstruction(hp1, hp2) and
  3049. MatchInstruction(hp2, A_MOV, [S_B]) and
  3050. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3051. { Try to merge the two bytes }
  3052. TryConstMerge(hp1, hp2) then
  3053. { Now try to merge the two words (hp2 will get deleted) }
  3054. TryConstMerge(p, hp1);
  3055. end;
  3056. S_L:
  3057. begin
  3058. { Though this only really benefits x86_64 and not i386, it
  3059. gets a potential optimisation done faster and hence
  3060. reduces the number of times OptPass1MOV is entered }
  3061. if GetNextInstruction(p, hp1) and
  3062. MatchInstruction(hp1, A_MOV, [S_W]) and
  3063. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3064. GetNextInstruction(hp1, hp2) and
  3065. MatchInstruction(hp2, A_MOV, [S_W]) and
  3066. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3067. { Try to merge the two words }
  3068. TryConstMerge(hp1, hp2) then
  3069. { This will always fail on i386, so don't bother
  3070. calling it unless we're doing x86_64 }
  3071. {$ifdef x86_64}
  3072. { Now try to merge the two longwords (hp2 will get deleted) }
  3073. TryConstMerge(p, hp1)
  3074. {$endif x86_64}
  3075. ;
  3076. end;
  3077. else
  3078. ;
  3079. end;
  3080. Exit;
  3081. end;
  3082. if (taicpu(p).oper[1]^.typ = top_reg) and
  3083. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3084. begin
  3085. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3086. TransferUsedRegs(TmpUsedRegs);
  3087. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3088. { we have
  3089. mov x, %treg
  3090. mov %treg, y
  3091. }
  3092. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3093. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3094. { we've got
  3095. mov x, %treg
  3096. mov %treg, y
  3097. with %treg is not used after }
  3098. case taicpu(p).oper[0]^.typ Of
  3099. { top_reg is covered by DeepMOVOpt }
  3100. top_const:
  3101. begin
  3102. { change
  3103. mov const, %treg
  3104. mov %treg, y
  3105. to
  3106. mov const, y
  3107. }
  3108. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3109. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3110. begin
  3111. if taicpu(hp1).oper[1]^.typ=top_reg then
  3112. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3113. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3114. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3115. RemoveInstruction(hp1);
  3116. Result:=true;
  3117. Exit;
  3118. end;
  3119. end;
  3120. top_ref:
  3121. case taicpu(hp1).oper[1]^.typ of
  3122. top_reg:
  3123. begin
  3124. { change
  3125. mov mem, %treg
  3126. mov %treg, %reg
  3127. to
  3128. mov mem, %reg"
  3129. }
  3130. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3131. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3132. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3133. RemoveInstruction(hp1);
  3134. Result:=true;
  3135. Exit;
  3136. end;
  3137. top_ref:
  3138. begin
  3139. {$ifdef x86_64}
  3140. { Look for the following to simplify:
  3141. mov x(mem1), %reg
  3142. mov %reg, y(mem2)
  3143. mov x+8(mem1), %reg
  3144. mov %reg, y+8(mem2)
  3145. Change to:
  3146. movdqu x(mem1), %xmmreg
  3147. movdqu %xmmreg, y(mem2)
  3148. ...but only as long as the memory blocks don't overlap
  3149. }
  3150. SourceRef := taicpu(p).oper[0]^.ref^;
  3151. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3152. if (taicpu(p).opsize = S_Q) and
  3153. GetNextInstruction(hp1, hp2) and
  3154. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3155. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3156. begin
  3157. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3158. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3159. Inc(SourceRef.offset, 8);
  3160. if UseAVX then
  3161. begin
  3162. MovAligned := A_VMOVDQA;
  3163. MovUnaligned := A_VMOVDQU;
  3164. end
  3165. else
  3166. begin
  3167. MovAligned := A_MOVDQA;
  3168. MovUnaligned := A_MOVDQU;
  3169. end;
  3170. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3171. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3172. begin
  3173. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3174. Inc(TargetRef.offset, 8);
  3175. if GetNextInstruction(hp2, hp3) and
  3176. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3177. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3178. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3179. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3180. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3181. begin
  3182. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3183. if NewMMReg <> NR_NO then
  3184. begin
  3185. { Remember that the offsets are 8 ahead }
  3186. if ((SourceRef.offset mod 16) = 8) and
  3187. (
  3188. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3189. (SourceRef.base = current_procinfo.framepointer) or
  3190. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3191. ) then
  3192. taicpu(p).opcode := MovAligned
  3193. else
  3194. taicpu(p).opcode := MovUnaligned;
  3195. taicpu(p).opsize := S_XMM;
  3196. taicpu(p).oper[1]^.reg := NewMMReg;
  3197. if ((TargetRef.offset mod 16) = 8) and
  3198. (
  3199. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3200. (TargetRef.base = current_procinfo.framepointer) or
  3201. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3202. ) then
  3203. taicpu(hp1).opcode := MovAligned
  3204. else
  3205. taicpu(hp1).opcode := MovUnaligned;
  3206. taicpu(hp1).opsize := S_XMM;
  3207. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3208. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3209. RemoveInstruction(hp2);
  3210. RemoveInstruction(hp3);
  3211. Result := True;
  3212. Exit;
  3213. end;
  3214. end;
  3215. end
  3216. else
  3217. begin
  3218. { See if the next references are 8 less rather than 8 greater }
  3219. Dec(SourceRef.offset, 16); { -8 the other way }
  3220. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3221. begin
  3222. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3223. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3224. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3225. GetNextInstruction(hp2, hp3) and
  3226. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3227. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3228. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3229. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3230. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3231. begin
  3232. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3233. if NewMMReg <> NR_NO then
  3234. begin
  3235. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3236. if ((SourceRef.offset mod 16) = 0) and
  3237. (
  3238. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3239. (SourceRef.base = current_procinfo.framepointer) or
  3240. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3241. ) then
  3242. taicpu(hp2).opcode := MovAligned
  3243. else
  3244. taicpu(hp2).opcode := MovUnaligned;
  3245. taicpu(hp2).opsize := S_XMM;
  3246. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3247. if ((TargetRef.offset mod 16) = 0) and
  3248. (
  3249. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3250. (TargetRef.base = current_procinfo.framepointer) or
  3251. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3252. ) then
  3253. taicpu(hp3).opcode := MovAligned
  3254. else
  3255. taicpu(hp3).opcode := MovUnaligned;
  3256. taicpu(hp3).opsize := S_XMM;
  3257. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3258. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3259. RemoveInstruction(hp1);
  3260. RemoveCurrentP(p, hp2);
  3261. Result := True;
  3262. Exit;
  3263. end;
  3264. end;
  3265. end;
  3266. end;
  3267. end;
  3268. {$endif x86_64}
  3269. end;
  3270. else
  3271. { The write target should be a reg or a ref }
  3272. InternalError(2021091601);
  3273. end;
  3274. else
  3275. ;
  3276. end
  3277. else
  3278. { %treg is used afterwards, but all eventualities
  3279. other than the first MOV instruction being a constant
  3280. are covered by DeepMOVOpt, so only check for that }
  3281. if (taicpu(p).oper[0]^.typ = top_const) and
  3282. (
  3283. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3284. not (cs_opt_size in current_settings.optimizerswitches) or
  3285. (taicpu(hp1).opsize = S_B)
  3286. ) and
  3287. (
  3288. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3289. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3290. ) then
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3293. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3294. end;
  3295. end;
  3296. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3297. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3298. { mov reg1, mem1 or mov mem1, reg1
  3299. mov mem2, reg2 mov reg2, mem2}
  3300. begin
  3301. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3302. { mov reg1, mem1 or mov mem1, reg1
  3303. mov mem2, reg1 mov reg2, mem1}
  3304. begin
  3305. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3306. { Removes the second statement from
  3307. mov reg1, mem1/reg2
  3308. mov mem1/reg2, reg1 }
  3309. begin
  3310. if taicpu(p).oper[0]^.typ=top_reg then
  3311. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3312. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3313. RemoveInstruction(hp1);
  3314. Result:=true;
  3315. exit;
  3316. end
  3317. else
  3318. begin
  3319. TransferUsedRegs(TmpUsedRegs);
  3320. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3321. if (taicpu(p).oper[1]^.typ = top_ref) and
  3322. { mov reg1, mem1
  3323. mov mem2, reg1 }
  3324. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3325. GetNextInstruction(hp1, hp2) and
  3326. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3327. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3328. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3329. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3330. { change to
  3331. mov reg1, mem1 mov reg1, mem1
  3332. mov mem2, reg1 cmp reg1, mem2
  3333. cmp mem1, reg1
  3334. }
  3335. begin
  3336. RemoveInstruction(hp2);
  3337. taicpu(hp1).opcode := A_CMP;
  3338. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3339. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3340. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3341. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3342. end;
  3343. end;
  3344. end
  3345. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3346. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3347. begin
  3348. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3349. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3350. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3351. end
  3352. else
  3353. begin
  3354. TransferUsedRegs(TmpUsedRegs);
  3355. if GetNextInstruction(hp1, hp2) and
  3356. MatchOpType(taicpu(p),top_ref,top_reg) and
  3357. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3358. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3359. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3360. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3361. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3362. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3363. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3364. { mov mem1, %reg1
  3365. mov %reg1, mem2
  3366. mov mem2, reg2
  3367. to:
  3368. mov mem1, reg2
  3369. mov reg2, mem2}
  3370. begin
  3371. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3372. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3373. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3374. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3375. RemoveInstruction(hp2);
  3376. Result := True;
  3377. end
  3378. {$ifdef i386}
  3379. { this is enabled for i386 only, as the rules to create the reg sets below
  3380. are too complicated for x86-64, so this makes this code too error prone
  3381. on x86-64
  3382. }
  3383. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3384. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3385. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3386. { mov mem1, reg1 mov mem1, reg1
  3387. mov reg1, mem2 mov reg1, mem2
  3388. mov mem2, reg2 mov mem2, reg1
  3389. to: to:
  3390. mov mem1, reg1 mov mem1, reg1
  3391. mov mem1, reg2 mov reg1, mem2
  3392. mov reg1, mem2
  3393. or (if mem1 depends on reg1
  3394. and/or if mem2 depends on reg2)
  3395. to:
  3396. mov mem1, reg1
  3397. mov reg1, mem2
  3398. mov reg1, reg2
  3399. }
  3400. begin
  3401. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3402. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3403. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3404. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3405. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3406. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3407. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3408. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3409. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3410. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3411. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3412. end
  3413. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3414. begin
  3415. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3416. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3417. end
  3418. else
  3419. begin
  3420. RemoveInstruction(hp2);
  3421. end
  3422. {$endif i386}
  3423. ;
  3424. end;
  3425. end
  3426. { movl [mem1],reg1
  3427. movl [mem1],reg2
  3428. to
  3429. movl [mem1],reg1
  3430. movl reg1,reg2
  3431. }
  3432. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3433. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3434. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3435. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3436. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3437. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3438. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3439. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3440. begin
  3441. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3442. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3443. end;
  3444. { movl const1,[mem1]
  3445. movl [mem1],reg1
  3446. to
  3447. movl const1,reg1
  3448. movl reg1,[mem1]
  3449. }
  3450. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3451. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3452. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3453. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3454. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3455. begin
  3456. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3457. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3458. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3459. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3460. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3461. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3462. Result:=true;
  3463. exit;
  3464. end;
  3465. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3466. { Change:
  3467. movl %reg1,%reg2
  3468. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3469. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3470. To:
  3471. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3472. movl x(%reg1),%reg1
  3473. movl %reg1,%regX
  3474. }
  3475. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3476. begin
  3477. p_SourceReg := taicpu(p).oper[0]^.reg;
  3478. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3479. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3480. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3481. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3482. GetNextInstruction(hp1, hp2) and
  3483. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3484. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3485. begin
  3486. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3487. if RegInRef(p_TargetReg, SourceRef) and
  3488. { If %reg1 also appears in the second reference, then it will
  3489. not refer to the same memory block as the first reference }
  3490. not RegInRef(p_SourceReg, SourceRef) then
  3491. begin
  3492. { Check to see if the references match if %reg2 is changed to %reg1 }
  3493. if SourceRef.base = p_TargetReg then
  3494. SourceRef.base := p_SourceReg;
  3495. if SourceRef.index = p_TargetReg then
  3496. SourceRef.index := p_SourceReg;
  3497. { RefsEqual also checks to ensure both references are non-volatile }
  3498. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3499. begin
  3500. taicpu(hp2).loadreg(0, p_SourceReg);
  3501. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3502. Result := True;
  3503. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3504. begin
  3505. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3506. RemoveCurrentP(p, hp1);
  3507. Exit;
  3508. end
  3509. else
  3510. begin
  3511. { Check to see if %reg2 is no longer in use }
  3512. TransferUsedRegs(TmpUsedRegs);
  3513. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3514. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3515. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3516. begin
  3517. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3518. RemoveCurrentP(p, hp1);
  3519. Exit;
  3520. end;
  3521. end;
  3522. { If we reach this point, p and hp1 weren't actually modified,
  3523. so we can do a bit more work on this pass }
  3524. end;
  3525. end;
  3526. end;
  3527. end;
  3528. end;
  3529. { search further than the next instruction for a mov (as long as it's not a jump) }
  3530. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3531. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3532. (taicpu(p).oper[1]^.typ = top_reg) and
  3533. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3534. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3535. begin
  3536. { we work with hp2 here, so hp1 can be still used later on when
  3537. checking for GetNextInstruction_p }
  3538. hp3 := hp1;
  3539. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3540. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3541. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3542. TransferUsedRegs(TmpUsedRegs);
  3543. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3544. if NotFirstIteration then
  3545. JumpTracking := TLinkedList.Create
  3546. else
  3547. JumpTracking := nil;
  3548. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3549. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3550. (hp2.typ=ait_instruction) do
  3551. begin
  3552. case taicpu(hp2).opcode of
  3553. A_POP:
  3554. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3555. begin
  3556. if not CrossJump and
  3557. not RegUsedBetween(p_TargetReg, p, hp2) then
  3558. begin
  3559. { We can remove the original MOV since the register
  3560. wasn't used between it and its popping from the stack }
  3561. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3562. RemoveCurrentp(p, hp1);
  3563. Result := True;
  3564. JumpTracking.Free;
  3565. Exit;
  3566. end;
  3567. { Can't go any further }
  3568. Break;
  3569. end;
  3570. A_MOV:
  3571. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3572. ((taicpu(p).oper[0]^.typ=top_const) or
  3573. ((taicpu(p).oper[0]^.typ=top_reg) and
  3574. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3575. )
  3576. ) then
  3577. begin
  3578. { we have
  3579. mov x, %treg
  3580. mov %treg, y
  3581. }
  3582. { We don't need to call UpdateUsedRegs for every instruction between
  3583. p and hp2 because the register we're concerned about will not
  3584. become deallocated (otherwise GetNextInstructionUsingReg would
  3585. have stopped at an earlier instruction). [Kit] }
  3586. TempRegUsed :=
  3587. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3588. RegReadByInstruction(p_TargetReg, hp3) or
  3589. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3590. case taicpu(p).oper[0]^.typ Of
  3591. top_reg:
  3592. begin
  3593. { change
  3594. mov %reg, %treg
  3595. mov %treg, y
  3596. to
  3597. mov %reg, y
  3598. }
  3599. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3600. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3601. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3602. begin
  3603. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3604. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3605. if TempRegUsed then
  3606. begin
  3607. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3608. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3609. { Set the start of the next GetNextInstructionUsingRegCond search
  3610. to start at the entry right before hp2 (which is about to be removed) }
  3611. hp3 := tai(hp2.Previous);
  3612. RemoveInstruction(hp2);
  3613. { See if there's more we can optimise }
  3614. Continue;
  3615. end
  3616. else
  3617. begin
  3618. RemoveInstruction(hp2);
  3619. { We can remove the original MOV too }
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3621. RemoveCurrentP(p, hp1);
  3622. Result:=true;
  3623. JumpTracking.Free;
  3624. Exit;
  3625. end;
  3626. end
  3627. else
  3628. begin
  3629. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3630. taicpu(hp2).loadReg(0, p_SourceReg);
  3631. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3632. { Check to see if the register also appears in the reference }
  3633. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3634. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3635. { Don't remove the first instruction if the temporary register is in use }
  3636. if not TempRegUsed and
  3637. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3638. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3639. begin
  3640. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3641. RemoveCurrentP(p, hp1);
  3642. Result:=true;
  3643. JumpTracking.Free;
  3644. Exit;
  3645. end;
  3646. { No need to set Result to True here. If there's another instruction later
  3647. on that can be optimised, it will be detected when the main Pass 1 loop
  3648. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3649. end;
  3650. end;
  3651. top_const:
  3652. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3653. begin
  3654. { change
  3655. mov const, %treg
  3656. mov %treg, y
  3657. to
  3658. mov const, y
  3659. }
  3660. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3661. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3662. begin
  3663. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3664. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3665. if TempRegUsed then
  3666. begin
  3667. { Don't remove the first instruction if the temporary register is in use }
  3668. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3669. { No need to set Result to True. If there's another instruction later on
  3670. that can be optimised, it will be detected when the main Pass 1 loop
  3671. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3672. end
  3673. else
  3674. begin
  3675. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3676. RemoveCurrentP(p, hp1);
  3677. Result:=true;
  3678. Exit;
  3679. end;
  3680. end;
  3681. end;
  3682. else
  3683. Internalerror(2019103001);
  3684. end;
  3685. end
  3686. else
  3687. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3688. begin
  3689. if not CrossJump and
  3690. not RegUsedBetween(p_TargetReg, p, hp2) and
  3691. not RegReadByInstruction(p_TargetReg, hp2) then
  3692. begin
  3693. { Register is not used before it is overwritten }
  3694. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3695. RemoveCurrentp(p, hp1);
  3696. Result := True;
  3697. Exit;
  3698. end;
  3699. if (taicpu(p).oper[0]^.typ = top_const) and
  3700. (taicpu(hp2).oper[0]^.typ = top_const) then
  3701. begin
  3702. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3703. begin
  3704. { Same value - register hasn't changed }
  3705. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3706. RemoveInstruction(hp2);
  3707. Result := True;
  3708. { See if there's more we can optimise }
  3709. Continue;
  3710. end;
  3711. end;
  3712. end;
  3713. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3714. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3715. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3716. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3717. begin
  3718. {
  3719. Change from:
  3720. mov ###, %reg
  3721. ...
  3722. movs/z %reg,%reg (Same register, just different sizes)
  3723. To:
  3724. movs/z ###, %reg (Longer version)
  3725. ...
  3726. (remove)
  3727. }
  3728. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3729. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3730. { Keep the first instruction as mov if ### is a constant }
  3731. if taicpu(p).oper[0]^.typ = top_const then
  3732. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3733. else
  3734. begin
  3735. taicpu(p).opcode := taicpu(hp2).opcode;
  3736. taicpu(p).opsize := taicpu(hp2).opsize;
  3737. end;
  3738. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3739. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3740. RemoveInstruction(hp2);
  3741. Result := True;
  3742. JumpTracking.Free;
  3743. Exit;
  3744. end;
  3745. else
  3746. { Move down to the MatchOpType if-block below };
  3747. end;
  3748. { Also catches MOV/S/Z instructions that aren't modified }
  3749. if taicpu(p).oper[0]^.typ = top_reg then
  3750. begin
  3751. p_SourceReg := taicpu(p).oper[0]^.reg;
  3752. if
  3753. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3754. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3755. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3756. begin
  3757. Result := True;
  3758. { Just in case something didn't get modified (e.g. an
  3759. implicit register). Also, if it does read from this
  3760. register, then there's no longer an advantage to
  3761. changing the register on subsequent instructions.}
  3762. if not RegReadByInstruction(p_TargetReg, hp2) then
  3763. begin
  3764. { If a conditional jump was crossed, do not delete
  3765. the original MOV no matter what }
  3766. if not CrossJump and
  3767. { RegEndOfLife returns True if the register is
  3768. deallocated before the next instruction or has
  3769. been loaded with a new value }
  3770. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3771. begin
  3772. { We can remove the original MOV }
  3773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3774. RemoveCurrentp(p, hp1);
  3775. JumpTracking.Free;
  3776. Result := True;
  3777. Exit;
  3778. end;
  3779. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3780. begin
  3781. { See if there's more we can optimise }
  3782. hp3 := hp2;
  3783. Continue;
  3784. end;
  3785. end;
  3786. end;
  3787. end;
  3788. { Break out of the while loop under normal circumstances }
  3789. Break;
  3790. end;
  3791. JumpTracking.Free;
  3792. end;
  3793. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3794. (taicpu(p).oper[1]^.typ = top_reg) and
  3795. (taicpu(p).opsize = S_L) and
  3796. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3797. (hp2.typ = ait_instruction) and
  3798. (taicpu(hp2).opcode = A_AND) and
  3799. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3800. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3801. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3802. ) then
  3803. begin
  3804. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3805. begin
  3806. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3807. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3808. begin
  3809. { Optimize out:
  3810. mov x, %reg
  3811. and ffffffffh, %reg
  3812. }
  3813. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3814. RemoveInstruction(hp2);
  3815. Result:=true;
  3816. exit;
  3817. end;
  3818. end;
  3819. end;
  3820. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3821. x >= RetOffset) as it doesn't do anything (it writes either to a
  3822. parameter or to the temporary storage room for the function
  3823. result)
  3824. }
  3825. if IsExitCode(hp1) and
  3826. (taicpu(p).oper[1]^.typ = top_ref) and
  3827. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3828. (
  3829. (
  3830. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3831. not (
  3832. assigned(current_procinfo.procdef.funcretsym) and
  3833. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3834. )
  3835. ) or
  3836. { Also discard writes to the stack that are below the base pointer,
  3837. as this is temporary storage rather than a function result on the
  3838. stack, say. }
  3839. (
  3840. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3841. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3842. )
  3843. ) then
  3844. begin
  3845. RemoveCurrentp(p, hp1);
  3846. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3847. RemoveLastDeallocForFuncRes(p);
  3848. Result:=true;
  3849. exit;
  3850. end;
  3851. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3852. begin
  3853. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3854. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3855. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3856. begin
  3857. { change
  3858. mov reg1, mem1
  3859. test/cmp x, mem1
  3860. to
  3861. mov reg1, mem1
  3862. test/cmp x, reg1
  3863. }
  3864. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3865. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3866. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3867. Result := True;
  3868. Exit;
  3869. end;
  3870. if DoMovCmpMemOpt(p, hp1, True) then
  3871. begin
  3872. Result := True;
  3873. Exit;
  3874. end;
  3875. end;
  3876. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3877. { If the flags register is in use, don't change the instruction to an
  3878. ADD otherwise this will scramble the flags. [Kit] }
  3879. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3880. begin
  3881. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3882. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3883. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3884. ) or
  3885. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3886. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3887. )
  3888. ) then
  3889. { mov reg1,ref
  3890. lea reg2,[reg1,reg2]
  3891. to
  3892. add reg2,ref}
  3893. begin
  3894. TransferUsedRegs(TmpUsedRegs);
  3895. { reg1 may not be used afterwards }
  3896. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3897. begin
  3898. Taicpu(hp1).opcode:=A_ADD;
  3899. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3900. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3901. RemoveCurrentp(p, hp1);
  3902. result:=true;
  3903. exit;
  3904. end;
  3905. end;
  3906. { If the LEA instruction can be converted into an arithmetic instruction,
  3907. it may be possible to then fold it in the next optimisation, otherwise
  3908. there's nothing more that can be optimised here. }
  3909. if not ConvertLEA(taicpu(hp1)) then
  3910. Exit;
  3911. end;
  3912. if (taicpu(p).oper[1]^.typ = top_reg) and
  3913. (hp1.typ = ait_instruction) and
  3914. GetNextInstruction(hp1, hp2) and
  3915. MatchInstruction(hp2,A_MOV,[]) and
  3916. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3917. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3918. (
  3919. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3920. {$ifdef x86_64}
  3921. or
  3922. (
  3923. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3924. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3925. )
  3926. {$endif x86_64}
  3927. ) then
  3928. begin
  3929. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3930. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3931. { change movsX/movzX reg/ref, reg2
  3932. add/sub/or/... reg3/$const, reg2
  3933. mov reg2 reg/ref
  3934. dealloc reg2
  3935. to
  3936. add/sub/or/... reg3/$const, reg/ref }
  3937. begin
  3938. TransferUsedRegs(TmpUsedRegs);
  3939. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3940. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3941. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3942. begin
  3943. { by example:
  3944. movswl %si,%eax movswl %si,%eax p
  3945. decl %eax addl %edx,%eax hp1
  3946. movw %ax,%si movw %ax,%si hp2
  3947. ->
  3948. movswl %si,%eax movswl %si,%eax p
  3949. decw %eax addw %edx,%eax hp1
  3950. movw %ax,%si movw %ax,%si hp2
  3951. }
  3952. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3953. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3954. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3955. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3956. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3957. {
  3958. ->
  3959. movswl %si,%eax movswl %si,%eax p
  3960. decw %si addw %dx,%si hp1
  3961. movw %ax,%si movw %ax,%si hp2
  3962. }
  3963. case taicpu(hp1).ops of
  3964. 1:
  3965. begin
  3966. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3967. if taicpu(hp1).oper[0]^.typ=top_reg then
  3968. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3969. end;
  3970. 2:
  3971. begin
  3972. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3973. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3974. (taicpu(hp1).opcode<>A_SHL) and
  3975. (taicpu(hp1).opcode<>A_SHR) and
  3976. (taicpu(hp1).opcode<>A_SAR) then
  3977. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3978. end;
  3979. else
  3980. internalerror(2008042701);
  3981. end;
  3982. {
  3983. ->
  3984. decw %si addw %dx,%si p
  3985. }
  3986. RemoveInstruction(hp2);
  3987. RemoveCurrentP(p, hp1);
  3988. Result:=True;
  3989. Exit;
  3990. end;
  3991. end;
  3992. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3993. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3994. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3995. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3996. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3997. )
  3998. {$ifdef i386}
  3999. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4000. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4001. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4002. {$endif i386}
  4003. then
  4004. { change movsX/movzX reg/ref, reg2
  4005. add/sub/or/... regX/$const, reg2
  4006. mov reg2, reg3
  4007. dealloc reg2
  4008. to
  4009. movsX/movzX reg/ref, reg3
  4010. add/sub/or/... reg3/$const, reg3
  4011. }
  4012. begin
  4013. TransferUsedRegs(TmpUsedRegs);
  4014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4015. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4016. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4017. begin
  4018. { by example:
  4019. movswl %si,%eax movswl %si,%eax p
  4020. decl %eax addl %edx,%eax hp1
  4021. movw %ax,%si movw %ax,%si hp2
  4022. ->
  4023. movswl %si,%eax movswl %si,%eax p
  4024. decw %eax addw %edx,%eax hp1
  4025. movw %ax,%si movw %ax,%si hp2
  4026. }
  4027. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4028. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4029. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4030. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4031. { limit size of constants as well to avoid assembler errors, but
  4032. check opsize to avoid overflow when left shifting the 1 }
  4033. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4034. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4035. {$ifdef x86_64}
  4036. { Be careful of, for example:
  4037. movl %reg1,%reg2
  4038. addl %reg3,%reg2
  4039. movq %reg2,%reg4
  4040. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4041. }
  4042. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4043. begin
  4044. taicpu(hp2).changeopsize(S_L);
  4045. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4046. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4047. end;
  4048. {$endif x86_64}
  4049. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4050. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4051. if taicpu(p).oper[0]^.typ=top_reg then
  4052. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4053. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4054. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4055. {
  4056. ->
  4057. movswl %si,%eax movswl %si,%eax p
  4058. decw %si addw %dx,%si hp1
  4059. movw %ax,%si movw %ax,%si hp2
  4060. }
  4061. case taicpu(hp1).ops of
  4062. 1:
  4063. begin
  4064. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4065. if taicpu(hp1).oper[0]^.typ=top_reg then
  4066. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4067. end;
  4068. 2:
  4069. begin
  4070. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4071. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4072. (taicpu(hp1).opcode<>A_SHL) and
  4073. (taicpu(hp1).opcode<>A_SHR) and
  4074. (taicpu(hp1).opcode<>A_SAR) then
  4075. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4076. end;
  4077. else
  4078. internalerror(2018111801);
  4079. end;
  4080. {
  4081. ->
  4082. decw %si addw %dx,%si p
  4083. }
  4084. RemoveInstruction(hp2);
  4085. end;
  4086. end;
  4087. end;
  4088. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4089. GetNextInstruction(hp1, hp2) and
  4090. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4091. MatchOperand(Taicpu(p).oper[0]^,0) and
  4092. (Taicpu(p).oper[1]^.typ = top_reg) and
  4093. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4094. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4095. { mov reg1,0
  4096. bts reg1,operand1 --> mov reg1,operand2
  4097. or reg1,operand2 bts reg1,operand1}
  4098. begin
  4099. Taicpu(hp2).opcode:=A_MOV;
  4100. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4101. asml.remove(hp1);
  4102. insertllitem(hp2,hp2.next,hp1);
  4103. RemoveCurrentp(p, hp1);
  4104. Result:=true;
  4105. exit;
  4106. end;
  4107. {
  4108. mov ref,reg0
  4109. <op> reg0,reg1
  4110. dealloc reg0
  4111. to
  4112. <op> ref,reg1
  4113. }
  4114. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4115. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4116. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4117. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4118. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4119. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4120. begin
  4121. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4122. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4123. RemoveCurrentp(p, hp1);
  4124. Result:=true;
  4125. exit;
  4126. end;
  4127. {$ifdef x86_64}
  4128. { Convert:
  4129. movq x(ref),%reg64
  4130. shrq y,%reg64
  4131. To:
  4132. movl x+4(ref),%reg32
  4133. shrl y-32,%reg32 (Remove if y = 32)
  4134. }
  4135. if (taicpu(p).opsize = S_Q) and
  4136. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4137. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4138. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4139. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4140. (taicpu(hp1).oper[0]^.val >= 32) and
  4141. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4142. begin
  4143. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4144. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4145. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4146. { Convert to 32-bit }
  4147. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4148. taicpu(p).opsize := S_L;
  4149. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4150. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4151. if (taicpu(hp1).oper[0]^.val = 32) then
  4152. begin
  4153. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4154. RemoveInstruction(hp1);
  4155. end
  4156. else
  4157. begin
  4158. { This will potentially open up more arithmetic operations since
  4159. the peephole optimizer now has a big hint that only the lower
  4160. 32 bits are currently in use (and opcodes are smaller in size) }
  4161. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4162. taicpu(hp1).opsize := S_L;
  4163. Dec(taicpu(hp1).oper[0]^.val, 32);
  4164. DebugMsg(SPeepholeOptimization + PreMessage +
  4165. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4166. end;
  4167. Result := True;
  4168. Exit;
  4169. end;
  4170. {$endif x86_64}
  4171. { Backward optimisation. If we have:
  4172. func. %reg1,%reg2
  4173. mov %reg2,%reg3
  4174. (dealloc %reg2)
  4175. Change to:
  4176. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4177. }
  4178. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4179. begin
  4180. p_SourceReg := taicpu(p).oper[0]^.reg;
  4181. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4182. TransferUsedRegs(TmpUsedRegs);
  4183. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4184. GetLastInstruction(p, hp2) and
  4185. (hp2.typ = ait_instruction) and
  4186. { Have to make sure it's an instruction that only reads from
  4187. operand 1 and only writes (not reads or modifies) from operand 2;
  4188. in essence, a one-operand pure function such as BSR or POPCNT }
  4189. (taicpu(hp2).ops = 2) and
  4190. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4191. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4192. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4193. begin
  4194. case taicpu(hp2).opcode of
  4195. A_FSTSW, A_FNSTSW,
  4196. A_IN, A_INS, A_OUT, A_OUTS,
  4197. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4198. { These routines have explicit operands, but they are restricted in
  4199. what they can be (e.g. IN and OUT can only read from AL, AX or
  4200. EAX. }
  4201. ;
  4202. else
  4203. begin
  4204. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4205. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4206. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4207. RemoveCurrentp(p, hp1);
  4208. Result := True;
  4209. Exit;
  4210. end;
  4211. end;
  4212. end;
  4213. end;
  4214. end;
  4215. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4216. var
  4217. hp1 : tai;
  4218. begin
  4219. Result:=false;
  4220. if taicpu(p).ops <> 2 then
  4221. exit;
  4222. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4223. GetNextInstruction(p,hp1) then
  4224. begin
  4225. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4226. (taicpu(hp1).ops = 2) then
  4227. begin
  4228. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4229. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4230. { movXX reg1, mem1 or movXX mem1, reg1
  4231. movXX mem2, reg2 movXX reg2, mem2}
  4232. begin
  4233. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4234. { movXX reg1, mem1 or movXX mem1, reg1
  4235. movXX mem2, reg1 movXX reg2, mem1}
  4236. begin
  4237. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4238. begin
  4239. { Removes the second statement from
  4240. movXX reg1, mem1/reg2
  4241. movXX mem1/reg2, reg1
  4242. }
  4243. if taicpu(p).oper[0]^.typ=top_reg then
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. { Removes the second statement from
  4246. movXX mem1/reg1, reg2
  4247. movXX reg2, mem1/reg1
  4248. }
  4249. if (taicpu(p).oper[1]^.typ=top_reg) and
  4250. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4251. begin
  4252. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4253. RemoveInstruction(hp1);
  4254. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4255. Result:=true;
  4256. exit;
  4257. end
  4258. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4259. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4260. begin
  4261. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4262. RemoveInstruction(hp1);
  4263. Result:=true;
  4264. exit;
  4265. end;
  4266. end
  4267. end;
  4268. end;
  4269. end;
  4270. end;
  4271. end;
  4272. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4273. var
  4274. hp1 : tai;
  4275. begin
  4276. result:=false;
  4277. { replace
  4278. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4279. MovX %mreg2,%mreg1
  4280. dealloc %mreg2
  4281. by
  4282. <Op>X %mreg2,%mreg1
  4283. ?
  4284. }
  4285. if GetNextInstruction(p,hp1) and
  4286. { we mix single and double opperations here because we assume that the compiler
  4287. generates vmovapd only after double operations and vmovaps only after single operations }
  4288. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4289. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4290. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4291. (taicpu(p).oper[0]^.typ=top_reg) then
  4292. begin
  4293. TransferUsedRegs(TmpUsedRegs);
  4294. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4295. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4296. begin
  4297. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4298. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4299. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4300. RemoveInstruction(hp1);
  4301. result:=true;
  4302. end;
  4303. end;
  4304. end;
  4305. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4306. var
  4307. hp1, p_label, p_dist, hp1_dist: tai;
  4308. JumpLabel, JumpLabel_dist: TAsmLabel;
  4309. FirstValue, SecondValue: TCGInt;
  4310. begin
  4311. Result := False;
  4312. if (taicpu(p).oper[0]^.typ = top_const) and
  4313. (taicpu(p).oper[0]^.val <> -1) then
  4314. begin
  4315. { Convert unsigned maximum constants to -1 to aid optimisation }
  4316. case taicpu(p).opsize of
  4317. S_B:
  4318. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4319. begin
  4320. taicpu(p).oper[0]^.val := -1;
  4321. Result := True;
  4322. Exit;
  4323. end;
  4324. S_W:
  4325. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4326. begin
  4327. taicpu(p).oper[0]^.val := -1;
  4328. Result := True;
  4329. Exit;
  4330. end;
  4331. S_L:
  4332. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4333. begin
  4334. taicpu(p).oper[0]^.val := -1;
  4335. Result := True;
  4336. Exit;
  4337. end;
  4338. {$ifdef x86_64}
  4339. S_Q:
  4340. { Storing anything greater than $7FFFFFFF is not possible so do
  4341. nothing };
  4342. {$endif x86_64}
  4343. else
  4344. InternalError(2021121001);
  4345. end;
  4346. end;
  4347. if GetNextInstruction(p, hp1) and
  4348. TrySwapMovCmp(p, hp1) then
  4349. begin
  4350. Result := True;
  4351. Exit;
  4352. end;
  4353. { Search for:
  4354. test $x,(reg/ref)
  4355. jne @lbl1
  4356. test $y,(reg/ref) (same register or reference)
  4357. jne @lbl1
  4358. Change to:
  4359. test $(x or y),(reg/ref)
  4360. jne @lbl1
  4361. (Note, this doesn't work with je instead of jne)
  4362. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4363. Also search for:
  4364. test $x,(reg/ref)
  4365. je @lbl1
  4366. test $y,(reg/ref)
  4367. je/jne @lbl2
  4368. If (x or y) = x, then the second jump is deterministic
  4369. }
  4370. if (
  4371. (
  4372. (taicpu(p).oper[0]^.typ = top_const) or
  4373. (
  4374. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4375. (taicpu(p).oper[0]^.typ = top_reg) and
  4376. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4377. )
  4378. ) and
  4379. MatchInstruction(hp1, A_JCC, [])
  4380. ) then
  4381. begin
  4382. if (taicpu(p).oper[0]^.typ = top_reg) and
  4383. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4384. FirstValue := -1
  4385. else
  4386. FirstValue := taicpu(p).oper[0]^.val;
  4387. { If we have several test/jne's in a row, it might be the case that
  4388. the second label doesn't go to the same location, but the one
  4389. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4390. so accommodate for this with a while loop.
  4391. }
  4392. hp1_dist := hp1;
  4393. if GetNextInstruction(hp1, p_dist) and
  4394. (p_dist.typ = ait_instruction) and
  4395. (
  4396. (
  4397. (taicpu(p_dist).opcode = A_TEST) and
  4398. (
  4399. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4400. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4401. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4402. )
  4403. ) or
  4404. (
  4405. { cmp 0,%reg = test %reg,%reg }
  4406. (taicpu(p_dist).opcode = A_CMP) and
  4407. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4408. )
  4409. ) and
  4410. { Make sure the destination operands are actually the same }
  4411. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4412. GetNextInstruction(p_dist, hp1_dist) and
  4413. MatchInstruction(hp1_dist, A_JCC, []) then
  4414. begin
  4415. if
  4416. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4417. (
  4418. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4419. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4420. ) then
  4421. SecondValue := -1
  4422. else
  4423. SecondValue := taicpu(p_dist).oper[0]^.val;
  4424. { If both of the TEST constants are identical, delete the second
  4425. TEST that is unnecessary. }
  4426. if (FirstValue = SecondValue) then
  4427. begin
  4428. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4429. RemoveInstruction(p_dist);
  4430. { Don't let the flags register become deallocated and reallocated between the jumps }
  4431. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4432. Result := True;
  4433. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4434. begin
  4435. { Since the second jump's condition is a subset of the first, we
  4436. know it will never branch because the first jump dominates it.
  4437. Get it out of the way now rather than wait for the jump
  4438. optimisations for a speed boost. }
  4439. if IsJumpToLabel(taicpu(hp1_dist)) then
  4440. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4441. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4442. RemoveInstruction(hp1_dist);
  4443. end
  4444. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4445. begin
  4446. { If the inverse of the first condition is a subset of the second,
  4447. the second one will definitely branch if the first one doesn't }
  4448. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4449. MakeUnconditional(taicpu(hp1_dist));
  4450. RemoveDeadCodeAfterJump(hp1_dist);
  4451. end;
  4452. Exit;
  4453. end;
  4454. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4455. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4456. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4457. then the second jump will never branch, so it can also be
  4458. removed regardless of where it goes }
  4459. (
  4460. (FirstValue = -1) or
  4461. (SecondValue = -1) or
  4462. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4463. ) then
  4464. begin
  4465. { Same jump location... can be a register since nothing's changed }
  4466. { If any of the entries are equivalent to test %reg,%reg, then the
  4467. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4468. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4469. if IsJumpToLabel(taicpu(hp1_dist)) then
  4470. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4471. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4472. RemoveInstruction(hp1_dist);
  4473. { Only remove the second test if no jumps or other conditional instructions follow }
  4474. TransferUsedRegs(TmpUsedRegs);
  4475. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4476. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4477. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4478. RemoveInstruction(p_dist);
  4479. Result := True;
  4480. Exit;
  4481. end;
  4482. end;
  4483. end;
  4484. { Search for:
  4485. test %reg,%reg
  4486. j(c1) @lbl1
  4487. ...
  4488. @lbl:
  4489. test %reg,%reg (same register)
  4490. j(c2) @lbl2
  4491. If c2 is a subset of c1, change to:
  4492. test %reg,%reg
  4493. j(c1) @lbl2
  4494. (@lbl1 may become a dead label as a result)
  4495. }
  4496. if (taicpu(p).oper[1]^.typ = top_reg) and
  4497. (taicpu(p).oper[0]^.typ = top_reg) and
  4498. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4499. MatchInstruction(hp1, A_JCC, []) and
  4500. IsJumpToLabel(taicpu(hp1)) then
  4501. begin
  4502. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4503. p_label := nil;
  4504. if Assigned(JumpLabel) then
  4505. p_label := getlabelwithsym(JumpLabel);
  4506. if Assigned(p_label) and
  4507. GetNextInstruction(p_label, p_dist) and
  4508. MatchInstruction(p_dist, A_TEST, []) and
  4509. { It's fine if the second test uses smaller sub-registers }
  4510. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4511. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4512. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4513. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4514. GetNextInstruction(p_dist, hp1_dist) and
  4515. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4516. begin
  4517. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4518. if JumpLabel = JumpLabel_dist then
  4519. { This is an infinite loop }
  4520. Exit;
  4521. { Best optimisation when the first condition is a subset (or equal) of the second }
  4522. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4523. begin
  4524. { Any registers used here will already be allocated }
  4525. if Assigned(JumpLabel) then
  4526. JumpLabel.DecRefs;
  4527. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4528. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4529. Result := True;
  4530. Exit;
  4531. end;
  4532. end;
  4533. end;
  4534. end;
  4535. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4536. var
  4537. hp1, hp2: tai;
  4538. ActiveReg: TRegister;
  4539. OldOffset: asizeint;
  4540. ThisConst: TCGInt;
  4541. function RegDeallocated: Boolean;
  4542. begin
  4543. TransferUsedRegs(TmpUsedRegs);
  4544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4545. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4546. end;
  4547. begin
  4548. result:=false;
  4549. hp1 := nil;
  4550. { replace
  4551. addX const,%reg1
  4552. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4553. dealloc %reg1
  4554. by
  4555. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4556. }
  4557. if MatchOpType(taicpu(p),top_const,top_reg) then
  4558. begin
  4559. ActiveReg := taicpu(p).oper[1]^.reg;
  4560. { Ensures the entire register was updated }
  4561. if (taicpu(p).opsize >= S_L) and
  4562. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4563. MatchInstruction(hp1,A_LEA,[]) and
  4564. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4565. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4566. (
  4567. { Cover the case where the register in the reference is also the destination register }
  4568. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4569. (
  4570. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4571. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4572. RegDeallocated
  4573. )
  4574. ) then
  4575. begin
  4576. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4577. {$push}
  4578. {$R-}{$Q-}
  4579. { Explicitly disable overflow checking for these offset calculation
  4580. as those do not matter for the final result }
  4581. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4582. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4583. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4584. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4585. {$pop}
  4586. {$ifdef x86_64}
  4587. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4588. begin
  4589. { Overflow; abort }
  4590. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4591. end
  4592. else
  4593. {$endif x86_64}
  4594. begin
  4595. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4596. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4597. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4598. RemoveCurrentP(p, hp1)
  4599. else
  4600. RemoveCurrentP(p);
  4601. result:=true;
  4602. Exit;
  4603. end;
  4604. end;
  4605. if (
  4606. { Save calling GetNextInstructionUsingReg again }
  4607. Assigned(hp1) or
  4608. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4609. ) and
  4610. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4611. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4612. begin
  4613. if taicpu(hp1).oper[0]^.typ = top_const then
  4614. begin
  4615. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4616. if taicpu(hp1).opcode = A_ADD then
  4617. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4618. else
  4619. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4620. Result := True;
  4621. { Handle any overflows }
  4622. case taicpu(p).opsize of
  4623. S_B:
  4624. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4625. S_W:
  4626. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4627. S_L:
  4628. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4629. {$ifdef x86_64}
  4630. S_Q:
  4631. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4632. { Overflow; abort }
  4633. Result := False
  4634. else
  4635. taicpu(p).oper[0]^.val := ThisConst;
  4636. {$endif x86_64}
  4637. else
  4638. InternalError(2021102610);
  4639. end;
  4640. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4641. if Result then
  4642. begin
  4643. if (taicpu(p).oper[0]^.val < 0) and
  4644. (
  4645. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4646. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4647. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4648. ) then
  4649. begin
  4650. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4651. taicpu(p).opcode := A_SUB;
  4652. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4653. end
  4654. else
  4655. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4656. RemoveInstruction(hp1);
  4657. end;
  4658. end
  4659. else
  4660. begin
  4661. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4662. TransferUsedRegs(TmpUsedRegs);
  4663. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4664. hp2 := p;
  4665. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4666. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4667. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4668. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4669. begin
  4670. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4671. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4672. Asml.Remove(p);
  4673. Asml.InsertAfter(p, hp1);
  4674. p := hp1;
  4675. Result := True;
  4676. end;
  4677. end;
  4678. end;
  4679. end;
  4680. end;
  4681. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4682. var
  4683. hp1: tai;
  4684. ref: Integer;
  4685. saveref: treference;
  4686. Multiple: TCGInt;
  4687. Adjacent: Boolean;
  4688. begin
  4689. Result:=false;
  4690. { play save and throw an error if LEA uses a seg register prefix,
  4691. this is most likely an error somewhere else }
  4692. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4693. internalerror(2022022001);
  4694. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4695. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4696. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4697. (
  4698. { do not mess with leas accessing the stack pointer
  4699. unless it's a null operation }
  4700. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4701. (
  4702. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4703. (taicpu(p).oper[0]^.ref^.offset = 0)
  4704. )
  4705. ) and
  4706. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4707. begin
  4708. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4709. begin
  4710. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4711. begin
  4712. taicpu(p).opcode := A_MOV;
  4713. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4714. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4715. end
  4716. else
  4717. begin
  4718. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4719. RemoveCurrentP(p);
  4720. end;
  4721. Result:=true;
  4722. exit;
  4723. end
  4724. else if (
  4725. { continue to use lea to adjust the stack pointer,
  4726. it is the recommended way, but only if not optimizing for size }
  4727. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4728. (cs_opt_size in current_settings.optimizerswitches)
  4729. ) and
  4730. { If the flags register is in use, don't change the instruction
  4731. to an ADD otherwise this will scramble the flags. [Kit] }
  4732. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4733. ConvertLEA(taicpu(p)) then
  4734. begin
  4735. Result:=true;
  4736. exit;
  4737. end;
  4738. end;
  4739. { Don't optimise if the stack or frame pointer is the destination register }
  4740. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4741. Exit;
  4742. if GetNextInstruction(p,hp1) and
  4743. (hp1.typ=ait_instruction) then
  4744. begin
  4745. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4746. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4747. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4748. begin
  4749. TransferUsedRegs(TmpUsedRegs);
  4750. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4751. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4752. begin
  4753. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4754. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4755. RemoveInstruction(hp1);
  4756. result:=true;
  4757. exit;
  4758. end;
  4759. end;
  4760. { changes
  4761. lea <ref1>, reg1
  4762. <op> ...,<ref. with reg1>,...
  4763. to
  4764. <op> ...,<ref1>,... }
  4765. { find a reference which uses reg1 }
  4766. 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
  4767. ref:=0
  4768. 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
  4769. ref:=1
  4770. else
  4771. ref:=-1;
  4772. if (ref<>-1) and
  4773. { reg1 must be either the base or the index }
  4774. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4775. begin
  4776. { reg1 can be removed from the reference }
  4777. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4778. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4779. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4780. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4781. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4782. else
  4783. Internalerror(2019111201);
  4784. { check if the can insert all data of the lea into the second instruction }
  4785. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4786. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4787. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4788. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4789. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4790. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4791. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4792. {$ifdef x86_64}
  4793. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4794. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4795. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4796. )
  4797. {$endif x86_64}
  4798. then
  4799. begin
  4800. { reg1 might not used by the second instruction after it is remove from the reference }
  4801. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4802. begin
  4803. TransferUsedRegs(TmpUsedRegs);
  4804. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4805. { reg1 is not updated so it might not be used afterwards }
  4806. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4807. begin
  4808. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4809. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4810. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4811. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4812. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4813. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4814. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4815. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4816. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4817. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4818. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4819. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4820. RemoveCurrentP(p, hp1);
  4821. result:=true;
  4822. exit;
  4823. end
  4824. end;
  4825. end;
  4826. { recover }
  4827. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4828. end;
  4829. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4830. if Adjacent or
  4831. { Check further ahead (up to 2 instructions ahead for -O2) }
  4832. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4833. begin
  4834. { Check common LEA/LEA conditions }
  4835. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4836. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4837. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4838. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4839. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4840. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4841. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4842. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4843. (
  4844. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4845. calling it (since it calls GetNextInstruction) }
  4846. Adjacent or
  4847. (
  4848. (
  4849. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4850. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4851. ) and (
  4852. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4853. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4854. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4855. )
  4856. )
  4857. ) then
  4858. begin
  4859. { changes
  4860. lea (regX,scale), reg1
  4861. lea offset(reg1,reg1), reg1
  4862. to
  4863. lea offset(regX,scale*2), reg1
  4864. and
  4865. lea (regX,scale1), reg1
  4866. lea offset(reg1,scale2), reg1
  4867. to
  4868. lea offset(regX,scale1*scale2), reg1
  4869. ... so long as the final scale does not exceed 8
  4870. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4871. }
  4872. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4873. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4874. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4875. (
  4876. (
  4877. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4878. ) or (
  4879. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4880. (
  4881. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4882. (
  4883. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4884. Adjacent or
  4885. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4886. )
  4887. )
  4888. )
  4889. ) and (
  4890. (
  4891. { lea (reg1,scale2), reg1 variant }
  4892. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4893. (
  4894. (
  4895. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4896. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4897. ) or (
  4898. { lea (regX,regX), reg1 variant }
  4899. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4900. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4901. )
  4902. )
  4903. ) or (
  4904. { lea (reg1,reg1), reg1 variant }
  4905. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4906. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4907. )
  4908. ) then
  4909. begin
  4910. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4911. { Make everything homogeneous to make calculations easier }
  4912. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4913. begin
  4914. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4915. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4916. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4917. else
  4918. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4919. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4920. end;
  4921. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4922. begin
  4923. { Just to prevent miscalculations }
  4924. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4925. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4926. else
  4927. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4928. end
  4929. else
  4930. begin
  4931. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4932. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4933. end;
  4934. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4935. RemoveCurrentP(p);
  4936. result:=true;
  4937. exit;
  4938. end
  4939. { changes
  4940. lea offset1(regX), reg1
  4941. lea offset2(reg1), reg1
  4942. to
  4943. lea offset1+offset2(regX), reg1 }
  4944. else if
  4945. (
  4946. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4947. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4948. ) or (
  4949. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4950. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4951. (
  4952. (
  4953. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4954. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4955. ) or (
  4956. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4957. (
  4958. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4959. (
  4960. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4961. (
  4962. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4963. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4964. )
  4965. )
  4966. )
  4967. )
  4968. )
  4969. ) then
  4970. begin
  4971. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4972. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4973. begin
  4974. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4975. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4976. { if the register is used as index and base, we have to increase for base as well
  4977. and adapt base }
  4978. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4979. begin
  4980. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4981. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4982. end;
  4983. end
  4984. else
  4985. begin
  4986. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4987. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4988. end;
  4989. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4990. begin
  4991. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4992. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4993. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4994. end;
  4995. RemoveCurrentP(p);
  4996. result:=true;
  4997. exit;
  4998. end;
  4999. end;
  5000. { Change:
  5001. leal/q $x(%reg1),%reg2
  5002. ...
  5003. shll/q $y,%reg2
  5004. To:
  5005. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5006. }
  5007. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5008. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5009. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5010. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5011. (taicpu(hp1).oper[0]^.val <= 3) then
  5012. begin
  5013. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5014. TransferUsedRegs(TmpUsedRegs);
  5015. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5016. if
  5017. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5018. (this works even if scalefactor is zero) }
  5019. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5020. { Ensure offset doesn't go out of bounds }
  5021. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5022. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5023. (
  5024. (
  5025. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5026. (
  5027. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5028. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5029. (
  5030. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5031. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5032. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5033. )
  5034. )
  5035. ) or (
  5036. (
  5037. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5038. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5039. ) and
  5040. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5041. )
  5042. ) then
  5043. begin
  5044. repeat
  5045. with taicpu(p).oper[0]^.ref^ do
  5046. begin
  5047. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5048. if index = base then
  5049. begin
  5050. if Multiple > 4 then
  5051. { Optimisation will no longer work because resultant
  5052. scale factor will exceed 8 }
  5053. Break;
  5054. base := NR_NO;
  5055. scalefactor := 2;
  5056. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5057. end
  5058. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5059. begin
  5060. { Scale factor only works on the index register }
  5061. index := base;
  5062. base := NR_NO;
  5063. end;
  5064. { For safety }
  5065. if scalefactor <= 1 then
  5066. begin
  5067. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5068. scalefactor := Multiple;
  5069. end
  5070. else
  5071. begin
  5072. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5073. scalefactor := scalefactor * Multiple;
  5074. end;
  5075. offset := offset * Multiple;
  5076. end;
  5077. RemoveInstruction(hp1);
  5078. Result := True;
  5079. Exit;
  5080. { This repeat..until loop exists for the benefit of Break }
  5081. until True;
  5082. end;
  5083. end;
  5084. end;
  5085. end;
  5086. end;
  5087. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5088. var
  5089. hp1 : tai;
  5090. begin
  5091. DoSubAddOpt := False;
  5092. if taicpu(p).oper[0]^.typ <> top_const then
  5093. { Should have been confirmed before calling }
  5094. InternalError(2021102601);
  5095. if GetLastInstruction(p, hp1) and
  5096. (hp1.typ = ait_instruction) and
  5097. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5098. case taicpu(hp1).opcode Of
  5099. A_DEC:
  5100. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5101. begin
  5102. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5103. RemoveInstruction(hp1);
  5104. end;
  5105. A_SUB:
  5106. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5107. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5108. begin
  5109. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5110. RemoveInstruction(hp1);
  5111. end;
  5112. A_ADD:
  5113. begin
  5114. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5115. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5116. begin
  5117. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5118. RemoveInstruction(hp1);
  5119. if (taicpu(p).oper[0]^.val = 0) then
  5120. begin
  5121. hp1 := tai(p.next);
  5122. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5123. if not GetLastInstruction(hp1, p) then
  5124. p := hp1;
  5125. DoSubAddOpt := True;
  5126. end
  5127. end;
  5128. end;
  5129. else
  5130. ;
  5131. end;
  5132. end;
  5133. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5134. begin
  5135. Result := False;
  5136. if UpdateTmpUsedRegs then
  5137. TransferUsedRegs(TmpUsedRegs);
  5138. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5139. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5140. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5141. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5142. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5143. (
  5144. (
  5145. (taicpu(hp1).opcode = A_TEST)
  5146. ) or (
  5147. (taicpu(hp1).opcode = A_CMP) and
  5148. { A sanity check more than anything }
  5149. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5150. )
  5151. ) then
  5152. begin
  5153. { change
  5154. mov mem, %reg
  5155. cmp/test x, %reg / test %reg,%reg
  5156. (reg deallocated)
  5157. to
  5158. cmp/test x, mem / cmp 0, mem
  5159. }
  5160. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5161. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5162. begin
  5163. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5164. if (taicpu(hp1).opcode = A_TEST) and
  5165. (
  5166. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5167. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5168. ) then
  5169. begin
  5170. taicpu(hp1).opcode := A_CMP;
  5171. taicpu(hp1).loadconst(0, 0);
  5172. end;
  5173. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5174. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5175. RemoveCurrentP(p, hp1);
  5176. Result := True;
  5177. Exit;
  5178. end;
  5179. end;
  5180. end;
  5181. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5182. var
  5183. hp2, hp3, hp4, hp5, hp6: tai;
  5184. ThisReg: TRegister;
  5185. JumpLoc: TAsmLabel;
  5186. begin
  5187. Result := False;
  5188. {
  5189. Convert:
  5190. j<c> .L1
  5191. .L2:
  5192. mov 1,reg
  5193. jmp .L3 (or ret, although it might not be a RET yet)
  5194. .L1:
  5195. mov 0,reg
  5196. jmp .L3 (or ret)
  5197. ( As long as .L3 <> .L1 or .L2)
  5198. To:
  5199. mov 0,reg
  5200. set<not(c)> reg
  5201. jmp .L3 (or ret)
  5202. .L2:
  5203. mov 1,reg
  5204. jmp .L3 (or ret)
  5205. .L1:
  5206. mov 0,reg
  5207. jmp .L3 (or ret)
  5208. }
  5209. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5210. Exit;
  5211. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5212. if GetNextInstruction(hp_label, hp2) and
  5213. MatchInstruction(hp2,A_MOV,[]) and
  5214. (taicpu(hp2).oper[0]^.typ = top_const) and
  5215. (
  5216. (
  5217. (taicpu(hp2).oper[1]^.typ = top_reg)
  5218. {$ifdef i386}
  5219. { Under i386, ESI, EDI, EBP and ESP
  5220. don't have an 8-bit representation }
  5221. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5222. {$endif i386}
  5223. ) or (
  5224. {$ifdef i386}
  5225. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5226. {$endif i386}
  5227. (taicpu(hp2).opsize = S_B)
  5228. )
  5229. ) and
  5230. GetNextInstruction(hp2, hp3) and
  5231. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5232. (
  5233. (taicpu(hp3).opcode=A_RET) or
  5234. (
  5235. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5236. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5237. )
  5238. ) and
  5239. GetNextInstruction(hp3, hp4) and
  5240. SkipAligns(hp4, hp4) and
  5241. (hp4.typ=ait_label) and
  5242. (tai_label(hp4).labsym=JumpLoc) and
  5243. (
  5244. not (cs_opt_size in current_settings.optimizerswitches) or
  5245. { If the initial jump is the label's only reference, then it will
  5246. become a dead label if the other conditions are met and hence
  5247. remove at least 2 instructions, including a jump }
  5248. (JumpLoc.getrefs = 1)
  5249. ) and
  5250. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5251. that will be optimised out }
  5252. GetNextInstruction(hp4, hp5) and
  5253. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5254. (taicpu(hp5).oper[0]^.typ = top_const) and
  5255. (
  5256. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5257. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5258. ) and
  5259. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5260. GetNextInstruction(hp5,hp6) and
  5261. (
  5262. (hp6.typ<>ait_label) or
  5263. SkipLabels(hp6, hp6)
  5264. ) and
  5265. (hp6.typ=ait_instruction) then
  5266. begin
  5267. { First, let's look at the two jumps that are hp3 and hp6 }
  5268. if not
  5269. (
  5270. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5271. (
  5272. (taicpu(hp6).opcode=A_RET) or
  5273. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5274. )
  5275. ) then
  5276. { If condition is False, then the JMP/RET instructions matched conventionally }
  5277. begin
  5278. { See if one of the jumps can be instantly converted into a RET }
  5279. if (taicpu(hp3).opcode=A_JMP) then
  5280. begin
  5281. { Reuse hp5 }
  5282. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5283. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5284. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5285. Exit;
  5286. if MatchInstruction(hp5, A_RET, []) then
  5287. begin
  5288. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5289. ConvertJumpToRET(hp3, hp5);
  5290. Result := True;
  5291. end
  5292. else
  5293. Exit;
  5294. end;
  5295. if (taicpu(hp6).opcode=A_JMP) then
  5296. begin
  5297. { Reuse hp5 }
  5298. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5299. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5300. Exit;
  5301. if MatchInstruction(hp5, A_RET, []) then
  5302. begin
  5303. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5304. ConvertJumpToRET(hp6, hp5);
  5305. Result := True;
  5306. end
  5307. else
  5308. Exit;
  5309. end;
  5310. if not
  5311. (
  5312. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5313. (
  5314. (taicpu(hp6).opcode=A_RET) or
  5315. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5316. )
  5317. ) then
  5318. { Still doesn't match }
  5319. Exit;
  5320. end;
  5321. if (taicpu(hp2).oper[0]^.val = 1) then
  5322. begin
  5323. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5324. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5325. end
  5326. else
  5327. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5328. if taicpu(hp2).opsize=S_B then
  5329. begin
  5330. if taicpu(hp2).oper[1]^.typ = top_reg then
  5331. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5332. else
  5333. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5334. hp2 := p;
  5335. end
  5336. else
  5337. begin
  5338. { Will be a register because the size can't be S_B otherwise }
  5339. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5340. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5341. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5342. taicpu(hp2).fileinfo:=taicpu(p).fileinfo;
  5343. { Inserting it right before p will guarantee that the flags are also tracked }
  5344. Asml.InsertBefore(hp2, p);
  5345. end;
  5346. taicpu(hp4).fileinfo := taicpu(hp2).fileinfo;
  5347. taicpu(hp4).condition := taicpu(p).condition;
  5348. asml.InsertBefore(hp4, hp2);
  5349. JumpLoc.decrefs;
  5350. if taicpu(hp3).opcode = A_JMP then
  5351. begin
  5352. MakeUnconditional(taicpu(p));
  5353. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5354. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5355. end
  5356. else
  5357. begin
  5358. taicpu(p).condition := C_None;
  5359. taicpu(p).opcode := A_RET;
  5360. taicpu(p).clearop(0);
  5361. taicpu(p).ops := 0;
  5362. end;
  5363. if (JumpLoc.getrefs = 0) then
  5364. RemoveDeadCodeAfterJump(hp3);
  5365. Result:=true;
  5366. exit;
  5367. end;
  5368. end;
  5369. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5370. var
  5371. hp1, hp2: tai;
  5372. ActiveReg: TRegister;
  5373. OldOffset: asizeint;
  5374. ThisConst: TCGInt;
  5375. function RegDeallocated: Boolean;
  5376. begin
  5377. TransferUsedRegs(TmpUsedRegs);
  5378. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5379. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5380. end;
  5381. begin
  5382. Result:=false;
  5383. hp1 := nil;
  5384. { replace
  5385. subX const,%reg1
  5386. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5387. dealloc %reg1
  5388. by
  5389. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5390. }
  5391. if MatchOpType(taicpu(p),top_const,top_reg) then
  5392. begin
  5393. ActiveReg := taicpu(p).oper[1]^.reg;
  5394. { Ensures the entire register was updated }
  5395. if (taicpu(p).opsize >= S_L) and
  5396. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5397. MatchInstruction(hp1,A_LEA,[]) and
  5398. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5399. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5400. (
  5401. { Cover the case where the register in the reference is also the destination register }
  5402. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5403. (
  5404. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5405. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5406. RegDeallocated
  5407. )
  5408. ) then
  5409. begin
  5410. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5411. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5412. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5413. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5414. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5415. {$ifdef x86_64}
  5416. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5417. begin
  5418. { Overflow; abort }
  5419. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5420. end
  5421. else
  5422. {$endif x86_64}
  5423. begin
  5424. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5425. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5426. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5427. RemoveCurrentP(p, hp1)
  5428. else
  5429. RemoveCurrentP(p);
  5430. result:=true;
  5431. Exit;
  5432. end;
  5433. end;
  5434. if (
  5435. { Save calling GetNextInstructionUsingReg again }
  5436. Assigned(hp1) or
  5437. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5438. ) and
  5439. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5440. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5441. begin
  5442. if taicpu(hp1).oper[0]^.typ = top_const then
  5443. begin
  5444. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5445. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5446. Result := True;
  5447. { Handle any overflows }
  5448. case taicpu(p).opsize of
  5449. S_B:
  5450. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5451. S_W:
  5452. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5453. S_L:
  5454. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5455. {$ifdef x86_64}
  5456. S_Q:
  5457. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5458. { Overflow; abort }
  5459. Result := False
  5460. else
  5461. taicpu(p).oper[0]^.val := ThisConst;
  5462. {$endif x86_64}
  5463. else
  5464. InternalError(2021102610);
  5465. end;
  5466. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5467. if Result then
  5468. begin
  5469. if (taicpu(p).oper[0]^.val < 0) and
  5470. (
  5471. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5472. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5473. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5474. ) then
  5475. begin
  5476. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5477. taicpu(p).opcode := A_SUB;
  5478. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5479. end
  5480. else
  5481. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5482. RemoveInstruction(hp1);
  5483. end;
  5484. end
  5485. else
  5486. begin
  5487. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5488. TransferUsedRegs(TmpUsedRegs);
  5489. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5490. hp2 := p;
  5491. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5492. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5493. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5494. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5495. begin
  5496. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5497. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5498. Asml.Remove(p);
  5499. Asml.InsertAfter(p, hp1);
  5500. p := hp1;
  5501. Result := True;
  5502. Exit;
  5503. end;
  5504. end;
  5505. end;
  5506. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5507. { * change "sub/add const1, reg" or "dec reg" followed by
  5508. "sub const2, reg" to one "sub ..., reg" }
  5509. {$ifdef i386}
  5510. if (taicpu(p).oper[0]^.val = 2) and
  5511. (ActiveReg = NR_ESP) and
  5512. { Don't do the sub/push optimization if the sub }
  5513. { comes from setting up the stack frame (JM) }
  5514. (not(GetLastInstruction(p,hp1)) or
  5515. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5516. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5517. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5518. begin
  5519. hp1 := tai(p.next);
  5520. while Assigned(hp1) and
  5521. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5522. not RegReadByInstruction(NR_ESP,hp1) and
  5523. not RegModifiedByInstruction(NR_ESP,hp1) do
  5524. hp1 := tai(hp1.next);
  5525. if Assigned(hp1) and
  5526. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5527. begin
  5528. taicpu(hp1).changeopsize(S_L);
  5529. if taicpu(hp1).oper[0]^.typ=top_reg then
  5530. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5531. hp1 := tai(p.next);
  5532. RemoveCurrentp(p, hp1);
  5533. Result:=true;
  5534. exit;
  5535. end;
  5536. end;
  5537. {$endif i386}
  5538. if DoSubAddOpt(p) then
  5539. Result:=true;
  5540. end;
  5541. end;
  5542. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5543. var
  5544. TmpBool1,TmpBool2 : Boolean;
  5545. tmpref : treference;
  5546. hp1,hp2: tai;
  5547. mask: tcgint;
  5548. begin
  5549. Result:=false;
  5550. { All these optimisations work on "shl/sal const,%reg" }
  5551. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5552. Exit;
  5553. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5554. (taicpu(p).oper[0]^.val <= 3) then
  5555. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5556. begin
  5557. { should we check the next instruction? }
  5558. TmpBool1 := True;
  5559. { have we found an add/sub which could be
  5560. integrated in the lea? }
  5561. TmpBool2 := False;
  5562. reference_reset(tmpref,2,[]);
  5563. TmpRef.index := taicpu(p).oper[1]^.reg;
  5564. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5565. while TmpBool1 and
  5566. GetNextInstruction(p, hp1) and
  5567. (tai(hp1).typ = ait_instruction) and
  5568. ((((taicpu(hp1).opcode = A_ADD) or
  5569. (taicpu(hp1).opcode = A_SUB)) and
  5570. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5571. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5572. (((taicpu(hp1).opcode = A_INC) or
  5573. (taicpu(hp1).opcode = A_DEC)) and
  5574. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5575. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5576. ((taicpu(hp1).opcode = A_LEA) and
  5577. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5578. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5579. (not GetNextInstruction(hp1,hp2) or
  5580. not instrReadsFlags(hp2)) Do
  5581. begin
  5582. TmpBool1 := False;
  5583. if taicpu(hp1).opcode=A_LEA then
  5584. begin
  5585. if (TmpRef.base = NR_NO) and
  5586. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5587. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5588. { Segment register isn't a concern here }
  5589. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5590. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5591. begin
  5592. TmpBool1 := True;
  5593. TmpBool2 := True;
  5594. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5595. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5596. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5597. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5598. RemoveInstruction(hp1);
  5599. end
  5600. end
  5601. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5602. begin
  5603. TmpBool1 := True;
  5604. TmpBool2 := True;
  5605. case taicpu(hp1).opcode of
  5606. A_ADD:
  5607. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5608. A_SUB:
  5609. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5610. else
  5611. internalerror(2019050536);
  5612. end;
  5613. RemoveInstruction(hp1);
  5614. end
  5615. else
  5616. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5617. (((taicpu(hp1).opcode = A_ADD) and
  5618. (TmpRef.base = NR_NO)) or
  5619. (taicpu(hp1).opcode = A_INC) or
  5620. (taicpu(hp1).opcode = A_DEC)) then
  5621. begin
  5622. TmpBool1 := True;
  5623. TmpBool2 := True;
  5624. case taicpu(hp1).opcode of
  5625. A_ADD:
  5626. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5627. A_INC:
  5628. inc(TmpRef.offset);
  5629. A_DEC:
  5630. dec(TmpRef.offset);
  5631. else
  5632. internalerror(2019050535);
  5633. end;
  5634. RemoveInstruction(hp1);
  5635. end;
  5636. end;
  5637. if TmpBool2
  5638. {$ifndef x86_64}
  5639. or
  5640. ((current_settings.optimizecputype < cpu_Pentium2) and
  5641. (taicpu(p).oper[0]^.val <= 3) and
  5642. not(cs_opt_size in current_settings.optimizerswitches))
  5643. {$endif x86_64}
  5644. then
  5645. begin
  5646. if not(TmpBool2) and
  5647. (taicpu(p).oper[0]^.val=1) then
  5648. begin
  5649. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5650. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5651. end
  5652. else
  5653. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5654. taicpu(p).oper[1]^.reg);
  5655. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5656. InsertLLItem(p.previous, p.next, hp1);
  5657. p.free;
  5658. p := hp1;
  5659. end;
  5660. end
  5661. {$ifndef x86_64}
  5662. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5663. begin
  5664. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5665. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5666. (unlike shl, which is only Tairable in the U pipe) }
  5667. if taicpu(p).oper[0]^.val=1 then
  5668. begin
  5669. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5670. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5671. InsertLLItem(p.previous, p.next, hp1);
  5672. p.free;
  5673. p := hp1;
  5674. end
  5675. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5676. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5677. else if (taicpu(p).opsize = S_L) and
  5678. (taicpu(p).oper[0]^.val<= 3) then
  5679. begin
  5680. reference_reset(tmpref,2,[]);
  5681. TmpRef.index := taicpu(p).oper[1]^.reg;
  5682. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5683. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5684. InsertLLItem(p.previous, p.next, hp1);
  5685. p.free;
  5686. p := hp1;
  5687. end;
  5688. end
  5689. {$endif x86_64}
  5690. else if
  5691. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5692. (
  5693. (
  5694. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5695. SetAndTest(hp1, hp2)
  5696. {$ifdef x86_64}
  5697. ) or
  5698. (
  5699. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5700. GetNextInstruction(hp1, hp2) and
  5701. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5702. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5703. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5704. {$endif x86_64}
  5705. )
  5706. ) and
  5707. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5708. begin
  5709. { Change:
  5710. shl x, %reg1
  5711. mov -(1<<x), %reg2
  5712. and %reg2, %reg1
  5713. Or:
  5714. shl x, %reg1
  5715. and -(1<<x), %reg1
  5716. To just:
  5717. shl x, %reg1
  5718. Since the and operation only zeroes bits that are already zero from the shl operation
  5719. }
  5720. case taicpu(p).oper[0]^.val of
  5721. 8:
  5722. mask:=$FFFFFFFFFFFFFF00;
  5723. 16:
  5724. mask:=$FFFFFFFFFFFF0000;
  5725. 32:
  5726. mask:=$FFFFFFFF00000000;
  5727. 63:
  5728. { Constant pre-calculated to prevent overflow errors with Int64 }
  5729. mask:=$8000000000000000;
  5730. else
  5731. begin
  5732. if taicpu(p).oper[0]^.val >= 64 then
  5733. { Shouldn't happen realistically, since the register
  5734. is guaranteed to be set to zero at this point }
  5735. mask := 0
  5736. else
  5737. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5738. end;
  5739. end;
  5740. if taicpu(hp1).oper[0]^.val = mask then
  5741. begin
  5742. { Everything checks out, perform the optimisation, as long as
  5743. the FLAGS register isn't being used}
  5744. TransferUsedRegs(TmpUsedRegs);
  5745. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5746. {$ifdef x86_64}
  5747. if (hp1 <> hp2) then
  5748. begin
  5749. { "shl/mov/and" version }
  5750. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5751. { Don't do the optimisation if the FLAGS register is in use }
  5752. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5753. begin
  5754. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5755. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5756. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5757. begin
  5758. RemoveInstruction(hp1);
  5759. Result := True;
  5760. end;
  5761. { Only set Result to True if the 'mov' instruction was removed }
  5762. RemoveInstruction(hp2);
  5763. end;
  5764. end
  5765. else
  5766. {$endif x86_64}
  5767. begin
  5768. { "shl/and" version }
  5769. { Don't do the optimisation if the FLAGS register is in use }
  5770. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5771. begin
  5772. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5773. RemoveInstruction(hp1);
  5774. Result := True;
  5775. end;
  5776. end;
  5777. Exit;
  5778. end
  5779. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5780. begin
  5781. { Even if the mask doesn't allow for its removal, we might be
  5782. able to optimise the mask for the "shl/and" version, which
  5783. may permit other peephole optimisations }
  5784. {$ifdef DEBUG_AOPTCPU}
  5785. mask := taicpu(hp1).oper[0]^.val and mask;
  5786. if taicpu(hp1).oper[0]^.val <> mask then
  5787. begin
  5788. DebugMsg(
  5789. SPeepholeOptimization +
  5790. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5791. ' to $' + debug_tostr(mask) +
  5792. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5793. taicpu(hp1).oper[0]^.val := mask;
  5794. end;
  5795. {$else DEBUG_AOPTCPU}
  5796. { If debugging is off, just set the operand even if it's the same }
  5797. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5798. {$endif DEBUG_AOPTCPU}
  5799. end;
  5800. end;
  5801. {
  5802. change
  5803. shl/sal const,reg
  5804. <op> ...(...,reg,1),...
  5805. into
  5806. <op> ...(...,reg,1 shl const),...
  5807. if const in 1..3
  5808. }
  5809. if MatchOpType(taicpu(p), top_const, top_reg) and
  5810. (taicpu(p).oper[0]^.val in [1..3]) and
  5811. GetNextInstruction(p, hp1) and
  5812. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5813. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5814. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5815. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5816. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5817. begin
  5818. TransferUsedRegs(TmpUsedRegs);
  5819. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5820. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5821. begin
  5822. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5823. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5824. RemoveCurrentP(p);
  5825. Result:=true;
  5826. end;
  5827. end;
  5828. end;
  5829. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5830. var
  5831. CurrentRef: TReference;
  5832. FullReg: TRegister;
  5833. hp1, hp2: tai;
  5834. begin
  5835. Result := False;
  5836. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5837. Exit;
  5838. { We assume you've checked if the operand is actually a reference by
  5839. this point. If it isn't, you'll most likely get an access violation }
  5840. CurrentRef := first_mov.oper[1]^.ref^;
  5841. { Memory must be aligned }
  5842. if (CurrentRef.offset mod 4) <> 0 then
  5843. Exit;
  5844. Inc(CurrentRef.offset);
  5845. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5846. if MatchOperand(second_mov.oper[0]^, 0) and
  5847. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5848. GetNextInstruction(second_mov, hp1) and
  5849. (hp1.typ = ait_instruction) and
  5850. (taicpu(hp1).opcode = A_MOV) and
  5851. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5852. (taicpu(hp1).oper[0]^.val = 0) then
  5853. begin
  5854. Inc(CurrentRef.offset);
  5855. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5856. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5857. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5858. begin
  5859. case taicpu(hp1).opsize of
  5860. S_B:
  5861. if GetNextInstruction(hp1, hp2) and
  5862. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5863. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5864. (taicpu(hp2).oper[0]^.val = 0) then
  5865. begin
  5866. Inc(CurrentRef.offset);
  5867. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5868. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5869. (taicpu(hp2).opsize = S_B) then
  5870. begin
  5871. RemoveInstruction(hp1);
  5872. RemoveInstruction(hp2);
  5873. first_mov.opsize := S_L;
  5874. if first_mov.oper[0]^.typ = top_reg then
  5875. begin
  5876. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5877. { Reuse second_mov as a MOVZX instruction }
  5878. second_mov.opcode := A_MOVZX;
  5879. second_mov.opsize := S_BL;
  5880. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5881. second_mov.loadreg(1, FullReg);
  5882. first_mov.oper[0]^.reg := FullReg;
  5883. asml.Remove(second_mov);
  5884. asml.InsertBefore(second_mov, first_mov);
  5885. end
  5886. else
  5887. { It's a value }
  5888. begin
  5889. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5890. RemoveInstruction(second_mov);
  5891. end;
  5892. Result := True;
  5893. Exit;
  5894. end;
  5895. end;
  5896. S_W:
  5897. begin
  5898. RemoveInstruction(hp1);
  5899. first_mov.opsize := S_L;
  5900. if first_mov.oper[0]^.typ = top_reg then
  5901. begin
  5902. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5903. { Reuse second_mov as a MOVZX instruction }
  5904. second_mov.opcode := A_MOVZX;
  5905. second_mov.opsize := S_BL;
  5906. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5907. second_mov.loadreg(1, FullReg);
  5908. first_mov.oper[0]^.reg := FullReg;
  5909. asml.Remove(second_mov);
  5910. asml.InsertBefore(second_mov, first_mov);
  5911. end
  5912. else
  5913. { It's a value }
  5914. begin
  5915. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5916. RemoveInstruction(second_mov);
  5917. end;
  5918. Result := True;
  5919. Exit;
  5920. end;
  5921. else
  5922. ;
  5923. end;
  5924. end;
  5925. end;
  5926. end;
  5927. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5928. { returns true if a "continue" should be done after this optimization }
  5929. var
  5930. hp1, hp2: tai;
  5931. begin
  5932. Result := false;
  5933. if MatchOpType(taicpu(p),top_ref) and
  5934. GetNextInstruction(p, hp1) and
  5935. (hp1.typ = ait_instruction) and
  5936. (((taicpu(hp1).opcode = A_FLD) and
  5937. (taicpu(p).opcode = A_FSTP)) or
  5938. ((taicpu(p).opcode = A_FISTP) and
  5939. (taicpu(hp1).opcode = A_FILD))) and
  5940. MatchOpType(taicpu(hp1),top_ref) and
  5941. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5942. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5943. begin
  5944. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5945. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5946. GetNextInstruction(hp1, hp2) and
  5947. (hp2.typ = ait_instruction) and
  5948. IsExitCode(hp2) and
  5949. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5950. not(assigned(current_procinfo.procdef.funcretsym) and
  5951. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5952. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5953. begin
  5954. RemoveInstruction(hp1);
  5955. RemoveCurrentP(p, hp2);
  5956. RemoveLastDeallocForFuncRes(p);
  5957. Result := true;
  5958. end
  5959. else
  5960. { we can do this only in fast math mode as fstp is rounding ...
  5961. ... still disabled as it breaks the compiler and/or rtl }
  5962. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5963. { ... or if another fstp equal to the first one follows }
  5964. (GetNextInstruction(hp1,hp2) and
  5965. (hp2.typ = ait_instruction) and
  5966. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5967. (taicpu(p).opsize=taicpu(hp2).opsize))
  5968. ) and
  5969. { fst can't store an extended/comp value }
  5970. (taicpu(p).opsize <> S_FX) and
  5971. (taicpu(p).opsize <> S_IQ) then
  5972. begin
  5973. if (taicpu(p).opcode = A_FSTP) then
  5974. taicpu(p).opcode := A_FST
  5975. else
  5976. taicpu(p).opcode := A_FIST;
  5977. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5978. RemoveInstruction(hp1);
  5979. end;
  5980. end;
  5981. end;
  5982. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5983. var
  5984. hp1, hp2: tai;
  5985. begin
  5986. result:=false;
  5987. if MatchOpType(taicpu(p),top_reg) and
  5988. GetNextInstruction(p, hp1) and
  5989. (hp1.typ = Ait_Instruction) and
  5990. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5991. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5992. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5993. { change to
  5994. fld reg fxxx reg,st
  5995. fxxxp st, st1 (hp1)
  5996. Remark: non commutative operations must be reversed!
  5997. }
  5998. begin
  5999. case taicpu(hp1).opcode Of
  6000. A_FMULP,A_FADDP,
  6001. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6002. begin
  6003. case taicpu(hp1).opcode Of
  6004. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6005. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6006. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6007. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6008. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6009. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6010. else
  6011. internalerror(2019050534);
  6012. end;
  6013. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6014. taicpu(hp1).oper[1]^.reg := NR_ST;
  6015. RemoveCurrentP(p, hp1);
  6016. Result:=true;
  6017. exit;
  6018. end;
  6019. else
  6020. ;
  6021. end;
  6022. end
  6023. else
  6024. if MatchOpType(taicpu(p),top_ref) and
  6025. GetNextInstruction(p, hp2) and
  6026. (hp2.typ = Ait_Instruction) and
  6027. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6028. (taicpu(p).opsize in [S_FS, S_FL]) and
  6029. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6030. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6031. if GetLastInstruction(p, hp1) and
  6032. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6033. MatchOpType(taicpu(hp1),top_ref) and
  6034. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6035. if ((taicpu(hp2).opcode = A_FMULP) or
  6036. (taicpu(hp2).opcode = A_FADDP)) then
  6037. { change to
  6038. fld/fst mem1 (hp1) fld/fst mem1
  6039. fld mem1 (p) fadd/
  6040. faddp/ fmul st, st
  6041. fmulp st, st1 (hp2) }
  6042. begin
  6043. RemoveCurrentP(p, hp1);
  6044. if (taicpu(hp2).opcode = A_FADDP) then
  6045. taicpu(hp2).opcode := A_FADD
  6046. else
  6047. taicpu(hp2).opcode := A_FMUL;
  6048. taicpu(hp2).oper[1]^.reg := NR_ST;
  6049. end
  6050. else
  6051. { change to
  6052. fld/fst mem1 (hp1) fld/fst mem1
  6053. fld mem1 (p) fld st}
  6054. begin
  6055. taicpu(p).changeopsize(S_FL);
  6056. taicpu(p).loadreg(0,NR_ST);
  6057. end
  6058. else
  6059. begin
  6060. case taicpu(hp2).opcode Of
  6061. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6062. { change to
  6063. fld/fst mem1 (hp1) fld/fst mem1
  6064. fld mem2 (p) fxxx mem2
  6065. fxxxp st, st1 (hp2) }
  6066. begin
  6067. case taicpu(hp2).opcode Of
  6068. A_FADDP: taicpu(p).opcode := A_FADD;
  6069. A_FMULP: taicpu(p).opcode := A_FMUL;
  6070. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6071. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6072. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6073. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6074. else
  6075. internalerror(2019050533);
  6076. end;
  6077. RemoveInstruction(hp2);
  6078. end
  6079. else
  6080. ;
  6081. end
  6082. end
  6083. end;
  6084. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6085. begin
  6086. Result := condition_in(cond1, cond2) or
  6087. { Not strictly subsets due to the actual flags checked, but because we're
  6088. comparing integers, E is a subset of AE and GE and their aliases }
  6089. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6090. end;
  6091. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6092. var
  6093. v: TCGInt;
  6094. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6095. FirstMatch: Boolean;
  6096. NewReg: TRegister;
  6097. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6098. begin
  6099. Result:=false;
  6100. { All these optimisations need a next instruction }
  6101. if not GetNextInstruction(p, hp1) then
  6102. Exit;
  6103. { Search for:
  6104. cmp ###,###
  6105. j(c1) @lbl1
  6106. ...
  6107. @lbl:
  6108. cmp ###,### (same comparison as above)
  6109. j(c2) @lbl2
  6110. If c1 is a subset of c2, change to:
  6111. cmp ###,###
  6112. j(c1) @lbl2
  6113. (@lbl1 may become a dead label as a result)
  6114. }
  6115. { Also handle cases where there are multiple jumps in a row }
  6116. p_jump := hp1;
  6117. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6118. begin
  6119. if IsJumpToLabel(taicpu(p_jump)) then
  6120. begin
  6121. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6122. p_label := nil;
  6123. if Assigned(JumpLabel) then
  6124. p_label := getlabelwithsym(JumpLabel);
  6125. if Assigned(p_label) and
  6126. GetNextInstruction(p_label, p_dist) and
  6127. MatchInstruction(p_dist, A_CMP, []) and
  6128. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6129. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6130. GetNextInstruction(p_dist, hp1_dist) and
  6131. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6132. begin
  6133. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6134. if JumpLabel = JumpLabel_dist then
  6135. { This is an infinite loop }
  6136. Exit;
  6137. { Best optimisation when the first condition is a subset (or equal) of the second }
  6138. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6139. begin
  6140. { Any registers used here will already be allocated }
  6141. if Assigned(JumpLabel) then
  6142. JumpLabel.DecRefs;
  6143. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6144. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6145. Result := True;
  6146. { Don't exit yet. Since p and p_jump haven't actually been
  6147. removed, we can check for more on this iteration }
  6148. end
  6149. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6150. GetNextInstruction(hp1_dist, hp1_label) and
  6151. SkipAligns(hp1_label, hp1_label) and
  6152. (hp1_label.typ = ait_label) then
  6153. begin
  6154. JumpLabel_far := tai_label(hp1_label).labsym;
  6155. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6156. { This is an infinite loop }
  6157. Exit;
  6158. if Assigned(JumpLabel_far) then
  6159. begin
  6160. { In this situation, if the first jump branches, the second one will never,
  6161. branch so change the destination label to after the second jump }
  6162. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6163. if Assigned(JumpLabel) then
  6164. JumpLabel.DecRefs;
  6165. JumpLabel_far.IncRefs;
  6166. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6167. Result := True;
  6168. { Don't exit yet. Since p and p_jump haven't actually been
  6169. removed, we can check for more on this iteration }
  6170. Continue;
  6171. end;
  6172. end;
  6173. end;
  6174. end;
  6175. { Search for:
  6176. cmp ###,###
  6177. j(c1) @lbl1
  6178. cmp ###,### (same as first)
  6179. Remove second cmp
  6180. }
  6181. if GetNextInstruction(p_jump, hp2) and
  6182. (
  6183. (
  6184. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6185. (
  6186. (
  6187. MatchOpType(taicpu(p), top_const, top_reg) and
  6188. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6189. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6190. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6191. ) or (
  6192. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6193. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6194. )
  6195. )
  6196. ) or (
  6197. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6198. MatchOperand(taicpu(p).oper[0]^, 0) and
  6199. (taicpu(p).oper[1]^.typ = top_reg) and
  6200. MatchInstruction(hp2, A_TEST, []) and
  6201. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6202. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6203. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6204. )
  6205. ) then
  6206. begin
  6207. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6208. RemoveInstruction(hp2);
  6209. Result := True;
  6210. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6211. end;
  6212. GetNextInstruction(p_jump, p_jump);
  6213. end;
  6214. {
  6215. Try to optimise the following:
  6216. cmp $x,### ($x and $y can be registers or constants)
  6217. je @lbl1 (only reference)
  6218. cmp $y,### (### are identical)
  6219. @Lbl:
  6220. sete %reg1
  6221. Change to:
  6222. cmp $x,###
  6223. sete %reg2 (allocate new %reg2)
  6224. cmp $y,###
  6225. sete %reg1
  6226. orb %reg2,%reg1
  6227. (dealloc %reg2)
  6228. This adds an instruction (so don't perform under -Os), but it removes
  6229. a conditional branch.
  6230. }
  6231. if not (cs_opt_size in current_settings.optimizerswitches) and
  6232. (
  6233. (hp1 = p_jump) or
  6234. GetNextInstruction(p, hp1)
  6235. ) and
  6236. MatchInstruction(hp1, A_Jcc, []) and
  6237. IsJumpToLabel(taicpu(hp1)) and
  6238. (taicpu(hp1).condition in [C_E, C_Z]) and
  6239. GetNextInstruction(hp1, hp2) and
  6240. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6241. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6242. { The first operand of CMP instructions can only be a register or
  6243. immediate anyway, so no need to check }
  6244. GetNextInstruction(hp2, p_label) and
  6245. (
  6246. (p_label.typ = ait_label) or
  6247. (
  6248. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6249. to potentially cut down on the iterations of Pass 1 }
  6250. MatchInstruction(p_label, A_Jcc, []) and
  6251. IsJumpToLabel(taicpu(p_label)) and
  6252. { Use p_dist to hold the jump briefly }
  6253. SetAndTest(p_label, p_dist) and
  6254. GetNextInstruction(p_dist, p_label) and
  6255. (p_label.typ = ait_label) and
  6256. (tai_label(p_label).labsym.getrefs >= 2) and
  6257. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6258. { We might as well collapse the jump now }
  6259. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6260. )
  6261. ) and
  6262. (tai_label(p_label).labsym.getrefs = 1) and
  6263. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6264. GetNextInstruction(p_label, p_dist) and
  6265. MatchInstruction(p_dist, A_SETcc, []) and
  6266. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6267. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6268. { Get the instruction after the SETcc instruction so we can
  6269. allocate a new register over the entire range }
  6270. GetNextInstruction(p_dist, hp1_dist) then
  6271. begin
  6272. TransferUsedRegs(TmpUsedRegs);
  6273. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6274. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6275. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6276. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6277. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6278. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6279. begin
  6280. { Register can appear in p if it's not used afterwards, so only
  6281. allocate between hp1 and hp1_dist }
  6282. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6283. if NewReg <> NR_NO then
  6284. begin
  6285. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6286. { Change the jump instruction into a SETcc instruction }
  6287. taicpu(hp1).opcode := A_SETcc;
  6288. taicpu(hp1).opsize := S_B;
  6289. taicpu(hp1).loadreg(0, NewReg);
  6290. { This is now a dead label }
  6291. tai_label(p_label).labsym.decrefs;
  6292. { Prefer adding before the next instruction so the FLAGS
  6293. register is deallocated first }
  6294. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6295. AsmL.InsertBefore(
  6296. hp2,
  6297. hp1_dist
  6298. );
  6299. { Make sure the new register is in use over the new instruction
  6300. (long-winded, but things work best when the FLAGS register
  6301. is not allocated here) }
  6302. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6303. Result := True;
  6304. { Don't exit yet, as p wasn't changed and hp1, while
  6305. modified, is still intact and might be optimised by the
  6306. SETcc optimisation below }
  6307. end;
  6308. end;
  6309. end;
  6310. if taicpu(p).oper[0]^.typ = top_const then
  6311. begin
  6312. if (taicpu(p).oper[0]^.val = 0) and
  6313. (taicpu(p).oper[1]^.typ = top_reg) and
  6314. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6315. begin
  6316. hp2 := p;
  6317. FirstMatch := True;
  6318. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6319. anything meaningful once it's converted to "test %reg,%reg";
  6320. additionally, some jumps will always (or never) branch, so
  6321. evaluate every jump immediately following the
  6322. comparison, optimising the conditions if possible.
  6323. Similarly with SETcc... those that are always set to 0 or 1
  6324. are changed to MOV instructions }
  6325. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6326. (
  6327. GetNextInstruction(hp2, hp1) and
  6328. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6329. ) do
  6330. begin
  6331. FirstMatch := False;
  6332. case taicpu(hp1).condition of
  6333. C_B, C_C, C_NAE, C_O:
  6334. { For B/NAE:
  6335. Will never branch since an unsigned integer can never be below zero
  6336. For C/O:
  6337. Result cannot overflow because 0 is being subtracted
  6338. }
  6339. begin
  6340. if taicpu(hp1).opcode = A_Jcc then
  6341. begin
  6342. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6343. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6344. RemoveInstruction(hp1);
  6345. { Since hp1 was deleted, hp2 must not be updated }
  6346. Continue;
  6347. end
  6348. else
  6349. begin
  6350. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6351. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6352. taicpu(hp1).opcode := A_MOV;
  6353. taicpu(hp1).ops := 2;
  6354. taicpu(hp1).condition := C_None;
  6355. taicpu(hp1).opsize := S_B;
  6356. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6357. taicpu(hp1).loadconst(0, 0);
  6358. end;
  6359. end;
  6360. C_BE, C_NA:
  6361. begin
  6362. { Will only branch if equal to zero }
  6363. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6364. taicpu(hp1).condition := C_E;
  6365. end;
  6366. C_A, C_NBE:
  6367. begin
  6368. { Will only branch if not equal to zero }
  6369. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6370. taicpu(hp1).condition := C_NE;
  6371. end;
  6372. C_AE, C_NB, C_NC, C_NO:
  6373. begin
  6374. { Will always branch }
  6375. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6376. if taicpu(hp1).opcode = A_Jcc then
  6377. begin
  6378. MakeUnconditional(taicpu(hp1));
  6379. { Any jumps/set that follow will now be dead code }
  6380. RemoveDeadCodeAfterJump(taicpu(hp1));
  6381. Break;
  6382. end
  6383. else
  6384. begin
  6385. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6386. taicpu(hp1).opcode := A_MOV;
  6387. taicpu(hp1).ops := 2;
  6388. taicpu(hp1).condition := C_None;
  6389. taicpu(hp1).opsize := S_B;
  6390. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6391. taicpu(hp1).loadconst(0, 1);
  6392. end;
  6393. end;
  6394. C_None:
  6395. InternalError(2020012201);
  6396. C_P, C_PE, C_NP, C_PO:
  6397. { We can't handle parity checks and they should never be generated
  6398. after a general-purpose CMP (it's used in some floating-point
  6399. comparisons that don't use CMP) }
  6400. InternalError(2020012202);
  6401. else
  6402. { Zero/Equality, Sign, their complements and all of the
  6403. signed comparisons do not need to be converted };
  6404. end;
  6405. hp2 := hp1;
  6406. end;
  6407. { Convert the instruction to a TEST }
  6408. taicpu(p).opcode := A_TEST;
  6409. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6410. Result := True;
  6411. Exit;
  6412. end
  6413. else if (taicpu(p).oper[0]^.val = 1) and
  6414. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6415. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6416. begin
  6417. { Convert; To:
  6418. cmp $1,r/m cmp $0,r/m
  6419. jl @lbl jle @lbl
  6420. }
  6421. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6422. taicpu(p).oper[0]^.val := 0;
  6423. taicpu(hp1).condition := C_LE;
  6424. { If the instruction is now "cmp $0,%reg", convert it to a
  6425. TEST (and effectively do the work of the "cmp $0,%reg" in
  6426. the block above)
  6427. If it's a reference, we can get away with not setting
  6428. Result to True because he haven't evaluated the jump
  6429. in this pass yet.
  6430. }
  6431. if (taicpu(p).oper[1]^.typ = top_reg) then
  6432. begin
  6433. taicpu(p).opcode := A_TEST;
  6434. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6435. Result := True;
  6436. end;
  6437. Exit;
  6438. end
  6439. else if (taicpu(p).oper[1]^.typ = top_reg)
  6440. {$ifdef x86_64}
  6441. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6442. {$endif x86_64}
  6443. then
  6444. begin
  6445. { cmp register,$8000 neg register
  6446. je target --> jo target
  6447. .... only if register is deallocated before jump.}
  6448. case Taicpu(p).opsize of
  6449. S_B: v:=$80;
  6450. S_W: v:=$8000;
  6451. S_L: v:=qword($80000000);
  6452. else
  6453. internalerror(2013112905);
  6454. end;
  6455. if (taicpu(p).oper[0]^.val=v) and
  6456. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6457. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6458. begin
  6459. TransferUsedRegs(TmpUsedRegs);
  6460. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6461. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6462. begin
  6463. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6464. Taicpu(p).opcode:=A_NEG;
  6465. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6466. Taicpu(p).clearop(1);
  6467. Taicpu(p).ops:=1;
  6468. if Taicpu(hp1).condition=C_E then
  6469. Taicpu(hp1).condition:=C_O
  6470. else
  6471. Taicpu(hp1).condition:=C_NO;
  6472. Result:=true;
  6473. exit;
  6474. end;
  6475. end;
  6476. end;
  6477. end;
  6478. if TrySwapMovCmp(p, hp1) then
  6479. begin
  6480. Result := True;
  6481. Exit;
  6482. end;
  6483. end;
  6484. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6485. var
  6486. hp1: tai;
  6487. begin
  6488. {
  6489. remove the second (v)pxor from
  6490. pxor reg,reg
  6491. ...
  6492. pxor reg,reg
  6493. }
  6494. Result:=false;
  6495. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6496. MatchOpType(taicpu(p),top_reg,top_reg) and
  6497. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6498. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6499. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6500. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6501. begin
  6502. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6503. RemoveInstruction(hp1);
  6504. Result:=true;
  6505. Exit;
  6506. end
  6507. {
  6508. replace
  6509. pxor reg1,reg1
  6510. movapd/s reg1,reg2
  6511. dealloc reg1
  6512. by
  6513. pxor reg2,reg2
  6514. }
  6515. else if GetNextInstruction(p,hp1) and
  6516. { we mix single and double opperations here because we assume that the compiler
  6517. generates vmovapd only after double operations and vmovaps only after single operations }
  6518. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6519. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6520. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6521. (taicpu(p).oper[0]^.typ=top_reg) then
  6522. begin
  6523. TransferUsedRegs(TmpUsedRegs);
  6524. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6525. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6526. begin
  6527. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6528. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6529. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6530. RemoveInstruction(hp1);
  6531. result:=true;
  6532. end;
  6533. end;
  6534. end;
  6535. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6536. var
  6537. hp1: tai;
  6538. begin
  6539. {
  6540. remove the second (v)pxor from
  6541. (v)pxor reg,reg
  6542. ...
  6543. (v)pxor reg,reg
  6544. }
  6545. Result:=false;
  6546. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6547. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6548. begin
  6549. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6550. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6551. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6552. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6553. begin
  6554. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6555. RemoveInstruction(hp1);
  6556. Result:=true;
  6557. Exit;
  6558. end;
  6559. {$ifdef x86_64}
  6560. {
  6561. replace
  6562. vpxor reg1,reg1,reg1
  6563. vmov reg,mem
  6564. by
  6565. movq $0,mem
  6566. }
  6567. if GetNextInstruction(p,hp1) and
  6568. MatchInstruction(hp1,A_VMOVSD,[]) and
  6569. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6570. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6571. begin
  6572. TransferUsedRegs(TmpUsedRegs);
  6573. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6574. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6575. begin
  6576. taicpu(hp1).loadconst(0,0);
  6577. taicpu(hp1).opcode:=A_MOV;
  6578. taicpu(hp1).opsize:=S_Q;
  6579. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6580. RemoveCurrentP(p);
  6581. result:=true;
  6582. Exit;
  6583. end;
  6584. end;
  6585. {$endif x86_64}
  6586. end
  6587. {
  6588. replace
  6589. vpxor reg1,reg1,reg2
  6590. by
  6591. vpxor reg2,reg2,reg2
  6592. to avoid unncessary data dependencies
  6593. }
  6594. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6595. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6596. begin
  6597. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6598. { avoid unncessary data dependency }
  6599. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6600. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6601. result:=true;
  6602. exit;
  6603. end;
  6604. Result:=OptPass1VOP(p);
  6605. end;
  6606. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6607. var
  6608. hp1 : tai;
  6609. begin
  6610. result:=false;
  6611. { replace
  6612. IMul const,%mreg1,%mreg2
  6613. Mov %reg2,%mreg3
  6614. dealloc %mreg3
  6615. by
  6616. Imul const,%mreg1,%mreg23
  6617. }
  6618. if (taicpu(p).ops=3) and
  6619. GetNextInstruction(p,hp1) and
  6620. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6621. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6622. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6623. begin
  6624. TransferUsedRegs(TmpUsedRegs);
  6625. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6626. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6627. begin
  6628. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6629. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6630. RemoveInstruction(hp1);
  6631. result:=true;
  6632. end;
  6633. end;
  6634. end;
  6635. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6636. var
  6637. hp1 : tai;
  6638. begin
  6639. result:=false;
  6640. { replace
  6641. IMul %reg0,%reg1,%reg2
  6642. Mov %reg2,%reg3
  6643. dealloc %reg2
  6644. by
  6645. Imul %reg0,%reg1,%reg3
  6646. }
  6647. if GetNextInstruction(p,hp1) and
  6648. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6649. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6650. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6651. begin
  6652. TransferUsedRegs(TmpUsedRegs);
  6653. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6654. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6655. begin
  6656. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6657. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6658. RemoveInstruction(hp1);
  6659. result:=true;
  6660. end;
  6661. end;
  6662. end;
  6663. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6664. var
  6665. hp1: tai;
  6666. begin
  6667. Result:=false;
  6668. { get rid of
  6669. (v)cvtss2sd reg0,<reg1,>reg2
  6670. (v)cvtss2sd reg2,<reg2,>reg0
  6671. }
  6672. if GetNextInstruction(p,hp1) and
  6673. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6674. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6675. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6676. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6677. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6678. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6679. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6680. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6681. )
  6682. ) then
  6683. begin
  6684. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6685. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6686. begin
  6687. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6688. RemoveCurrentP(p);
  6689. RemoveInstruction(hp1);
  6690. end
  6691. else
  6692. begin
  6693. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6694. if taicpu(hp1).opcode=A_CVTSD2SS then
  6695. begin
  6696. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6697. taicpu(p).opcode:=A_MOVAPS;
  6698. end
  6699. else
  6700. begin
  6701. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6702. taicpu(p).opcode:=A_VMOVAPS;
  6703. end;
  6704. taicpu(p).ops:=2;
  6705. RemoveInstruction(hp1);
  6706. end;
  6707. Result:=true;
  6708. Exit;
  6709. end;
  6710. end;
  6711. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6712. var
  6713. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6714. ThisReg: TRegister;
  6715. begin
  6716. Result := False;
  6717. if not GetNextInstruction(p,hp1) then
  6718. Exit;
  6719. {
  6720. convert
  6721. j<c> .L1
  6722. mov 1,reg
  6723. jmp .L2
  6724. .L1
  6725. mov 0,reg
  6726. .L2
  6727. into
  6728. mov 0,reg
  6729. set<not(c)> reg
  6730. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6731. would destroy the flag contents
  6732. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6733. executed at the same time as a previous comparison.
  6734. set<not(c)> reg
  6735. movzx reg, reg
  6736. }
  6737. if MatchInstruction(hp1,A_MOV,[]) and
  6738. (taicpu(hp1).oper[0]^.typ = top_const) and
  6739. (
  6740. (
  6741. (taicpu(hp1).oper[1]^.typ = top_reg)
  6742. {$ifdef i386}
  6743. { Under i386, ESI, EDI, EBP and ESP
  6744. don't have an 8-bit representation }
  6745. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6746. {$endif i386}
  6747. ) or (
  6748. {$ifdef i386}
  6749. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6750. {$endif i386}
  6751. (taicpu(hp1).opsize = S_B)
  6752. )
  6753. ) and
  6754. GetNextInstruction(hp1,hp2) and
  6755. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6756. GetNextInstruction(hp2,hp3) and
  6757. SkipAligns(hp3, hp3) and
  6758. (hp3.typ=ait_label) and
  6759. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6760. GetNextInstruction(hp3,hp4) and
  6761. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6762. (taicpu(hp4).oper[0]^.typ = top_const) and
  6763. (
  6764. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6765. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6766. ) and
  6767. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6768. GetNextInstruction(hp4,hp5) and
  6769. SkipAligns(hp5, hp5) and
  6770. (hp5.typ=ait_label) and
  6771. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6772. begin
  6773. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6774. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6775. tai_label(hp3).labsym.DecRefs;
  6776. { If this isn't the only reference to the middle label, we can
  6777. still make a saving - only that the first jump and everything
  6778. that follows will remain. }
  6779. if (tai_label(hp3).labsym.getrefs = 0) then
  6780. begin
  6781. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6782. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6783. else
  6784. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6785. { remove jump, first label and second MOV (also catching any aligns) }
  6786. repeat
  6787. if not GetNextInstruction(hp2, hp3) then
  6788. InternalError(2021040810);
  6789. RemoveInstruction(hp2);
  6790. hp2 := hp3;
  6791. until hp2 = hp5;
  6792. { Don't decrement reference count before the removal loop
  6793. above, otherwise GetNextInstruction won't stop on the
  6794. the label }
  6795. tai_label(hp5).labsym.DecRefs;
  6796. end
  6797. else
  6798. begin
  6799. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6800. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6801. else
  6802. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6803. end;
  6804. taicpu(p).opcode:=A_SETcc;
  6805. taicpu(p).opsize:=S_B;
  6806. taicpu(p).is_jmp:=False;
  6807. if taicpu(hp1).opsize=S_B then
  6808. begin
  6809. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6810. if taicpu(hp1).oper[1]^.typ = top_reg then
  6811. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6812. RemoveInstruction(hp1);
  6813. end
  6814. else
  6815. begin
  6816. { Will be a register because the size can't be S_B otherwise }
  6817. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6818. taicpu(p).loadreg(0, ThisReg);
  6819. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6820. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6821. begin
  6822. case taicpu(hp1).opsize of
  6823. S_W:
  6824. taicpu(hp1).opsize := S_BW;
  6825. S_L:
  6826. taicpu(hp1).opsize := S_BL;
  6827. {$ifdef x86_64}
  6828. S_Q:
  6829. begin
  6830. taicpu(hp1).opsize := S_BL;
  6831. { Change the destination register to 32-bit }
  6832. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6833. end;
  6834. {$endif x86_64}
  6835. else
  6836. InternalError(2021040820);
  6837. end;
  6838. taicpu(hp1).opcode := A_MOVZX;
  6839. taicpu(hp1).loadreg(0, ThisReg);
  6840. end
  6841. else
  6842. begin
  6843. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6844. { hp1 is already a MOV instruction with the correct register }
  6845. taicpu(hp1).loadconst(0, 0);
  6846. { Inserting it right before p will guarantee that the flags are also tracked }
  6847. asml.Remove(hp1);
  6848. asml.InsertBefore(hp1, p);
  6849. end;
  6850. end;
  6851. Result:=true;
  6852. exit;
  6853. end
  6854. else if (hp1.typ = ait_label) then
  6855. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6856. end;
  6857. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6858. var
  6859. hp1, hp2, hp3: tai;
  6860. SourceRef, TargetRef: TReference;
  6861. CurrentReg: TRegister;
  6862. begin
  6863. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6864. if not UseAVX then
  6865. InternalError(2021100501);
  6866. Result := False;
  6867. { Look for the following to simplify:
  6868. vmovdqa/u x(mem1), %xmmreg
  6869. vmovdqa/u %xmmreg, y(mem2)
  6870. vmovdqa/u x+16(mem1), %xmmreg
  6871. vmovdqa/u %xmmreg, y+16(mem2)
  6872. Change to:
  6873. vmovdqa/u x(mem1), %ymmreg
  6874. vmovdqa/u %ymmreg, y(mem2)
  6875. vpxor %ymmreg, %ymmreg, %ymmreg
  6876. ( The VPXOR instruction is to zero the upper half, thus removing the
  6877. need to call the potentially expensive VZEROUPPER instruction. Other
  6878. peephole optimisations can remove VPXOR if it's unnecessary )
  6879. }
  6880. TransferUsedRegs(TmpUsedRegs);
  6881. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6882. { NOTE: In the optimisations below, if the references dictate that an
  6883. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6884. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6885. if (taicpu(p).opsize = S_XMM) and
  6886. MatchOpType(taicpu(p), top_ref, top_reg) and
  6887. GetNextInstruction(p, hp1) and
  6888. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6889. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6890. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6891. begin
  6892. SourceRef := taicpu(p).oper[0]^.ref^;
  6893. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6894. if GetNextInstruction(hp1, hp2) and
  6895. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6896. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6897. begin
  6898. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6899. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6900. Inc(SourceRef.offset, 16);
  6901. { Reuse the register in the first block move }
  6902. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6903. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6904. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6905. begin
  6906. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6907. Inc(TargetRef.offset, 16);
  6908. if GetNextInstruction(hp2, hp3) and
  6909. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6910. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6911. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6912. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6913. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6914. begin
  6915. { Update the register tracking to the new size }
  6916. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6917. { Remember that the offsets are 16 ahead }
  6918. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6919. if not (
  6920. ((SourceRef.offset mod 32) = 16) and
  6921. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6922. ) then
  6923. taicpu(p).opcode := A_VMOVDQU;
  6924. taicpu(p).opsize := S_YMM;
  6925. taicpu(p).oper[1]^.reg := CurrentReg;
  6926. if not (
  6927. ((TargetRef.offset mod 32) = 16) and
  6928. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6929. ) then
  6930. taicpu(hp1).opcode := A_VMOVDQU;
  6931. taicpu(hp1).opsize := S_YMM;
  6932. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6933. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6934. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6935. if (pi_uses_ymm in current_procinfo.flags) then
  6936. RemoveInstruction(hp2)
  6937. else
  6938. begin
  6939. taicpu(hp2).opcode := A_VPXOR;
  6940. taicpu(hp2).opsize := S_YMM;
  6941. taicpu(hp2).loadreg(0, CurrentReg);
  6942. taicpu(hp2).loadreg(1, CurrentReg);
  6943. taicpu(hp2).loadreg(2, CurrentReg);
  6944. taicpu(hp2).ops := 3;
  6945. end;
  6946. RemoveInstruction(hp3);
  6947. Result := True;
  6948. Exit;
  6949. end;
  6950. end
  6951. else
  6952. begin
  6953. { See if the next references are 16 less rather than 16 greater }
  6954. Dec(SourceRef.offset, 32); { -16 the other way }
  6955. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6956. begin
  6957. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6958. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6959. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6960. GetNextInstruction(hp2, hp3) and
  6961. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6962. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6963. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6964. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6965. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6966. begin
  6967. { Update the register tracking to the new size }
  6968. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6969. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6970. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6971. if not(
  6972. ((SourceRef.offset mod 32) = 0) and
  6973. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6974. ) then
  6975. taicpu(hp2).opcode := A_VMOVDQU;
  6976. taicpu(hp2).opsize := S_YMM;
  6977. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6978. if not (
  6979. ((TargetRef.offset mod 32) = 0) and
  6980. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6981. ) then
  6982. taicpu(hp3).opcode := A_VMOVDQU;
  6983. taicpu(hp3).opsize := S_YMM;
  6984. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6985. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6986. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6987. if (pi_uses_ymm in current_procinfo.flags) then
  6988. RemoveInstruction(hp1)
  6989. else
  6990. begin
  6991. taicpu(hp1).opcode := A_VPXOR;
  6992. taicpu(hp1).opsize := S_YMM;
  6993. taicpu(hp1).loadreg(0, CurrentReg);
  6994. taicpu(hp1).loadreg(1, CurrentReg);
  6995. taicpu(hp1).loadreg(2, CurrentReg);
  6996. taicpu(hp1).ops := 3;
  6997. Asml.Remove(hp1);
  6998. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6999. end;
  7000. RemoveCurrentP(p, hp2);
  7001. Result := True;
  7002. Exit;
  7003. end;
  7004. end;
  7005. end;
  7006. end;
  7007. end;
  7008. end;
  7009. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7010. var
  7011. hp2, hp3, first_assignment: tai;
  7012. IncCount, OperIdx: Integer;
  7013. OrigLabel: TAsmLabel;
  7014. begin
  7015. Count := 0;
  7016. Result := False;
  7017. first_assignment := nil;
  7018. if (LoopCount >= 20) then
  7019. begin
  7020. { Guard against infinite loops }
  7021. Exit;
  7022. end;
  7023. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7024. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7025. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7026. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7027. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7028. Exit;
  7029. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7030. {
  7031. change
  7032. jmp .L1
  7033. ...
  7034. .L1:
  7035. mov ##, ## ( multiple movs possible )
  7036. jmp/ret
  7037. into
  7038. mov ##, ##
  7039. jmp/ret
  7040. }
  7041. if not Assigned(hp1) then
  7042. begin
  7043. hp1 := GetLabelWithSym(OrigLabel);
  7044. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7045. Exit;
  7046. end;
  7047. hp2 := hp1;
  7048. while Assigned(hp2) do
  7049. begin
  7050. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7051. SkipLabels(hp2,hp2);
  7052. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7053. Break;
  7054. case taicpu(hp2).opcode of
  7055. A_MOVSS:
  7056. begin
  7057. if taicpu(hp2).ops = 0 then
  7058. { Wrong MOVSS }
  7059. Break;
  7060. Inc(Count);
  7061. if Count >= 5 then
  7062. { Too many to be worthwhile }
  7063. Break;
  7064. GetNextInstruction(hp2, hp2);
  7065. Continue;
  7066. end;
  7067. A_MOV,
  7068. A_MOVD,
  7069. A_MOVQ,
  7070. A_MOVSX,
  7071. {$ifdef x86_64}
  7072. A_MOVSXD,
  7073. {$endif x86_64}
  7074. A_MOVZX,
  7075. A_MOVAPS,
  7076. A_MOVUPS,
  7077. A_MOVSD,
  7078. A_MOVAPD,
  7079. A_MOVUPD,
  7080. A_MOVDQA,
  7081. A_MOVDQU,
  7082. A_VMOVSS,
  7083. A_VMOVAPS,
  7084. A_VMOVUPS,
  7085. A_VMOVSD,
  7086. A_VMOVAPD,
  7087. A_VMOVUPD,
  7088. A_VMOVDQA,
  7089. A_VMOVDQU:
  7090. begin
  7091. Inc(Count);
  7092. if Count >= 5 then
  7093. { Too many to be worthwhile }
  7094. Break;
  7095. GetNextInstruction(hp2, hp2);
  7096. Continue;
  7097. end;
  7098. A_JMP:
  7099. begin
  7100. { Guard against infinite loops }
  7101. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7102. Exit;
  7103. { Analyse this jump first in case it also duplicates assignments }
  7104. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7105. begin
  7106. { Something did change! }
  7107. Result := True;
  7108. Inc(Count, IncCount);
  7109. if Count >= 5 then
  7110. begin
  7111. { Too many to be worthwhile }
  7112. Exit;
  7113. end;
  7114. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7115. Break;
  7116. end;
  7117. Result := True;
  7118. Break;
  7119. end;
  7120. A_RET:
  7121. begin
  7122. Result := True;
  7123. Break;
  7124. end;
  7125. else
  7126. Break;
  7127. end;
  7128. end;
  7129. if Result then
  7130. begin
  7131. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7132. if Count = 0 then
  7133. begin
  7134. Result := False;
  7135. Exit;
  7136. end;
  7137. hp3 := p;
  7138. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7139. while True do
  7140. begin
  7141. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7142. SkipLabels(hp1,hp1);
  7143. if (hp1.typ <> ait_instruction) then
  7144. InternalError(2021040720);
  7145. case taicpu(hp1).opcode of
  7146. A_JMP:
  7147. begin
  7148. { Change the original jump to the new destination }
  7149. OrigLabel.decrefs;
  7150. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7151. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7152. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7153. if not Assigned(first_assignment) then
  7154. InternalError(2021040810)
  7155. else
  7156. p := first_assignment;
  7157. Exit;
  7158. end;
  7159. A_RET:
  7160. begin
  7161. { Now change the jump into a RET instruction }
  7162. ConvertJumpToRET(p, hp1);
  7163. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7164. if not Assigned(first_assignment) then
  7165. InternalError(2021040811)
  7166. else
  7167. p := first_assignment;
  7168. Exit;
  7169. end;
  7170. else
  7171. begin
  7172. { Duplicate the MOV instruction }
  7173. hp3:=tai(hp1.getcopy);
  7174. if first_assignment = nil then
  7175. first_assignment := hp3;
  7176. asml.InsertBefore(hp3, p);
  7177. { Make sure the compiler knows about any final registers written here }
  7178. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7179. with taicpu(hp3).oper[OperIdx]^ do
  7180. begin
  7181. case typ of
  7182. top_ref:
  7183. begin
  7184. if (ref^.base <> NR_NO) and
  7185. (getsupreg(ref^.base) <> RS_ESP) and
  7186. (getsupreg(ref^.base) <> RS_EBP)
  7187. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7188. then
  7189. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7190. if (ref^.index <> NR_NO) and
  7191. (getsupreg(ref^.index) <> RS_ESP) and
  7192. (getsupreg(ref^.index) <> RS_EBP)
  7193. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7194. (ref^.index <> ref^.base) then
  7195. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7196. end;
  7197. top_reg:
  7198. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7199. else
  7200. ;
  7201. end;
  7202. end;
  7203. end;
  7204. end;
  7205. if not GetNextInstruction(hp1, hp1) then
  7206. { Should have dropped out earlier }
  7207. InternalError(2021040710);
  7208. end;
  7209. end;
  7210. end;
  7211. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7212. var
  7213. hp2: tai;
  7214. X: Integer;
  7215. const
  7216. WriteOp: array[0..3] of set of TInsChange = (
  7217. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7218. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7219. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7220. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7221. RegWriteFlags: array[0..7] of set of TInsChange = (
  7222. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7223. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7224. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7225. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7226. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7227. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7228. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7229. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7230. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7231. begin
  7232. { If we have something like:
  7233. cmp ###,%reg1
  7234. mov 0,%reg2
  7235. And no modified registers are shared, move the instruction to before
  7236. the comparison as this means it can be optimised without worrying
  7237. about the FLAGS register. (CMP/MOV is generated by
  7238. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7239. As long as the second instruction doesn't use the flags or one of the
  7240. registers used by CMP or TEST (also check any references that use the
  7241. registers), then it can be moved prior to the comparison.
  7242. }
  7243. Result := False;
  7244. if (hp1.typ <> ait_instruction) or
  7245. taicpu(hp1).is_jmp or
  7246. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7247. Exit;
  7248. { NOP is a pipeline fence, likely marking the beginning of the function
  7249. epilogue, so drop out. Similarly, drop out if POP or RET are
  7250. encountered }
  7251. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7252. Exit;
  7253. if (taicpu(hp1).opcode = A_MOVSS) and
  7254. (taicpu(hp1).ops = 0) then
  7255. { Wrong MOVSS }
  7256. Exit;
  7257. { Check for writes to specific registers first }
  7258. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7259. for X := 0 to 7 do
  7260. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7261. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7262. Exit;
  7263. for X := 0 to taicpu(hp1).ops - 1 do
  7264. begin
  7265. { Check to see if this operand writes to something }
  7266. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7267. { And matches something in the CMP/TEST instruction }
  7268. (
  7269. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7270. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7271. (
  7272. { If it's a register, make sure the register written to doesn't
  7273. appear in the cmp instruction as part of a reference }
  7274. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7275. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7276. )
  7277. ) then
  7278. Exit;
  7279. end;
  7280. { The instruction can be safely moved }
  7281. asml.Remove(hp1);
  7282. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7283. can be optimised into "xor %reg,%reg" later }
  7284. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7285. asml.InsertBefore(hp1, hp2)
  7286. else
  7287. { Note, if p.Previous is nil (even if it should logically never be the
  7288. case), FindRegAllocBackward immediately exits with False and so we
  7289. safely land here (we can't just pass p because FindRegAllocBackward
  7290. immediately exits on an instruction). [Kit] }
  7291. asml.InsertBefore(hp1, p);
  7292. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7293. for X := 0 to taicpu(hp1).ops - 1 do
  7294. case taicpu(hp1).oper[X]^.typ of
  7295. top_reg:
  7296. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7297. top_ref:
  7298. begin
  7299. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7300. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7301. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7302. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7303. end;
  7304. else
  7305. ;
  7306. end;
  7307. if taicpu(hp1).opcode = A_LEA then
  7308. { The flags will be overwritten by the CMP/TEST instruction }
  7309. ConvertLEA(taicpu(hp1));
  7310. Result := True;
  7311. end;
  7312. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7313. function IsXCHGAcceptable: Boolean; inline;
  7314. begin
  7315. { Always accept if optimising for size }
  7316. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7317. (
  7318. {$ifdef x86_64}
  7319. { XCHG takes 3 cycles on AMD Athlon64 }
  7320. (current_settings.optimizecputype >= cpu_core_i)
  7321. {$else x86_64}
  7322. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7323. than 3, so it becomes a saving compared to three MOVs with two of
  7324. them able to execute simultaneously. [Kit] }
  7325. (current_settings.optimizecputype >= cpu_PentiumM)
  7326. {$endif x86_64}
  7327. );
  7328. end;
  7329. var
  7330. NewRef: TReference;
  7331. hp1, hp2, hp3, hp4: Tai;
  7332. {$ifndef x86_64}
  7333. OperIdx: Integer;
  7334. {$endif x86_64}
  7335. NewInstr : Taicpu;
  7336. NewAligh : Tai_align;
  7337. DestLabel: TAsmLabel;
  7338. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7339. var
  7340. NextInstr: tai;
  7341. begin
  7342. Result := False;
  7343. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7344. if not GetNextInstruction(InputInstr, NextInstr) or
  7345. (
  7346. { The FLAGS register isn't always tracked properly, so do not
  7347. perform this optimisation if a conditional statement follows }
  7348. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7349. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7350. ) then
  7351. begin
  7352. reference_reset(NewRef, 1, []);
  7353. NewRef.base := taicpu(p).oper[0]^.reg;
  7354. NewRef.scalefactor := 1;
  7355. if taicpu(InputInstr).opcode = A_ADD then
  7356. begin
  7357. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7358. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7359. end
  7360. else
  7361. begin
  7362. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7363. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7364. end;
  7365. taicpu(p).opcode := A_LEA;
  7366. taicpu(p).loadref(0, NewRef);
  7367. RemoveInstruction(InputInstr);
  7368. Result := True;
  7369. end;
  7370. end;
  7371. begin
  7372. Result:=false;
  7373. { This optimisation adds an instruction, so only do it for speed }
  7374. if not (cs_opt_size in current_settings.optimizerswitches) and
  7375. MatchOpType(taicpu(p), top_const, top_reg) and
  7376. (taicpu(p).oper[0]^.val = 0) then
  7377. begin
  7378. { To avoid compiler warning }
  7379. DestLabel := nil;
  7380. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7381. InternalError(2021040750);
  7382. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7383. Exit;
  7384. case hp1.typ of
  7385. ait_label:
  7386. begin
  7387. { Change:
  7388. mov $0,%reg mov $0,%reg
  7389. @Lbl1: @Lbl1:
  7390. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7391. je @Lbl2 jne @Lbl2
  7392. To: To:
  7393. mov $0,%reg mov $0,%reg
  7394. jmp @Lbl2 jmp @Lbl3
  7395. (align) (align)
  7396. @Lbl1: @Lbl1:
  7397. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7398. je @Lbl2 je @Lbl2
  7399. @Lbl3: <-- Only if label exists
  7400. (Not if it's optimised for size)
  7401. }
  7402. if not GetNextInstruction(hp1, hp2) then
  7403. Exit;
  7404. if not (cs_opt_size in current_settings.optimizerswitches) and
  7405. (hp2.typ = ait_instruction) and
  7406. (
  7407. { Register sizes must exactly match }
  7408. (
  7409. (taicpu(hp2).opcode = A_CMP) and
  7410. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7411. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7412. ) or (
  7413. (taicpu(hp2).opcode = A_TEST) and
  7414. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7415. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7416. )
  7417. ) and GetNextInstruction(hp2, hp3) and
  7418. (hp3.typ = ait_instruction) and
  7419. (taicpu(hp3).opcode = A_JCC) and
  7420. (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
  7421. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7422. begin
  7423. { Check condition of jump }
  7424. { Always true? }
  7425. if condition_in(C_E, taicpu(hp3).condition) then
  7426. begin
  7427. { Copy label symbol and obtain matching label entry for the
  7428. conditional jump, as this will be our destination}
  7429. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7430. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7431. Result := True;
  7432. end
  7433. { Always false? }
  7434. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7435. begin
  7436. { This is only worth it if there's a jump to take }
  7437. case hp2.typ of
  7438. ait_instruction:
  7439. begin
  7440. if taicpu(hp2).opcode = A_JMP then
  7441. begin
  7442. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7443. { An unconditional jump follows the conditional jump which will always be false,
  7444. so use this jump's destination for the new jump }
  7445. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7446. Result := True;
  7447. end
  7448. else if taicpu(hp2).opcode = A_JCC then
  7449. begin
  7450. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7451. if condition_in(C_E, taicpu(hp2).condition) then
  7452. begin
  7453. { A second conditional jump follows the conditional jump which will always be false,
  7454. while the second jump is always True, so use this jump's destination for the new jump }
  7455. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7456. Result := True;
  7457. end;
  7458. { Don't risk it if the jump isn't always true (Result remains False) }
  7459. end;
  7460. end;
  7461. else
  7462. { If anything else don't optimise };
  7463. end;
  7464. end;
  7465. if Result then
  7466. begin
  7467. { Just so we have something to insert as a paremeter}
  7468. reference_reset(NewRef, 1, []);
  7469. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7470. { Now actually load the correct parameter (this also
  7471. increases the reference count) }
  7472. NewInstr.loadsymbol(0, DestLabel, 0);
  7473. { Get instruction before original label (may not be p under -O3) }
  7474. if not GetLastInstruction(hp1, hp2) then
  7475. { Shouldn't fail here }
  7476. InternalError(2021040701);
  7477. AsmL.InsertAfter(NewInstr, hp2);
  7478. { Add new alignment field }
  7479. (* AsmL.InsertAfter(
  7480. cai_align.create_max(
  7481. current_settings.alignment.jumpalign,
  7482. current_settings.alignment.jumpalignskipmax
  7483. ),
  7484. NewInstr
  7485. ); *)
  7486. end;
  7487. Exit;
  7488. end;
  7489. end;
  7490. else
  7491. ;
  7492. end;
  7493. end;
  7494. if not GetNextInstruction(p, hp1) then
  7495. Exit;
  7496. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7497. and DoMovCmpMemOpt(p, hp1, True) then
  7498. begin
  7499. Result := True;
  7500. Exit;
  7501. end
  7502. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7503. begin
  7504. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7505. further, but we can't just put this jump optimisation in pass 1
  7506. because it tends to perform worse when conditional jumps are
  7507. nearby (e.g. when converting CMOV instructions). [Kit] }
  7508. if OptPass2JMP(hp1) then
  7509. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7510. Result := OptPass1MOV(p)
  7511. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7512. returned True and the instruction is still a MOV, thus checking
  7513. the optimisations below }
  7514. { If OptPass2JMP returned False, no optimisations were done to
  7515. the jump and there are no further optimisations that can be done
  7516. to the MOV instruction on this pass }
  7517. end
  7518. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7519. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7520. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7521. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7522. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7523. begin
  7524. { Change:
  7525. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7526. addl/q $x,%reg2 subl/q $x,%reg2
  7527. To:
  7528. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7529. }
  7530. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7531. { be lazy, checking separately for sub would be slightly better }
  7532. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7533. begin
  7534. TransferUsedRegs(TmpUsedRegs);
  7535. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7536. if TryMovArith2Lea(hp1) then
  7537. begin
  7538. Result := True;
  7539. Exit;
  7540. end
  7541. end
  7542. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7543. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7544. { Same as above, but also adds or subtracts to %reg2 in between.
  7545. It's still valid as long as the flags aren't in use }
  7546. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7547. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7548. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7549. { be lazy, checking separately for sub would be slightly better }
  7550. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7551. begin
  7552. TransferUsedRegs(TmpUsedRegs);
  7553. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7554. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7555. if TryMovArith2Lea(hp2) then
  7556. begin
  7557. Result := True;
  7558. Exit;
  7559. end;
  7560. end;
  7561. end
  7562. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7563. {$ifdef x86_64}
  7564. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7565. {$else x86_64}
  7566. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7567. {$endif x86_64}
  7568. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7569. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7570. { mov reg1, reg2 mov reg1, reg2
  7571. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7572. begin
  7573. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7574. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7575. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7576. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7577. TransferUsedRegs(TmpUsedRegs);
  7578. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7579. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7580. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7581. then
  7582. begin
  7583. RemoveCurrentP(p, hp1);
  7584. Result:=true;
  7585. end;
  7586. exit;
  7587. end
  7588. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7589. IsXCHGAcceptable and
  7590. { XCHG doesn't support 8-byte registers }
  7591. (taicpu(p).opsize <> S_B) and
  7592. MatchInstruction(hp1, A_MOV, []) and
  7593. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7594. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7595. GetNextInstruction(hp1, hp2) and
  7596. MatchInstruction(hp2, A_MOV, []) and
  7597. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7598. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7599. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7600. begin
  7601. { mov %reg1,%reg2
  7602. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7603. mov %reg2,%reg3
  7604. (%reg2 not used afterwards)
  7605. Note that xchg takes 3 cycles to execute, and generally mov's take
  7606. only one cycle apiece, but the first two mov's can be executed in
  7607. parallel, only taking 2 cycles overall. Older processors should
  7608. therefore only optimise for size. [Kit]
  7609. }
  7610. TransferUsedRegs(TmpUsedRegs);
  7611. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7612. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7613. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7614. begin
  7615. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7616. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7617. taicpu(hp1).opcode := A_XCHG;
  7618. RemoveCurrentP(p, hp1);
  7619. RemoveInstruction(hp2);
  7620. Result := True;
  7621. Exit;
  7622. end;
  7623. end
  7624. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7625. MatchInstruction(hp1, A_SAR, []) then
  7626. begin
  7627. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7628. begin
  7629. { the use of %edx also covers the opsize being S_L }
  7630. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7631. begin
  7632. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7633. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7634. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7635. begin
  7636. { Change:
  7637. movl %eax,%edx
  7638. sarl $31,%edx
  7639. To:
  7640. cltd
  7641. }
  7642. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7643. RemoveInstruction(hp1);
  7644. taicpu(p).opcode := A_CDQ;
  7645. taicpu(p).opsize := S_NO;
  7646. taicpu(p).clearop(1);
  7647. taicpu(p).clearop(0);
  7648. taicpu(p).ops:=0;
  7649. Result := True;
  7650. end
  7651. else if (cs_opt_size in current_settings.optimizerswitches) and
  7652. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7653. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7654. begin
  7655. { Change:
  7656. movl %edx,%eax
  7657. sarl $31,%edx
  7658. To:
  7659. movl %edx,%eax
  7660. cltd
  7661. Note that this creates a dependency between the two instructions,
  7662. so only perform if optimising for size.
  7663. }
  7664. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7665. taicpu(hp1).opcode := A_CDQ;
  7666. taicpu(hp1).opsize := S_NO;
  7667. taicpu(hp1).clearop(1);
  7668. taicpu(hp1).clearop(0);
  7669. taicpu(hp1).ops:=0;
  7670. end;
  7671. {$ifndef x86_64}
  7672. end
  7673. { Don't bother if CMOV is supported, because a more optimal
  7674. sequence would have been generated for the Abs() intrinsic }
  7675. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7676. { the use of %eax also covers the opsize being S_L }
  7677. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7678. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7679. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7680. GetNextInstruction(hp1, hp2) and
  7681. MatchInstruction(hp2, A_XOR, [S_L]) and
  7682. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7683. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7684. GetNextInstruction(hp2, hp3) and
  7685. MatchInstruction(hp3, A_SUB, [S_L]) and
  7686. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7687. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7688. begin
  7689. { Change:
  7690. movl %eax,%edx
  7691. sarl $31,%eax
  7692. xorl %eax,%edx
  7693. subl %eax,%edx
  7694. (Instruction that uses %edx)
  7695. (%eax deallocated)
  7696. (%edx deallocated)
  7697. To:
  7698. cltd
  7699. xorl %edx,%eax <-- Note the registers have swapped
  7700. subl %edx,%eax
  7701. (Instruction that uses %eax) <-- %eax rather than %edx
  7702. }
  7703. TransferUsedRegs(TmpUsedRegs);
  7704. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7705. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7706. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7707. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7708. begin
  7709. if GetNextInstruction(hp3, hp4) and
  7710. not RegModifiedByInstruction(NR_EDX, hp4) and
  7711. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7712. begin
  7713. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7714. taicpu(p).opcode := A_CDQ;
  7715. taicpu(p).clearop(1);
  7716. taicpu(p).clearop(0);
  7717. taicpu(p).ops:=0;
  7718. RemoveInstruction(hp1);
  7719. taicpu(hp2).loadreg(0, NR_EDX);
  7720. taicpu(hp2).loadreg(1, NR_EAX);
  7721. taicpu(hp3).loadreg(0, NR_EDX);
  7722. taicpu(hp3).loadreg(1, NR_EAX);
  7723. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7724. { Convert references in the following instruction (hp4) from %edx to %eax }
  7725. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7726. with taicpu(hp4).oper[OperIdx]^ do
  7727. case typ of
  7728. top_reg:
  7729. if getsupreg(reg) = RS_EDX then
  7730. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7731. top_ref:
  7732. begin
  7733. if getsupreg(reg) = RS_EDX then
  7734. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7735. if getsupreg(reg) = RS_EDX then
  7736. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7737. end;
  7738. else
  7739. ;
  7740. end;
  7741. end;
  7742. end;
  7743. {$else x86_64}
  7744. end;
  7745. end
  7746. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7747. { the use of %rdx also covers the opsize being S_Q }
  7748. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7749. begin
  7750. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7751. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7752. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7753. begin
  7754. { Change:
  7755. movq %rax,%rdx
  7756. sarq $63,%rdx
  7757. To:
  7758. cqto
  7759. }
  7760. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7761. RemoveInstruction(hp1);
  7762. taicpu(p).opcode := A_CQO;
  7763. taicpu(p).opsize := S_NO;
  7764. taicpu(p).clearop(1);
  7765. taicpu(p).clearop(0);
  7766. taicpu(p).ops:=0;
  7767. Result := True;
  7768. end
  7769. else if (cs_opt_size in current_settings.optimizerswitches) and
  7770. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7771. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7772. begin
  7773. { Change:
  7774. movq %rdx,%rax
  7775. sarq $63,%rdx
  7776. To:
  7777. movq %rdx,%rax
  7778. cqto
  7779. Note that this creates a dependency between the two instructions,
  7780. so only perform if optimising for size.
  7781. }
  7782. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7783. taicpu(hp1).opcode := A_CQO;
  7784. taicpu(hp1).opsize := S_NO;
  7785. taicpu(hp1).clearop(1);
  7786. taicpu(hp1).clearop(0);
  7787. taicpu(hp1).ops:=0;
  7788. {$endif x86_64}
  7789. end;
  7790. end;
  7791. end
  7792. else if MatchInstruction(hp1, A_MOV, []) and
  7793. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7794. { Though "GetNextInstruction" could be factored out, along with
  7795. the instructions that depend on hp2, it is an expensive call that
  7796. should be delayed for as long as possible, hence we do cheaper
  7797. checks first that are likely to be False. [Kit] }
  7798. begin
  7799. if (
  7800. (
  7801. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7802. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7803. (
  7804. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7805. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7806. )
  7807. ) or
  7808. (
  7809. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7810. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7811. (
  7812. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7813. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7814. )
  7815. )
  7816. ) and
  7817. GetNextInstruction(hp1, hp2) and
  7818. MatchInstruction(hp2, A_SAR, []) and
  7819. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7820. begin
  7821. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7822. begin
  7823. { Change:
  7824. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7825. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7826. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7827. To:
  7828. movl r/m,%eax <- Note the change in register
  7829. cltd
  7830. }
  7831. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7832. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7833. taicpu(p).loadreg(1, NR_EAX);
  7834. taicpu(hp1).opcode := A_CDQ;
  7835. taicpu(hp1).clearop(1);
  7836. taicpu(hp1).clearop(0);
  7837. taicpu(hp1).ops:=0;
  7838. RemoveInstruction(hp2);
  7839. (*
  7840. {$ifdef x86_64}
  7841. end
  7842. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7843. { This code sequence does not get generated - however it might become useful
  7844. if and when 128-bit signed integer types make an appearance, so the code
  7845. is kept here for when it is eventually needed. [Kit] }
  7846. (
  7847. (
  7848. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7849. (
  7850. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7851. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7852. )
  7853. ) or
  7854. (
  7855. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7856. (
  7857. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7858. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7859. )
  7860. )
  7861. ) and
  7862. GetNextInstruction(hp1, hp2) and
  7863. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7864. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7865. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7866. begin
  7867. { Change:
  7868. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7869. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7870. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7871. To:
  7872. movq r/m,%rax <- Note the change in register
  7873. cqto
  7874. }
  7875. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7876. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7877. taicpu(p).loadreg(1, NR_RAX);
  7878. taicpu(hp1).opcode := A_CQO;
  7879. taicpu(hp1).clearop(1);
  7880. taicpu(hp1).clearop(0);
  7881. taicpu(hp1).ops:=0;
  7882. RemoveInstruction(hp2);
  7883. {$endif x86_64}
  7884. *)
  7885. end;
  7886. end;
  7887. {$ifdef x86_64}
  7888. end
  7889. else if (taicpu(p).opsize = S_L) and
  7890. (taicpu(p).oper[1]^.typ = top_reg) and
  7891. (
  7892. MatchInstruction(hp1, A_MOV,[]) and
  7893. (taicpu(hp1).opsize = S_L) and
  7894. (taicpu(hp1).oper[1]^.typ = top_reg)
  7895. ) and (
  7896. GetNextInstruction(hp1, hp2) and
  7897. (tai(hp2).typ=ait_instruction) and
  7898. (taicpu(hp2).opsize = S_Q) and
  7899. (
  7900. (
  7901. MatchInstruction(hp2, A_ADD,[]) and
  7902. (taicpu(hp2).opsize = S_Q) and
  7903. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7904. (
  7905. (
  7906. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7907. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7908. ) or (
  7909. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7910. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7911. )
  7912. )
  7913. ) or (
  7914. MatchInstruction(hp2, A_LEA,[]) and
  7915. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7916. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7917. (
  7918. (
  7919. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7920. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7921. ) or (
  7922. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7923. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7924. )
  7925. ) and (
  7926. (
  7927. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7928. ) or (
  7929. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7930. )
  7931. )
  7932. )
  7933. )
  7934. ) and (
  7935. GetNextInstruction(hp2, hp3) and
  7936. MatchInstruction(hp3, A_SHR,[]) and
  7937. (taicpu(hp3).opsize = S_Q) and
  7938. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7939. (taicpu(hp3).oper[0]^.val = 1) and
  7940. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7941. ) then
  7942. begin
  7943. { Change movl x, reg1d movl x, reg1d
  7944. movl y, reg2d movl y, reg2d
  7945. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7946. shrq $1, reg1q shrq $1, reg1q
  7947. ( reg1d and reg2d can be switched around in the first two instructions )
  7948. To movl x, reg1d
  7949. addl y, reg1d
  7950. rcrl $1, reg1d
  7951. This corresponds to the common expression (x + y) shr 1, where
  7952. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7953. smaller code, but won't account for x + y causing an overflow). [Kit]
  7954. }
  7955. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7956. { Change first MOV command to have the same register as the final output }
  7957. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7958. else
  7959. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7960. { Change second MOV command to an ADD command. This is easier than
  7961. converting the existing command because it means we don't have to
  7962. touch 'y', which might be a complicated reference, and also the
  7963. fact that the third command might either be ADD or LEA. [Kit] }
  7964. taicpu(hp1).opcode := A_ADD;
  7965. { Delete old ADD/LEA instruction }
  7966. RemoveInstruction(hp2);
  7967. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7968. taicpu(hp3).opcode := A_RCR;
  7969. taicpu(hp3).changeopsize(S_L);
  7970. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7971. {$endif x86_64}
  7972. end;
  7973. end;
  7974. {$push}
  7975. {$q-}{$r-}
  7976. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7977. var
  7978. ThisReg: TRegister;
  7979. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7980. TargetSubReg: TSubRegister;
  7981. hp1, hp2: tai;
  7982. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7983. { Store list of found instructions so we don't have to call
  7984. GetNextInstructionUsingReg multiple times }
  7985. InstrList: array of taicpu;
  7986. InstrMax, Index: Integer;
  7987. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7988. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7989. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7990. WorkingValue: TCgInt;
  7991. PreMessage: string;
  7992. { Data flow analysis }
  7993. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7994. BitwiseOnly, OrXorUsed,
  7995. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7996. function CheckOverflowConditions: Boolean;
  7997. begin
  7998. Result := True;
  7999. if (TestValSignedMax > SignedUpperLimit) then
  8000. UpperSignedOverflow := True;
  8001. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8002. LowerSignedOverflow := True;
  8003. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8004. LowerUnsignedOverflow := True;
  8005. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8006. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8007. begin
  8008. { Absolute overflow }
  8009. Result := False;
  8010. Exit;
  8011. end;
  8012. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8013. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8014. ShiftDownOverflow := True;
  8015. if (TestValMin < 0) or (TestValMax < 0) then
  8016. begin
  8017. LowerUnsignedOverflow := True;
  8018. UpperUnsignedOverflow := True;
  8019. end;
  8020. end;
  8021. function AdjustInitialLoadAndSize: Boolean;
  8022. begin
  8023. Result := False;
  8024. if not p_removed then
  8025. begin
  8026. if TargetSize = MinSize then
  8027. begin
  8028. { Convert the input MOVZX to a MOV }
  8029. if (taicpu(p).oper[0]^.typ = top_reg) and
  8030. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8031. begin
  8032. { Or remove it completely! }
  8033. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8034. RemoveCurrentP(p);
  8035. p_removed := True;
  8036. end
  8037. else
  8038. begin
  8039. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8040. taicpu(p).opcode := A_MOV;
  8041. taicpu(p).oper[1]^.reg := ThisReg;
  8042. taicpu(p).opsize := TargetSize;
  8043. end;
  8044. Result := True;
  8045. end
  8046. else if TargetSize <> MaxSize then
  8047. begin
  8048. case MaxSize of
  8049. S_L:
  8050. if TargetSize = S_W then
  8051. begin
  8052. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8053. taicpu(p).opsize := S_BW;
  8054. taicpu(p).oper[1]^.reg := ThisReg;
  8055. Result := True;
  8056. end
  8057. else
  8058. InternalError(2020112341);
  8059. S_W:
  8060. if TargetSize = S_L then
  8061. begin
  8062. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8063. taicpu(p).opsize := S_BL;
  8064. taicpu(p).oper[1]^.reg := ThisReg;
  8065. Result := True;
  8066. end
  8067. else
  8068. InternalError(2020112342);
  8069. else
  8070. ;
  8071. end;
  8072. end
  8073. else if not hp1_removed and not RegInUse then
  8074. begin
  8075. { If we have something like:
  8076. movzbl (oper),%regd
  8077. add x, %regd
  8078. movzbl %regb, %regd
  8079. We can reduce the register size to the input of the final
  8080. movzbl instruction. Overflows won't have any effect.
  8081. }
  8082. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8083. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8084. begin
  8085. TargetSize := S_B;
  8086. setsubreg(ThisReg, R_SUBL);
  8087. Result := True;
  8088. end
  8089. else if (taicpu(p).opsize = S_WL) and
  8090. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8091. begin
  8092. TargetSize := S_W;
  8093. setsubreg(ThisReg, R_SUBW);
  8094. Result := True;
  8095. end;
  8096. if Result then
  8097. begin
  8098. { Convert the input MOVZX to a MOV }
  8099. if (taicpu(p).oper[0]^.typ = top_reg) and
  8100. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8101. begin
  8102. { Or remove it completely! }
  8103. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8104. RemoveCurrentP(p);
  8105. p_removed := True;
  8106. end
  8107. else
  8108. begin
  8109. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8110. taicpu(p).opcode := A_MOV;
  8111. taicpu(p).oper[1]^.reg := ThisReg;
  8112. taicpu(p).opsize := TargetSize;
  8113. end;
  8114. end;
  8115. end;
  8116. end;
  8117. end;
  8118. procedure AdjustFinalLoad;
  8119. begin
  8120. if not LowerUnsignedOverflow then
  8121. begin
  8122. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8123. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8124. begin
  8125. { Convert the output MOVZX to a MOV }
  8126. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8127. begin
  8128. { Or remove it completely! }
  8129. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8130. { Be careful; if p = hp1 and p was also removed, p
  8131. will become a dangling pointer }
  8132. if p = hp1 then
  8133. begin
  8134. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8135. p_removed := True;
  8136. end
  8137. else
  8138. RemoveInstruction(hp1);
  8139. hp1_removed := True;
  8140. end
  8141. else
  8142. begin
  8143. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8144. taicpu(hp1).opcode := A_MOV;
  8145. taicpu(hp1).oper[0]^.reg := ThisReg;
  8146. taicpu(hp1).opsize := TargetSize;
  8147. end;
  8148. end
  8149. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8150. begin
  8151. { Need to change the size of the output }
  8152. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8153. taicpu(hp1).oper[0]^.reg := ThisReg;
  8154. taicpu(hp1).opsize := S_BL;
  8155. end;
  8156. end;
  8157. end;
  8158. function CompressInstructions: Boolean;
  8159. var
  8160. LocalIndex: Integer;
  8161. begin
  8162. Result := False;
  8163. { The objective here is to try to find a combination that
  8164. removes one of the MOV/Z instructions. }
  8165. if (
  8166. (taicpu(p).oper[0]^.typ <> top_reg) or
  8167. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8168. ) and
  8169. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8170. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8171. begin
  8172. { Make a preference to remove the second MOVZX instruction }
  8173. case taicpu(hp1).opsize of
  8174. S_BL, S_WL:
  8175. begin
  8176. TargetSize := S_L;
  8177. TargetSubReg := R_SUBD;
  8178. end;
  8179. S_BW:
  8180. begin
  8181. TargetSize := S_W;
  8182. TargetSubReg := R_SUBW;
  8183. end;
  8184. else
  8185. InternalError(2020112302);
  8186. end;
  8187. end
  8188. else
  8189. begin
  8190. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8191. begin
  8192. { Exceeded lower bound but not upper bound }
  8193. TargetSize := MaxSize;
  8194. end
  8195. else if not LowerUnsignedOverflow then
  8196. begin
  8197. { Size didn't exceed lower bound }
  8198. TargetSize := MinSize;
  8199. end
  8200. else
  8201. Exit;
  8202. end;
  8203. case TargetSize of
  8204. S_B:
  8205. TargetSubReg := R_SUBL;
  8206. S_W:
  8207. TargetSubReg := R_SUBW;
  8208. S_L:
  8209. TargetSubReg := R_SUBD;
  8210. else
  8211. InternalError(2020112350);
  8212. end;
  8213. { Update the register to its new size }
  8214. setsubreg(ThisReg, TargetSubReg);
  8215. RegInUse := False;
  8216. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8217. begin
  8218. { Check to see if the active register is used afterwards;
  8219. if not, we can change it and make a saving. }
  8220. TransferUsedRegs(TmpUsedRegs);
  8221. { The target register may be marked as in use to cross
  8222. a jump to a distant label, so exclude it }
  8223. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8224. hp2 := p;
  8225. repeat
  8226. { Explicitly check for the excluded register (don't include the first
  8227. instruction as it may be reading from here }
  8228. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8229. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8230. begin
  8231. RegInUse := True;
  8232. Break;
  8233. end;
  8234. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8235. if not GetNextInstruction(hp2, hp2) then
  8236. InternalError(2020112340);
  8237. until (hp2 = hp1);
  8238. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8239. { We might still be able to get away with this }
  8240. RegInUse := not
  8241. (
  8242. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8243. (hp2.typ = ait_instruction) and
  8244. (
  8245. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8246. instruction that doesn't actually contain ThisReg }
  8247. (cs_opt_level3 in current_settings.optimizerswitches) or
  8248. RegInInstruction(ThisReg, hp2)
  8249. ) and
  8250. RegLoadedWithNewValue(ThisReg, hp2)
  8251. );
  8252. if not RegInUse then
  8253. begin
  8254. { Force the register size to the same as this instruction so it can be removed}
  8255. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8256. begin
  8257. TargetSize := S_L;
  8258. TargetSubReg := R_SUBD;
  8259. end
  8260. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8261. begin
  8262. TargetSize := S_W;
  8263. TargetSubReg := R_SUBW;
  8264. end;
  8265. ThisReg := taicpu(hp1).oper[1]^.reg;
  8266. setsubreg(ThisReg, TargetSubReg);
  8267. RegChanged := True;
  8268. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8269. TransferUsedRegs(TmpUsedRegs);
  8270. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8271. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8272. if p = hp1 then
  8273. begin
  8274. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8275. p_removed := True;
  8276. end
  8277. else
  8278. RemoveInstruction(hp1);
  8279. hp1_removed := True;
  8280. { Instruction will become "mov %reg,%reg" }
  8281. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8282. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8283. begin
  8284. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8285. RemoveCurrentP(p);
  8286. p_removed := True;
  8287. end
  8288. else
  8289. taicpu(p).oper[1]^.reg := ThisReg;
  8290. Result := True;
  8291. end
  8292. else
  8293. begin
  8294. if TargetSize <> MaxSize then
  8295. begin
  8296. { Since the register is in use, we have to force it to
  8297. MaxSize otherwise part of it may become undefined later on }
  8298. TargetSize := MaxSize;
  8299. case TargetSize of
  8300. S_B:
  8301. TargetSubReg := R_SUBL;
  8302. S_W:
  8303. TargetSubReg := R_SUBW;
  8304. S_L:
  8305. TargetSubReg := R_SUBD;
  8306. else
  8307. InternalError(2020112351);
  8308. end;
  8309. setsubreg(ThisReg, TargetSubReg);
  8310. end;
  8311. AdjustFinalLoad;
  8312. end;
  8313. end
  8314. else
  8315. AdjustFinalLoad;
  8316. Result := AdjustInitialLoadAndSize or Result;
  8317. { Now go through every instruction we found and change the
  8318. size. If TargetSize = MaxSize, then almost no changes are
  8319. needed and Result can remain False if it hasn't been set
  8320. yet.
  8321. If RegChanged is True, then the register requires changing
  8322. and so the point about TargetSize = MaxSize doesn't apply. }
  8323. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8324. begin
  8325. for LocalIndex := 0 to InstrMax do
  8326. begin
  8327. { If p_removed is true, then the original MOV/Z was removed
  8328. and removing the AND instruction may not be safe if it
  8329. appears first }
  8330. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8331. InternalError(2020112310);
  8332. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8333. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8334. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8335. InstrList[LocalIndex].opsize := TargetSize;
  8336. end;
  8337. Result := True;
  8338. end;
  8339. end;
  8340. begin
  8341. Result := False;
  8342. p_removed := False;
  8343. hp1_removed := False;
  8344. ThisReg := taicpu(p).oper[1]^.reg;
  8345. { Check for:
  8346. movs/z ###,%ecx (or %cx or %rcx)
  8347. ...
  8348. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8349. (dealloc %ecx)
  8350. Change to:
  8351. mov ###,%cl (if ### = %cl, then remove completely)
  8352. ...
  8353. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8354. }
  8355. if (getsupreg(ThisReg) = RS_ECX) and
  8356. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8357. (hp1.typ = ait_instruction) and
  8358. (
  8359. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8360. instruction that doesn't actually contain ECX }
  8361. (cs_opt_level3 in current_settings.optimizerswitches) or
  8362. RegInInstruction(NR_ECX, hp1) or
  8363. (
  8364. { It's common for the shift/rotate's read/write register to be
  8365. initialised in between, so under -O2 and under, search ahead
  8366. one more instruction
  8367. }
  8368. GetNextInstruction(hp1, hp1) and
  8369. (hp1.typ = ait_instruction) and
  8370. RegInInstruction(NR_ECX, hp1)
  8371. )
  8372. ) and
  8373. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8374. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8375. begin
  8376. TransferUsedRegs(TmpUsedRegs);
  8377. hp2 := p;
  8378. repeat
  8379. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8380. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8381. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8382. begin
  8383. case taicpu(p).opsize of
  8384. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8385. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8386. begin
  8387. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8388. RemoveCurrentP(p);
  8389. end
  8390. else
  8391. begin
  8392. taicpu(p).opcode := A_MOV;
  8393. taicpu(p).opsize := S_B;
  8394. taicpu(p).oper[1]^.reg := NR_CL;
  8395. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8396. end;
  8397. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8398. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8399. begin
  8400. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8401. RemoveCurrentP(p);
  8402. end
  8403. else
  8404. begin
  8405. taicpu(p).opcode := A_MOV;
  8406. taicpu(p).opsize := S_W;
  8407. taicpu(p).oper[1]^.reg := NR_CX;
  8408. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8409. end;
  8410. {$ifdef x86_64}
  8411. S_LQ:
  8412. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8413. begin
  8414. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8415. RemoveCurrentP(p);
  8416. end
  8417. else
  8418. begin
  8419. taicpu(p).opcode := A_MOV;
  8420. taicpu(p).opsize := S_L;
  8421. taicpu(p).oper[1]^.reg := NR_ECX;
  8422. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8423. end;
  8424. {$endif x86_64}
  8425. else
  8426. InternalError(2021120401);
  8427. end;
  8428. Result := True;
  8429. Exit;
  8430. end;
  8431. end;
  8432. { This is anything but quick! }
  8433. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8434. Exit;
  8435. SetLength(InstrList, 0);
  8436. InstrMax := -1;
  8437. case taicpu(p).opsize of
  8438. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8439. begin
  8440. {$if defined(i386) or defined(i8086)}
  8441. { If the target size is 8-bit, make sure we can actually encode it }
  8442. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8443. Exit;
  8444. {$endif i386 or i8086}
  8445. LowerLimit := $FF;
  8446. SignedLowerLimit := $7F;
  8447. SignedLowerLimitBottom := -128;
  8448. MinSize := S_B;
  8449. if taicpu(p).opsize = S_BW then
  8450. begin
  8451. MaxSize := S_W;
  8452. UpperLimit := $FFFF;
  8453. SignedUpperLimit := $7FFF;
  8454. SignedUpperLimitBottom := -32768;
  8455. end
  8456. else
  8457. begin
  8458. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8459. MaxSize := S_L;
  8460. UpperLimit := $FFFFFFFF;
  8461. SignedUpperLimit := $7FFFFFFF;
  8462. SignedUpperLimitBottom := -2147483648;
  8463. end;
  8464. end;
  8465. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8466. begin
  8467. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8468. LowerLimit := $FFFF;
  8469. SignedLowerLimit := $7FFF;
  8470. SignedLowerLimitBottom := -32768;
  8471. UpperLimit := $FFFFFFFF;
  8472. SignedUpperLimit := $7FFFFFFF;
  8473. SignedUpperLimitBottom := -2147483648;
  8474. MinSize := S_W;
  8475. MaxSize := S_L;
  8476. end;
  8477. {$ifdef x86_64}
  8478. S_LQ:
  8479. begin
  8480. { Both the lower and upper limits are set to 32-bit. If a limit
  8481. is breached, then optimisation is impossible }
  8482. LowerLimit := $FFFFFFFF;
  8483. SignedLowerLimit := $7FFFFFFF;
  8484. SignedLowerLimitBottom := -2147483648;
  8485. UpperLimit := $FFFFFFFF;
  8486. SignedUpperLimit := $7FFFFFFF;
  8487. SignedUpperLimitBottom := -2147483648;
  8488. MinSize := S_L;
  8489. MaxSize := S_L;
  8490. end;
  8491. {$endif x86_64}
  8492. else
  8493. InternalError(2020112301);
  8494. end;
  8495. TestValMin := 0;
  8496. TestValMax := LowerLimit;
  8497. TestValSignedMax := SignedLowerLimit;
  8498. TryShiftDownLimit := LowerLimit;
  8499. TryShiftDown := S_NO;
  8500. ShiftDownOverflow := False;
  8501. RegChanged := False;
  8502. BitwiseOnly := True;
  8503. OrXorUsed := False;
  8504. UpperSignedOverflow := False;
  8505. LowerSignedOverflow := False;
  8506. UpperUnsignedOverflow := False;
  8507. LowerUnsignedOverflow := False;
  8508. hp1 := p;
  8509. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8510. (hp1.typ = ait_instruction) and
  8511. (
  8512. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8513. instruction that doesn't actually contain ThisReg }
  8514. (cs_opt_level3 in current_settings.optimizerswitches) or
  8515. { This allows this Movx optimisation to work through the SETcc instructions
  8516. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8517. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8518. skip over these SETcc instructions). }
  8519. (taicpu(hp1).opcode = A_SETcc) or
  8520. RegInInstruction(ThisReg, hp1)
  8521. ) do
  8522. begin
  8523. case taicpu(hp1).opcode of
  8524. A_INC,A_DEC:
  8525. begin
  8526. { Has to be an exact match on the register }
  8527. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8528. Break;
  8529. if taicpu(hp1).opcode = A_INC then
  8530. begin
  8531. Inc(TestValMin);
  8532. Inc(TestValMax);
  8533. Inc(TestValSignedMax);
  8534. end
  8535. else
  8536. begin
  8537. Dec(TestValMin);
  8538. Dec(TestValMax);
  8539. Dec(TestValSignedMax);
  8540. end;
  8541. end;
  8542. A_TEST, A_CMP:
  8543. begin
  8544. if (
  8545. { Too high a risk of non-linear behaviour that breaks DFA
  8546. here, unless it's cmp $0,%reg, which is equivalent to
  8547. test %reg,%reg }
  8548. OrXorUsed and
  8549. (taicpu(hp1).opcode = A_CMP) and
  8550. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8551. ) or
  8552. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8553. { Has to be an exact match on the register }
  8554. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8555. (
  8556. { Permit "test %reg,%reg" }
  8557. (taicpu(hp1).opcode = A_TEST) and
  8558. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8559. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8560. ) or
  8561. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8562. { Make sure the comparison value is not smaller than the
  8563. smallest allowed signed value for the minimum size (e.g.
  8564. -128 for 8-bit) }
  8565. not (
  8566. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8567. { Is it in the negative range? }
  8568. (
  8569. (taicpu(hp1).oper[0]^.val < 0) and
  8570. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8571. )
  8572. ) then
  8573. Break;
  8574. { Check to see if the active register is used afterwards }
  8575. TransferUsedRegs(TmpUsedRegs);
  8576. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8577. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8578. begin
  8579. { Make sure the comparison or any previous instructions
  8580. hasn't pushed the test values outside of the range of
  8581. MinSize }
  8582. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8583. begin
  8584. { Exceeded lower bound but not upper bound }
  8585. Exit;
  8586. end
  8587. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8588. begin
  8589. { Size didn't exceed lower bound }
  8590. TargetSize := MinSize;
  8591. end
  8592. else
  8593. Break;
  8594. case TargetSize of
  8595. S_B:
  8596. TargetSubReg := R_SUBL;
  8597. S_W:
  8598. TargetSubReg := R_SUBW;
  8599. S_L:
  8600. TargetSubReg := R_SUBD;
  8601. else
  8602. InternalError(2021051002);
  8603. end;
  8604. if TargetSize <> MaxSize then
  8605. begin
  8606. { Update the register to its new size }
  8607. setsubreg(ThisReg, TargetSubReg);
  8608. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8609. taicpu(hp1).oper[1]^.reg := ThisReg;
  8610. taicpu(hp1).opsize := TargetSize;
  8611. { Convert the input MOVZX to a MOV if necessary }
  8612. AdjustInitialLoadAndSize;
  8613. if (InstrMax >= 0) then
  8614. begin
  8615. for Index := 0 to InstrMax do
  8616. begin
  8617. { If p_removed is true, then the original MOV/Z was removed
  8618. and removing the AND instruction may not be safe if it
  8619. appears first }
  8620. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8621. InternalError(2020112311);
  8622. if InstrList[Index].oper[0]^.typ = top_reg then
  8623. InstrList[Index].oper[0]^.reg := ThisReg;
  8624. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8625. InstrList[Index].opsize := MinSize;
  8626. end;
  8627. end;
  8628. Result := True;
  8629. end;
  8630. Exit;
  8631. end;
  8632. end;
  8633. A_SETcc:
  8634. begin
  8635. { This allows this Movx optimisation to work through the SETcc instructions
  8636. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8637. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8638. skip over these SETcc instructions). }
  8639. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8640. { Of course, break out if the current register is used }
  8641. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8642. Break
  8643. else
  8644. { We must use Continue so the instruction doesn't get added
  8645. to InstrList }
  8646. Continue;
  8647. end;
  8648. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8649. begin
  8650. if
  8651. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8652. { Has to be an exact match on the register }
  8653. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8654. (
  8655. (
  8656. (taicpu(hp1).oper[0]^.typ = top_const) and
  8657. (
  8658. (
  8659. (taicpu(hp1).opcode = A_SHL) and
  8660. (
  8661. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8662. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8663. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8664. )
  8665. ) or (
  8666. (taicpu(hp1).opcode <> A_SHL) and
  8667. (
  8668. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8669. { Is it in the negative range? }
  8670. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8671. )
  8672. )
  8673. )
  8674. ) or (
  8675. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8676. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8677. )
  8678. ) then
  8679. Break;
  8680. { Only process OR and XOR if there are only bitwise operations,
  8681. since otherwise they can too easily fool the data flow
  8682. analysis (they can cause non-linear behaviour) }
  8683. case taicpu(hp1).opcode of
  8684. A_ADD:
  8685. begin
  8686. if OrXorUsed then
  8687. { Too high a risk of non-linear behaviour that breaks DFA here }
  8688. Break
  8689. else
  8690. BitwiseOnly := False;
  8691. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8692. begin
  8693. TestValMin := TestValMin * 2;
  8694. TestValMax := TestValMax * 2;
  8695. TestValSignedMax := TestValSignedMax * 2;
  8696. end
  8697. else
  8698. begin
  8699. WorkingValue := taicpu(hp1).oper[0]^.val;
  8700. TestValMin := TestValMin + WorkingValue;
  8701. TestValMax := TestValMax + WorkingValue;
  8702. TestValSignedMax := TestValSignedMax + WorkingValue;
  8703. end;
  8704. end;
  8705. A_SUB:
  8706. begin
  8707. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8708. begin
  8709. TestValMin := 0;
  8710. TestValMax := 0;
  8711. TestValSignedMax := 0;
  8712. end
  8713. else
  8714. begin
  8715. if OrXorUsed then
  8716. { Too high a risk of non-linear behaviour that breaks DFA here }
  8717. Break
  8718. else
  8719. BitwiseOnly := False;
  8720. WorkingValue := taicpu(hp1).oper[0]^.val;
  8721. TestValMin := TestValMin - WorkingValue;
  8722. TestValMax := TestValMax - WorkingValue;
  8723. TestValSignedMax := TestValSignedMax - WorkingValue;
  8724. end;
  8725. end;
  8726. A_AND:
  8727. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8728. begin
  8729. { we might be able to go smaller if AND appears first }
  8730. if InstrMax = -1 then
  8731. case MinSize of
  8732. S_B:
  8733. ;
  8734. S_W:
  8735. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8736. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8737. begin
  8738. TryShiftDown := S_B;
  8739. TryShiftDownLimit := $FF;
  8740. end;
  8741. S_L:
  8742. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8743. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8744. begin
  8745. TryShiftDown := S_B;
  8746. TryShiftDownLimit := $FF;
  8747. end
  8748. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8749. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8750. begin
  8751. TryShiftDown := S_W;
  8752. TryShiftDownLimit := $FFFF;
  8753. end;
  8754. else
  8755. InternalError(2020112320);
  8756. end;
  8757. WorkingValue := taicpu(hp1).oper[0]^.val;
  8758. TestValMin := TestValMin and WorkingValue;
  8759. TestValMax := TestValMax and WorkingValue;
  8760. TestValSignedMax := TestValSignedMax and WorkingValue;
  8761. end;
  8762. A_OR:
  8763. begin
  8764. if not BitwiseOnly then
  8765. Break;
  8766. OrXorUsed := True;
  8767. WorkingValue := taicpu(hp1).oper[0]^.val;
  8768. TestValMin := TestValMin or WorkingValue;
  8769. TestValMax := TestValMax or WorkingValue;
  8770. TestValSignedMax := TestValSignedMax or WorkingValue;
  8771. end;
  8772. A_XOR:
  8773. begin
  8774. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8775. begin
  8776. TestValMin := 0;
  8777. TestValMax := 0;
  8778. TestValSignedMax := 0;
  8779. end
  8780. else
  8781. begin
  8782. if not BitwiseOnly then
  8783. Break;
  8784. OrXorUsed := True;
  8785. WorkingValue := taicpu(hp1).oper[0]^.val;
  8786. TestValMin := TestValMin xor WorkingValue;
  8787. TestValMax := TestValMax xor WorkingValue;
  8788. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8789. end;
  8790. end;
  8791. A_SHL:
  8792. begin
  8793. BitwiseOnly := False;
  8794. WorkingValue := taicpu(hp1).oper[0]^.val;
  8795. TestValMin := TestValMin shl WorkingValue;
  8796. TestValMax := TestValMax shl WorkingValue;
  8797. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8798. end;
  8799. A_SHR,
  8800. { The first instruction was MOVZX, so the value won't be negative }
  8801. A_SAR:
  8802. begin
  8803. if InstrMax <> -1 then
  8804. BitwiseOnly := False
  8805. else
  8806. { we might be able to go smaller if SHR appears first }
  8807. case MinSize of
  8808. S_B:
  8809. ;
  8810. S_W:
  8811. if (taicpu(hp1).oper[0]^.val >= 8) then
  8812. begin
  8813. TryShiftDown := S_B;
  8814. TryShiftDownLimit := $FF;
  8815. TryShiftDownSignedLimit := $7F;
  8816. TryShiftDownSignedLimitLower := -128;
  8817. end;
  8818. S_L:
  8819. if (taicpu(hp1).oper[0]^.val >= 24) then
  8820. begin
  8821. TryShiftDown := S_B;
  8822. TryShiftDownLimit := $FF;
  8823. TryShiftDownSignedLimit := $7F;
  8824. TryShiftDownSignedLimitLower := -128;
  8825. end
  8826. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8827. begin
  8828. TryShiftDown := S_W;
  8829. TryShiftDownLimit := $FFFF;
  8830. TryShiftDownSignedLimit := $7FFF;
  8831. TryShiftDownSignedLimitLower := -32768;
  8832. end;
  8833. else
  8834. InternalError(2020112321);
  8835. end;
  8836. WorkingValue := taicpu(hp1).oper[0]^.val;
  8837. if taicpu(hp1).opcode = A_SAR then
  8838. begin
  8839. TestValMin := SarInt64(TestValMin, WorkingValue);
  8840. TestValMax := SarInt64(TestValMax, WorkingValue);
  8841. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8842. end
  8843. else
  8844. begin
  8845. TestValMin := TestValMin shr WorkingValue;
  8846. TestValMax := TestValMax shr WorkingValue;
  8847. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8848. end;
  8849. end;
  8850. else
  8851. InternalError(2020112303);
  8852. end;
  8853. end;
  8854. (*
  8855. A_IMUL:
  8856. case taicpu(hp1).ops of
  8857. 2:
  8858. begin
  8859. if not MatchOpType(hp1, top_reg, top_reg) or
  8860. { Has to be an exact match on the register }
  8861. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8862. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8863. Break;
  8864. TestValMin := TestValMin * TestValMin;
  8865. TestValMax := TestValMax * TestValMax;
  8866. TestValSignedMax := TestValSignedMax * TestValMax;
  8867. end;
  8868. 3:
  8869. begin
  8870. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8871. { Has to be an exact match on the register }
  8872. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8873. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8874. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8875. { Is it in the negative range? }
  8876. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8877. Break;
  8878. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8879. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8880. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8881. end;
  8882. else
  8883. Break;
  8884. end;
  8885. A_IDIV:
  8886. case taicpu(hp1).ops of
  8887. 3:
  8888. begin
  8889. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8890. { Has to be an exact match on the register }
  8891. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8892. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8893. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8894. { Is it in the negative range? }
  8895. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8896. Break;
  8897. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8898. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8899. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8900. end;
  8901. else
  8902. Break;
  8903. end;
  8904. *)
  8905. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8906. begin
  8907. { If there are no instructions in between, then we might be able to make a saving }
  8908. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8909. Break;
  8910. { We have something like:
  8911. movzbw %dl,%dx
  8912. ...
  8913. movswl %dx,%edx
  8914. Change the latter to a zero-extension then enter the
  8915. A_MOVZX case branch.
  8916. }
  8917. {$ifdef x86_64}
  8918. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8919. begin
  8920. { this becomes a zero extension from 32-bit to 64-bit, but
  8921. the upper 32 bits are already zero, so just delete the
  8922. instruction }
  8923. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8924. RemoveInstruction(hp1);
  8925. Result := True;
  8926. Exit;
  8927. end
  8928. else
  8929. {$endif x86_64}
  8930. begin
  8931. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8932. taicpu(hp1).opcode := A_MOVZX;
  8933. {$ifdef x86_64}
  8934. case taicpu(hp1).opsize of
  8935. S_BQ:
  8936. begin
  8937. taicpu(hp1).opsize := S_BL;
  8938. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8939. end;
  8940. S_WQ:
  8941. begin
  8942. taicpu(hp1).opsize := S_WL;
  8943. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8944. end;
  8945. S_LQ:
  8946. begin
  8947. taicpu(hp1).opcode := A_MOV;
  8948. taicpu(hp1).opsize := S_L;
  8949. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8950. { In this instance, we need to break out because the
  8951. instruction is no longer MOVZX or MOVSXD }
  8952. Result := True;
  8953. Exit;
  8954. end;
  8955. else
  8956. ;
  8957. end;
  8958. {$endif x86_64}
  8959. Result := CompressInstructions;
  8960. Exit;
  8961. end;
  8962. end;
  8963. A_MOVZX:
  8964. begin
  8965. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8966. Break;
  8967. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8968. begin
  8969. if (InstrMax = -1) and
  8970. { Will return false if the second parameter isn't ThisReg
  8971. (can happen on -O2 and under) }
  8972. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8973. begin
  8974. { The two MOVZX instructions are adjacent, so remove the first one }
  8975. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8976. RemoveCurrentP(p);
  8977. Result := True;
  8978. Exit;
  8979. end;
  8980. Break;
  8981. end;
  8982. Result := CompressInstructions;
  8983. Exit;
  8984. end;
  8985. else
  8986. { This includes ADC, SBB and IDIV }
  8987. Break;
  8988. end;
  8989. if not CheckOverflowConditions then
  8990. Break;
  8991. { Contains highest index (so instruction count - 1) }
  8992. Inc(InstrMax);
  8993. if InstrMax > High(InstrList) then
  8994. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8995. InstrList[InstrMax] := taicpu(hp1);
  8996. end;
  8997. end;
  8998. {$pop}
  8999. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9000. var
  9001. hp1 : tai;
  9002. begin
  9003. Result:=false;
  9004. if (taicpu(p).ops >= 2) and
  9005. ((taicpu(p).oper[0]^.typ = top_const) or
  9006. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9007. (taicpu(p).oper[1]^.typ = top_reg) and
  9008. ((taicpu(p).ops = 2) or
  9009. ((taicpu(p).oper[2]^.typ = top_reg) and
  9010. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9011. GetLastInstruction(p,hp1) and
  9012. MatchInstruction(hp1,A_MOV,[]) and
  9013. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9014. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9015. begin
  9016. TransferUsedRegs(TmpUsedRegs);
  9017. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9018. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9019. { change
  9020. mov reg1,reg2
  9021. imul y,reg2 to imul y,reg1,reg2 }
  9022. begin
  9023. taicpu(p).ops := 3;
  9024. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9025. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9026. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9027. RemoveInstruction(hp1);
  9028. result:=true;
  9029. end;
  9030. end;
  9031. end;
  9032. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9033. var
  9034. ThisLabel: TAsmLabel;
  9035. begin
  9036. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9037. ThisLabel.decrefs;
  9038. taicpu(p).opcode := A_RET;
  9039. taicpu(p).is_jmp := false;
  9040. taicpu(p).ops := taicpu(ret_p).ops;
  9041. case taicpu(ret_p).ops of
  9042. 0:
  9043. taicpu(p).clearop(0);
  9044. 1:
  9045. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9046. else
  9047. internalerror(2016041301);
  9048. end;
  9049. { If the original label is now dead, it might turn out that the label
  9050. immediately follows p. As a result, everything beyond it, which will
  9051. be just some final register configuration and a RET instruction, is
  9052. now dead code. [Kit] }
  9053. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9054. running RemoveDeadCodeAfterJump for each RET instruction, because
  9055. this optimisation rarely happens and most RETs appear at the end of
  9056. routines where there is nothing that can be stripped. [Kit] }
  9057. if not ThisLabel.is_used then
  9058. RemoveDeadCodeAfterJump(p);
  9059. end;
  9060. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9061. var
  9062. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9063. Unconditional, PotentialModified: Boolean;
  9064. OperPtr: POper;
  9065. NewRef: TReference;
  9066. InstrList: array of taicpu;
  9067. InstrMax, Index: Integer;
  9068. const
  9069. {$ifdef DEBUG_AOPTCPU}
  9070. SNoFlags: shortstring = ' so the flags aren''t modified';
  9071. {$else DEBUG_AOPTCPU}
  9072. SNoFlags = '';
  9073. {$endif DEBUG_AOPTCPU}
  9074. begin
  9075. Result:=false;
  9076. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9077. begin
  9078. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9079. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9080. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9081. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9082. GetNextInstruction(hp1, hp2) and
  9083. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9084. { Change from: To:
  9085. set(C) %reg j(~C) label
  9086. test %reg,%reg/cmp $0,%reg
  9087. je label
  9088. set(C) %reg j(C) label
  9089. test %reg,%reg/cmp $0,%reg
  9090. jne label
  9091. (Also do something similar with sete/setne instead of je/jne)
  9092. }
  9093. begin
  9094. { Before we do anything else, we need to check the instructions
  9095. in between SETcc and TEST to make sure they don't modify the
  9096. FLAGS register - if -O2 or under, there won't be any
  9097. instructions between SET and TEST }
  9098. TransferUsedRegs(TmpUsedRegs);
  9099. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9100. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9101. begin
  9102. next := p;
  9103. SetLength(InstrList, 0);
  9104. InstrMax := -1;
  9105. PotentialModified := False;
  9106. { Make a note of every instruction that modifies the FLAGS
  9107. register }
  9108. while GetNextInstruction(next, next) and (next <> hp1) do
  9109. begin
  9110. if next.typ <> ait_instruction then
  9111. { GetNextInstructionUsingReg should have returned False }
  9112. InternalError(2021051701);
  9113. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9114. begin
  9115. case taicpu(next).opcode of
  9116. A_SETcc,
  9117. A_CMOVcc,
  9118. A_Jcc:
  9119. begin
  9120. if PotentialModified then
  9121. { Not safe because the flags were modified earlier }
  9122. Exit
  9123. else
  9124. { Condition is the same as the initial SETcc, so this is safe
  9125. (don't add to instruction list though) }
  9126. Continue;
  9127. end;
  9128. A_ADD:
  9129. begin
  9130. if (taicpu(next).opsize = S_B) or
  9131. { LEA doesn't support 8-bit operands }
  9132. (taicpu(next).oper[1]^.typ <> top_reg) or
  9133. { Must write to a register }
  9134. (taicpu(next).oper[0]^.typ = top_ref) then
  9135. { Require a constant or a register }
  9136. Exit;
  9137. PotentialModified := True;
  9138. end;
  9139. A_SUB:
  9140. begin
  9141. if (taicpu(next).opsize = S_B) or
  9142. { LEA doesn't support 8-bit operands }
  9143. (taicpu(next).oper[1]^.typ <> top_reg) or
  9144. { Must write to a register }
  9145. (taicpu(next).oper[0]^.typ <> top_const) or
  9146. (taicpu(next).oper[0]^.val = $80000000) then
  9147. { Can't subtract a register with LEA - also
  9148. check that the value isn't -2^31, as this
  9149. can't be negated }
  9150. Exit;
  9151. PotentialModified := True;
  9152. end;
  9153. A_SAL,
  9154. A_SHL:
  9155. begin
  9156. if (taicpu(next).opsize = S_B) or
  9157. { LEA doesn't support 8-bit operands }
  9158. (taicpu(next).oper[1]^.typ <> top_reg) or
  9159. { Must write to a register }
  9160. (taicpu(next).oper[0]^.typ <> top_const) or
  9161. (taicpu(next).oper[0]^.val < 0) or
  9162. (taicpu(next).oper[0]^.val > 3) then
  9163. Exit;
  9164. PotentialModified := True;
  9165. end;
  9166. A_IMUL:
  9167. begin
  9168. if (taicpu(next).ops <> 3) or
  9169. (taicpu(next).oper[1]^.typ <> top_reg) or
  9170. { Must write to a register }
  9171. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9172. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9173. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9174. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9175. Exit
  9176. else
  9177. PotentialModified := True;
  9178. end;
  9179. else
  9180. { Don't know how to change this, so abort }
  9181. Exit;
  9182. end;
  9183. { Contains highest index (so instruction count - 1) }
  9184. Inc(InstrMax);
  9185. if InstrMax > High(InstrList) then
  9186. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9187. InstrList[InstrMax] := taicpu(next);
  9188. end;
  9189. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9190. end;
  9191. if not Assigned(next) or (next <> hp1) then
  9192. { It should be equal to hp1 }
  9193. InternalError(2021051702);
  9194. { Cycle through each instruction and check to see if we can
  9195. change them to versions that don't modify the flags }
  9196. if (InstrMax >= 0) then
  9197. begin
  9198. for Index := 0 to InstrMax do
  9199. case InstrList[Index].opcode of
  9200. A_ADD:
  9201. begin
  9202. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9203. InstrList[Index].opcode := A_LEA;
  9204. reference_reset(NewRef, 1, []);
  9205. NewRef.base := InstrList[Index].oper[1]^.reg;
  9206. if InstrList[Index].oper[0]^.typ = top_reg then
  9207. begin
  9208. NewRef.index := InstrList[Index].oper[0]^.reg;
  9209. NewRef.scalefactor := 1;
  9210. end
  9211. else
  9212. NewRef.offset := InstrList[Index].oper[0]^.val;
  9213. InstrList[Index].loadref(0, NewRef);
  9214. end;
  9215. A_SUB:
  9216. begin
  9217. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9218. InstrList[Index].opcode := A_LEA;
  9219. reference_reset(NewRef, 1, []);
  9220. NewRef.base := InstrList[Index].oper[1]^.reg;
  9221. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9222. InstrList[Index].loadref(0, NewRef);
  9223. end;
  9224. A_SHL,
  9225. A_SAL:
  9226. begin
  9227. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9228. InstrList[Index].opcode := A_LEA;
  9229. reference_reset(NewRef, 1, []);
  9230. NewRef.index := InstrList[Index].oper[1]^.reg;
  9231. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9232. InstrList[Index].loadref(0, NewRef);
  9233. end;
  9234. A_IMUL:
  9235. begin
  9236. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9237. InstrList[Index].opcode := A_LEA;
  9238. reference_reset(NewRef, 1, []);
  9239. NewRef.index := InstrList[Index].oper[1]^.reg;
  9240. case InstrList[Index].oper[0]^.val of
  9241. 2, 4, 8:
  9242. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9243. else {3, 5 and 9}
  9244. begin
  9245. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9246. NewRef.base := InstrList[Index].oper[1]^.reg;
  9247. end;
  9248. end;
  9249. InstrList[Index].loadref(0, NewRef);
  9250. end;
  9251. else
  9252. InternalError(2021051710);
  9253. end;
  9254. end;
  9255. { Mark the FLAGS register as used across this whole block }
  9256. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9257. end;
  9258. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9259. JumpC := taicpu(hp2).condition;
  9260. Unconditional := False;
  9261. if conditions_equal(JumpC, C_E) then
  9262. SetC := inverse_cond(taicpu(p).condition)
  9263. else if conditions_equal(JumpC, C_NE) then
  9264. SetC := taicpu(p).condition
  9265. else
  9266. { We've got something weird here (and inefficent) }
  9267. begin
  9268. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9269. SetC := C_NONE;
  9270. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9271. if condition_in(C_AE, JumpC) then
  9272. Unconditional := True
  9273. else
  9274. { Not sure what to do with this jump - drop out }
  9275. Exit;
  9276. end;
  9277. RemoveInstruction(hp1);
  9278. if Unconditional then
  9279. MakeUnconditional(taicpu(hp2))
  9280. else
  9281. begin
  9282. if SetC = C_NONE then
  9283. InternalError(2018061402);
  9284. taicpu(hp2).SetCondition(SetC);
  9285. end;
  9286. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9287. TmpUsedRegs }
  9288. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9289. begin
  9290. RemoveCurrentp(p, hp2);
  9291. if taicpu(hp2).opcode = A_SETcc then
  9292. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9293. else
  9294. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9295. end
  9296. else
  9297. if taicpu(hp2).opcode = A_SETcc then
  9298. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9299. else
  9300. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9301. Result := True;
  9302. end
  9303. else if
  9304. { Make sure the instructions are adjacent }
  9305. (
  9306. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9307. GetNextInstruction(p, hp1)
  9308. ) and
  9309. MatchInstruction(hp1, A_MOV, [S_B]) and
  9310. { Writing to memory is allowed }
  9311. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9312. begin
  9313. {
  9314. Watch out for sequences such as:
  9315. set(c)b %regb
  9316. movb %regb,(ref)
  9317. movb $0,1(ref)
  9318. movb $0,2(ref)
  9319. movb $0,3(ref)
  9320. Much more efficient to turn it into:
  9321. movl $0,%regl
  9322. set(c)b %regb
  9323. movl %regl,(ref)
  9324. Or:
  9325. set(c)b %regb
  9326. movzbl %regb,%regl
  9327. movl %regl,(ref)
  9328. }
  9329. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9330. GetNextInstruction(hp1, hp2) and
  9331. MatchInstruction(hp2, A_MOV, [S_B]) and
  9332. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9333. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9334. begin
  9335. { Don't do anything else except set Result to True }
  9336. end
  9337. else
  9338. begin
  9339. if taicpu(p).oper[0]^.typ = top_reg then
  9340. begin
  9341. TransferUsedRegs(TmpUsedRegs);
  9342. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9343. end;
  9344. { If it's not a register, it's a memory address }
  9345. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9346. begin
  9347. { Even if the register is still in use, we can minimise the
  9348. pipeline stall by changing the MOV into another SETcc. }
  9349. taicpu(hp1).opcode := A_SETcc;
  9350. taicpu(hp1).condition := taicpu(p).condition;
  9351. if taicpu(hp1).oper[1]^.typ = top_ref then
  9352. begin
  9353. { Swapping the operand pointers like this is probably a
  9354. bit naughty, but it is far faster than using loadoper
  9355. to transfer the reference from oper[1] to oper[0] if
  9356. you take into account the extra procedure calls and
  9357. the memory allocation and deallocation required }
  9358. OperPtr := taicpu(hp1).oper[1];
  9359. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9360. taicpu(hp1).oper[0] := OperPtr;
  9361. end
  9362. else
  9363. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9364. taicpu(hp1).clearop(1);
  9365. taicpu(hp1).ops := 1;
  9366. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9367. end
  9368. else
  9369. begin
  9370. if taicpu(hp1).oper[1]^.typ = top_reg then
  9371. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9372. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9373. RemoveInstruction(hp1);
  9374. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9375. end
  9376. end;
  9377. Result := True;
  9378. end;
  9379. end;
  9380. end;
  9381. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9382. var
  9383. hp1: tai;
  9384. Count: Integer;
  9385. OrigLabel: TAsmLabel;
  9386. begin
  9387. result := False;
  9388. { Sometimes, the optimisations below can permit this }
  9389. RemoveDeadCodeAfterJump(p);
  9390. 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
  9391. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9392. begin
  9393. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9394. { Also a side-effect of optimisations }
  9395. if CollapseZeroDistJump(p, OrigLabel) then
  9396. begin
  9397. Result := True;
  9398. Exit;
  9399. end;
  9400. hp1 := GetLabelWithSym(OrigLabel);
  9401. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9402. begin
  9403. if taicpu(hp1).opcode = A_RET then
  9404. begin
  9405. {
  9406. change
  9407. jmp .L1
  9408. ...
  9409. .L1:
  9410. ret
  9411. into
  9412. ret
  9413. }
  9414. begin
  9415. ConvertJumpToRET(p, hp1);
  9416. result:=true;
  9417. end;
  9418. end
  9419. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9420. not (cs_opt_size in current_settings.optimizerswitches) and
  9421. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9422. begin
  9423. Result := True;
  9424. Exit;
  9425. end;
  9426. end;
  9427. end;
  9428. end;
  9429. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9430. begin
  9431. CanBeCMOV:=assigned(p) and
  9432. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9433. { we can't use cmov ref,reg because
  9434. ref could be nil and cmov still throws an exception
  9435. if ref=nil but the mov isn't done (FK)
  9436. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9437. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9438. }
  9439. (taicpu(p).oper[1]^.typ = top_reg) and
  9440. (
  9441. (taicpu(p).oper[0]^.typ = top_reg) or
  9442. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9443. it is not expected that this can cause a seg. violation }
  9444. (
  9445. (taicpu(p).oper[0]^.typ = top_ref) and
  9446. IsRefSafe(taicpu(p).oper[0]^.ref)
  9447. )
  9448. );
  9449. end;
  9450. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9451. var
  9452. hp1,hp2: tai;
  9453. {$ifndef i8086}
  9454. hp3,hp4,hpmov2, hp5: tai;
  9455. l : Longint;
  9456. condition : TAsmCond;
  9457. {$endif i8086}
  9458. carryadd_opcode : TAsmOp;
  9459. symbol: TAsmSymbol;
  9460. increg, tmpreg: TRegister;
  9461. begin
  9462. result:=false;
  9463. if GetNextInstruction(p,hp1) then
  9464. begin
  9465. if (hp1.typ=ait_label) then
  9466. begin
  9467. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9468. Exit;
  9469. end
  9470. else if (hp1.typ<>ait_instruction) then
  9471. Exit;
  9472. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9473. if (
  9474. (
  9475. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9476. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9477. (Taicpu(hp1).oper[0]^.val=1)
  9478. ) or
  9479. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9480. ) and
  9481. GetNextInstruction(hp1,hp2) and
  9482. SkipAligns(hp2, hp2) and
  9483. (hp2.typ = ait_label) and
  9484. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9485. { jb @@1 cmc
  9486. inc/dec operand --> adc/sbb operand,0
  9487. @@1:
  9488. ... and ...
  9489. jnb @@1
  9490. inc/dec operand --> adc/sbb operand,0
  9491. @@1: }
  9492. begin
  9493. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9494. begin
  9495. case taicpu(hp1).opcode of
  9496. A_INC,
  9497. A_ADD:
  9498. carryadd_opcode:=A_ADC;
  9499. A_DEC,
  9500. A_SUB:
  9501. carryadd_opcode:=A_SBB;
  9502. else
  9503. InternalError(2021011001);
  9504. end;
  9505. Taicpu(p).clearop(0);
  9506. Taicpu(p).ops:=0;
  9507. Taicpu(p).is_jmp:=false;
  9508. Taicpu(p).opcode:=A_CMC;
  9509. Taicpu(p).condition:=C_NONE;
  9510. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9511. Taicpu(hp1).ops:=2;
  9512. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9513. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9514. else
  9515. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9516. Taicpu(hp1).loadconst(0,0);
  9517. Taicpu(hp1).opcode:=carryadd_opcode;
  9518. result:=true;
  9519. exit;
  9520. end
  9521. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9522. begin
  9523. case taicpu(hp1).opcode of
  9524. A_INC,
  9525. A_ADD:
  9526. carryadd_opcode:=A_ADC;
  9527. A_DEC,
  9528. A_SUB:
  9529. carryadd_opcode:=A_SBB;
  9530. else
  9531. InternalError(2021011002);
  9532. end;
  9533. Taicpu(hp1).ops:=2;
  9534. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9535. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9536. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9537. else
  9538. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9539. Taicpu(hp1).loadconst(0,0);
  9540. Taicpu(hp1).opcode:=carryadd_opcode;
  9541. RemoveCurrentP(p, hp1);
  9542. result:=true;
  9543. exit;
  9544. end
  9545. {
  9546. jcc @@1 setcc tmpreg
  9547. inc/dec/add/sub operand -> (movzx tmpreg)
  9548. @@1: add/sub tmpreg,operand
  9549. While this increases code size slightly, it makes the code much faster if the
  9550. jump is unpredictable
  9551. }
  9552. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9553. begin
  9554. { search for an available register which is volatile }
  9555. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9556. if increg <> NR_NO then
  9557. begin
  9558. { We don't need to check if tmpreg is in hp1 or not, because
  9559. it will be marked as in use at p (if not, this is
  9560. indictive of a compiler bug). }
  9561. TAsmLabel(symbol).decrefs;
  9562. Taicpu(p).clearop(0);
  9563. Taicpu(p).ops:=1;
  9564. Taicpu(p).is_jmp:=false;
  9565. Taicpu(p).opcode:=A_SETcc;
  9566. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9567. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9568. Taicpu(p).loadreg(0,increg);
  9569. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9570. begin
  9571. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9572. R_SUBW:
  9573. begin
  9574. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9575. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9576. end;
  9577. R_SUBD:
  9578. begin
  9579. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9580. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9581. end;
  9582. {$ifdef x86_64}
  9583. R_SUBQ:
  9584. begin
  9585. { MOVZX doesn't have a 64-bit variant, because
  9586. the 32-bit version implicitly zeroes the
  9587. upper 32-bits of the destination register }
  9588. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9589. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9590. setsubreg(tmpreg, R_SUBQ);
  9591. end;
  9592. {$endif x86_64}
  9593. else
  9594. Internalerror(2020030601);
  9595. end;
  9596. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9597. asml.InsertAfter(hp2,p);
  9598. end
  9599. else
  9600. tmpreg := increg;
  9601. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9602. begin
  9603. Taicpu(hp1).ops:=2;
  9604. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9605. end;
  9606. Taicpu(hp1).loadreg(0,tmpreg);
  9607. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9608. Result := True;
  9609. { p is no longer a Jcc instruction, so exit }
  9610. Exit;
  9611. end;
  9612. end;
  9613. end;
  9614. { Detect the following:
  9615. jmp<cond> @Lbl1
  9616. jmp @Lbl2
  9617. ...
  9618. @Lbl1:
  9619. ret
  9620. Change to:
  9621. jmp<inv_cond> @Lbl2
  9622. ret
  9623. }
  9624. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9625. begin
  9626. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9627. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9628. MatchInstruction(hp2,A_RET,[S_NO]) then
  9629. begin
  9630. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9631. { Change label address to that of the unconditional jump }
  9632. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9633. TAsmLabel(symbol).DecRefs;
  9634. taicpu(hp1).opcode := A_RET;
  9635. taicpu(hp1).is_jmp := false;
  9636. taicpu(hp1).ops := taicpu(hp2).ops;
  9637. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9638. case taicpu(hp2).ops of
  9639. 0:
  9640. taicpu(hp1).clearop(0);
  9641. 1:
  9642. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9643. else
  9644. internalerror(2016041302);
  9645. end;
  9646. end;
  9647. {$ifndef i8086}
  9648. end
  9649. {
  9650. convert
  9651. j<c> .L1
  9652. mov 1,reg
  9653. jmp .L2
  9654. .L1
  9655. mov 0,reg
  9656. .L2
  9657. into
  9658. mov 0,reg
  9659. set<not(c)> reg
  9660. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9661. would destroy the flag contents
  9662. }
  9663. else if MatchInstruction(hp1,A_MOV,[]) and
  9664. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9665. {$ifdef i386}
  9666. (
  9667. { Under i386, ESI, EDI, EBP and ESP
  9668. don't have an 8-bit representation }
  9669. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9670. ) and
  9671. {$endif i386}
  9672. (taicpu(hp1).oper[0]^.val=1) and
  9673. GetNextInstruction(hp1,hp2) and
  9674. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9675. GetNextInstruction(hp2,hp3) and
  9676. { skip align }
  9677. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9678. (hp3.typ=ait_label) and
  9679. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9680. (tai_label(hp3).labsym.getrefs=1) and
  9681. GetNextInstruction(hp3,hp4) and
  9682. MatchInstruction(hp4,A_MOV,[]) and
  9683. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9684. (taicpu(hp4).oper[0]^.val=0) and
  9685. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9686. GetNextInstruction(hp4,hp5) and
  9687. (hp5.typ=ait_label) and
  9688. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9689. (tai_label(hp5).labsym.getrefs=1) then
  9690. begin
  9691. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9692. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9693. { remove last label }
  9694. RemoveInstruction(hp5);
  9695. { remove second label }
  9696. RemoveInstruction(hp3);
  9697. { if align is present remove it }
  9698. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9699. RemoveInstruction(hp3);
  9700. { remove jmp }
  9701. RemoveInstruction(hp2);
  9702. if taicpu(hp1).opsize=S_B then
  9703. RemoveInstruction(hp1)
  9704. else
  9705. taicpu(hp1).loadconst(0,0);
  9706. taicpu(hp4).opcode:=A_SETcc;
  9707. taicpu(hp4).opsize:=S_B;
  9708. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9709. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9710. taicpu(hp4).opercnt:=1;
  9711. taicpu(hp4).ops:=1;
  9712. taicpu(hp4).freeop(1);
  9713. RemoveCurrentP(p);
  9714. Result:=true;
  9715. exit;
  9716. end
  9717. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9718. begin
  9719. { check for
  9720. jCC xxx
  9721. <several movs>
  9722. xxx:
  9723. Also spot:
  9724. Jcc xxx
  9725. <several movs>
  9726. jmp xxx
  9727. Change to:
  9728. <several cmovs with inverted condition>
  9729. jmp xxx
  9730. }
  9731. l:=0;
  9732. while assigned(hp1) and
  9733. CanBeCMOV(hp1) and
  9734. { stop on labels }
  9735. not(hp1.typ=ait_label) do
  9736. begin
  9737. inc(l);
  9738. hp5 := hp1;
  9739. GetNextInstruction(hp1,hp1);
  9740. end;
  9741. if assigned(hp1) then
  9742. begin
  9743. TransferUsedRegs(TmpUsedRegs);
  9744. if (
  9745. MatchInstruction(hp1, A_JMP, []) and
  9746. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9747. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9748. ) or
  9749. FindLabel(tasmlabel(symbol),hp1) then
  9750. begin
  9751. if (l<=4) and (l>0) then
  9752. begin
  9753. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9754. condition:=inverse_cond(taicpu(p).condition);
  9755. UpdateUsedRegs(tai(p.next));
  9756. GetNextInstruction(p,hp1);
  9757. repeat
  9758. if not Assigned(hp1) then
  9759. InternalError(2018062900);
  9760. taicpu(hp1).opcode:=A_CMOVcc;
  9761. taicpu(hp1).condition:=condition;
  9762. UpdateUsedRegs(tai(hp1.next));
  9763. GetNextInstruction(hp1,hp1);
  9764. until not(CanBeCMOV(hp1));
  9765. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9766. hp2 := hp1;
  9767. repeat
  9768. if not Assigned(hp2) then
  9769. InternalError(2018062910);
  9770. case hp2.typ of
  9771. ait_label:
  9772. { What we expected - break out of the loop (it won't be a dead label at the top of
  9773. a cluster because that was optimised at an earlier stage) }
  9774. Break;
  9775. ait_align:
  9776. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9777. begin
  9778. hp2 := tai(hp2.Next);
  9779. Continue;
  9780. end;
  9781. ait_instruction:
  9782. begin
  9783. if taicpu(hp2).opcode<>A_JMP then
  9784. InternalError(2018062912);
  9785. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9786. Break;
  9787. end
  9788. else
  9789. begin
  9790. { Might be a comment or temporary allocation entry }
  9791. if not (hp2.typ in SkipInstr) then
  9792. InternalError(2018062911);
  9793. hp2 := tai(hp2.Next);
  9794. Continue;
  9795. end;
  9796. end;
  9797. until False;
  9798. { Now we can safely decrement the reference count }
  9799. tasmlabel(symbol).decrefs;
  9800. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9801. { Remove the original jump }
  9802. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9803. if hp2.typ=ait_instruction then
  9804. begin
  9805. p:=hp2;
  9806. Result:=True;
  9807. end
  9808. else
  9809. begin
  9810. UpdateUsedRegs(tai(hp2.next));
  9811. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9812. { Remove the label if this is its final reference }
  9813. if (tasmlabel(symbol).getrefs=0) then
  9814. StripLabelFast(hp1);
  9815. end;
  9816. exit;
  9817. end;
  9818. end
  9819. else
  9820. begin
  9821. { check further for
  9822. jCC xxx
  9823. <several movs 1>
  9824. jmp yyy
  9825. xxx:
  9826. <several movs 2>
  9827. yyy:
  9828. }
  9829. { hp2 points to jmp yyy }
  9830. hp2:=hp1;
  9831. { skip hp1 to xxx (or an align right before it) }
  9832. GetNextInstruction(hp1, hp1);
  9833. if assigned(hp2) and
  9834. assigned(hp1) and
  9835. (l<=3) and
  9836. (hp2.typ=ait_instruction) and
  9837. (taicpu(hp2).is_jmp) and
  9838. (taicpu(hp2).condition=C_None) and
  9839. { real label and jump, no further references to the
  9840. label are allowed }
  9841. (tasmlabel(symbol).getrefs=1) and
  9842. FindLabel(tasmlabel(symbol),hp1) then
  9843. begin
  9844. l:=0;
  9845. { skip hp1 to <several moves 2> }
  9846. if (hp1.typ = ait_align) then
  9847. GetNextInstruction(hp1, hp1);
  9848. GetNextInstruction(hp1, hpmov2);
  9849. hp1 := hpmov2;
  9850. while assigned(hp1) and
  9851. CanBeCMOV(hp1) do
  9852. begin
  9853. inc(l);
  9854. hp5 := hp1;
  9855. GetNextInstruction(hp1, hp1);
  9856. end;
  9857. { hp1 points to yyy (or an align right before it) }
  9858. hp3 := hp1;
  9859. if assigned(hp1) and
  9860. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9861. begin
  9862. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9863. condition:=inverse_cond(taicpu(p).condition);
  9864. UpdateUsedRegs(tai(p.next));
  9865. GetNextInstruction(p,hp1);
  9866. repeat
  9867. taicpu(hp1).opcode:=A_CMOVcc;
  9868. taicpu(hp1).condition:=condition;
  9869. UpdateUsedRegs(tai(hp1.next));
  9870. GetNextInstruction(hp1,hp1);
  9871. until not(assigned(hp1)) or
  9872. not(CanBeCMOV(hp1));
  9873. condition:=inverse_cond(condition);
  9874. if GetLastInstruction(hpmov2,hp1) then
  9875. UpdateUsedRegs(tai(hp1.next));
  9876. hp1 := hpmov2;
  9877. { hp1 is now at <several movs 2> }
  9878. while Assigned(hp1) and CanBeCMOV(hp1) do
  9879. begin
  9880. taicpu(hp1).opcode:=A_CMOVcc;
  9881. taicpu(hp1).condition:=condition;
  9882. UpdateUsedRegs(tai(hp1.next));
  9883. GetNextInstruction(hp1,hp1);
  9884. end;
  9885. hp1 := p;
  9886. { Get first instruction after label }
  9887. UpdateUsedRegs(tai(hp3.next));
  9888. GetNextInstruction(hp3, p);
  9889. if assigned(p) and (hp3.typ = ait_align) then
  9890. GetNextInstruction(p, p);
  9891. { Don't dereference yet, as doing so will cause
  9892. GetNextInstruction to skip the label and
  9893. optional align marker. [Kit] }
  9894. GetNextInstruction(hp2, hp4);
  9895. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9896. { remove jCC }
  9897. RemoveInstruction(hp1);
  9898. { Now we can safely decrement it }
  9899. tasmlabel(symbol).decrefs;
  9900. { Remove label xxx (it will have a ref of zero due to the initial check }
  9901. StripLabelFast(hp4);
  9902. { remove jmp }
  9903. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9904. RemoveInstruction(hp2);
  9905. { As before, now we can safely decrement it }
  9906. tasmlabel(symbol).decrefs;
  9907. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9908. if tasmlabel(symbol).getrefs = 0 then
  9909. StripLabelFast(hp3);
  9910. if Assigned(p) then
  9911. result:=true;
  9912. exit;
  9913. end;
  9914. end;
  9915. end;
  9916. end;
  9917. {$endif i8086}
  9918. end;
  9919. end;
  9920. end;
  9921. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9922. var
  9923. hp1,hp2,hp3: tai;
  9924. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9925. NewSize: TOpSize;
  9926. NewRegSize: TSubRegister;
  9927. Limit: TCgInt;
  9928. SwapOper: POper;
  9929. begin
  9930. result:=false;
  9931. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9932. GetNextInstruction(p,hp1) and
  9933. (hp1.typ = ait_instruction);
  9934. if reg_and_hp1_is_instr and
  9935. (
  9936. (taicpu(hp1).opcode <> A_LEA) or
  9937. { If the LEA instruction can be converted into an arithmetic instruction,
  9938. it may be possible to then fold it. }
  9939. (
  9940. { If the flags register is in use, don't change the instruction
  9941. to an ADD otherwise this will scramble the flags. [Kit] }
  9942. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9943. ConvertLEA(taicpu(hp1))
  9944. )
  9945. ) and
  9946. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9947. GetNextInstruction(hp1,hp2) and
  9948. MatchInstruction(hp2,A_MOV,[]) and
  9949. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9950. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9951. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9952. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9953. {$ifdef i386}
  9954. { not all registers have byte size sub registers on i386 }
  9955. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9956. {$endif i386}
  9957. (((taicpu(hp1).ops=2) and
  9958. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9959. ((taicpu(hp1).ops=1) and
  9960. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9961. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9962. begin
  9963. { change movsX/movzX reg/ref, reg2
  9964. add/sub/or/... reg3/$const, reg2
  9965. mov reg2 reg/ref
  9966. to add/sub/or/... reg3/$const, reg/ref }
  9967. { by example:
  9968. movswl %si,%eax movswl %si,%eax p
  9969. decl %eax addl %edx,%eax hp1
  9970. movw %ax,%si movw %ax,%si hp2
  9971. ->
  9972. movswl %si,%eax movswl %si,%eax p
  9973. decw %eax addw %edx,%eax hp1
  9974. movw %ax,%si movw %ax,%si hp2
  9975. }
  9976. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9977. {
  9978. ->
  9979. movswl %si,%eax movswl %si,%eax p
  9980. decw %si addw %dx,%si hp1
  9981. movw %ax,%si movw %ax,%si hp2
  9982. }
  9983. case taicpu(hp1).ops of
  9984. 1:
  9985. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9986. 2:
  9987. begin
  9988. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9989. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9990. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9991. end;
  9992. else
  9993. internalerror(2008042702);
  9994. end;
  9995. {
  9996. ->
  9997. decw %si addw %dx,%si p
  9998. }
  9999. DebugMsg(SPeepholeOptimization + 'var3',p);
  10000. RemoveCurrentP(p, hp1);
  10001. RemoveInstruction(hp2);
  10002. Result := True;
  10003. Exit;
  10004. end;
  10005. if reg_and_hp1_is_instr and
  10006. (taicpu(hp1).opcode = A_MOV) and
  10007. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10008. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10009. {$ifdef x86_64}
  10010. { check for implicit extension to 64 bit }
  10011. or
  10012. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10013. (taicpu(hp1).opsize=S_Q) and
  10014. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10015. )
  10016. {$endif x86_64}
  10017. )
  10018. then
  10019. begin
  10020. { change
  10021. movx %reg1,%reg2
  10022. mov %reg2,%reg3
  10023. dealloc %reg2
  10024. into
  10025. movx %reg,%reg3
  10026. }
  10027. TransferUsedRegs(TmpUsedRegs);
  10028. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10029. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10030. begin
  10031. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10032. {$ifdef x86_64}
  10033. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10034. (taicpu(hp1).opsize=S_Q) then
  10035. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10036. else
  10037. {$endif x86_64}
  10038. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10039. RemoveInstruction(hp1);
  10040. Result := True;
  10041. Exit;
  10042. end;
  10043. end;
  10044. if reg_and_hp1_is_instr and
  10045. ((taicpu(hp1).opcode=A_MOV) or
  10046. (taicpu(hp1).opcode=A_ADD) or
  10047. (taicpu(hp1).opcode=A_SUB) or
  10048. (taicpu(hp1).opcode=A_CMP) or
  10049. (taicpu(hp1).opcode=A_OR) or
  10050. (taicpu(hp1).opcode=A_XOR) or
  10051. (taicpu(hp1).opcode=A_AND)
  10052. ) and
  10053. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10054. begin
  10055. AndTest := (taicpu(hp1).opcode=A_AND) and
  10056. GetNextInstruction(hp1, hp2) and
  10057. (hp2.typ = ait_instruction) and
  10058. (
  10059. (
  10060. (taicpu(hp2).opcode=A_TEST) and
  10061. (
  10062. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10063. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10064. (
  10065. { If the AND and TEST instructions share a constant, this is also valid }
  10066. (taicpu(hp1).oper[0]^.typ = top_const) and
  10067. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10068. )
  10069. ) and
  10070. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10071. ) or
  10072. (
  10073. (taicpu(hp2).opcode=A_CMP) and
  10074. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10075. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10076. )
  10077. );
  10078. { change
  10079. movx (oper),%reg2
  10080. and $x,%reg2
  10081. test %reg2,%reg2
  10082. dealloc %reg2
  10083. into
  10084. op %reg1,%reg3
  10085. if the second op accesses only the bits stored in reg1
  10086. }
  10087. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10088. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10089. (taicpu(hp1).oper[0]^.typ = top_const) and
  10090. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10091. AndTest then
  10092. begin
  10093. { Check if the AND constant is in range }
  10094. case taicpu(p).opsize of
  10095. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10096. begin
  10097. NewSize := S_B;
  10098. Limit := $FF;
  10099. end;
  10100. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10101. begin
  10102. NewSize := S_W;
  10103. Limit := $FFFF;
  10104. end;
  10105. {$ifdef x86_64}
  10106. S_LQ:
  10107. begin
  10108. NewSize := S_L;
  10109. Limit := $FFFFFFFF;
  10110. end;
  10111. {$endif x86_64}
  10112. else
  10113. InternalError(2021120303);
  10114. end;
  10115. if (
  10116. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10117. { Check for negative operands }
  10118. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10119. ) and
  10120. GetNextInstruction(hp2,hp3) and
  10121. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10122. (taicpu(hp3).condition in [C_E,C_NE]) then
  10123. begin
  10124. TransferUsedRegs(TmpUsedRegs);
  10125. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10126. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10127. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10128. begin
  10129. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10130. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10131. taicpu(hp1).opcode := A_TEST;
  10132. taicpu(hp1).opsize := NewSize;
  10133. RemoveInstruction(hp2);
  10134. RemoveCurrentP(p, hp1);
  10135. Result:=true;
  10136. exit;
  10137. end;
  10138. end;
  10139. end;
  10140. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10141. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10142. (taicpu(hp1).opsize=S_B)) or
  10143. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10144. (taicpu(hp1).opsize=S_W))
  10145. {$ifdef x86_64}
  10146. or ((taicpu(p).opsize=S_LQ) and
  10147. (taicpu(hp1).opsize=S_L))
  10148. {$endif x86_64}
  10149. ) and
  10150. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10151. begin
  10152. { change
  10153. movx %reg1,%reg2
  10154. op %reg2,%reg3
  10155. dealloc %reg2
  10156. into
  10157. op %reg1,%reg3
  10158. if the second op accesses only the bits stored in reg1
  10159. }
  10160. TransferUsedRegs(TmpUsedRegs);
  10161. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10162. if AndTest then
  10163. begin
  10164. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10165. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10166. end
  10167. else
  10168. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10169. if not RegUsed then
  10170. begin
  10171. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10172. if taicpu(p).oper[0]^.typ=top_reg then
  10173. begin
  10174. case taicpu(hp1).opsize of
  10175. S_B:
  10176. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10177. S_W:
  10178. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10179. S_L:
  10180. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10181. else
  10182. Internalerror(2020102301);
  10183. end;
  10184. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10185. end
  10186. else
  10187. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10188. RemoveCurrentP(p);
  10189. if AndTest then
  10190. RemoveInstruction(hp2);
  10191. result:=true;
  10192. exit;
  10193. end;
  10194. end
  10195. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10196. (
  10197. { Bitwise operations only }
  10198. (taicpu(hp1).opcode=A_AND) or
  10199. (taicpu(hp1).opcode=A_TEST) or
  10200. (
  10201. (taicpu(hp1).oper[0]^.typ = top_const) and
  10202. (
  10203. (taicpu(hp1).opcode=A_OR) or
  10204. (taicpu(hp1).opcode=A_XOR)
  10205. )
  10206. )
  10207. ) and
  10208. (
  10209. (taicpu(hp1).oper[0]^.typ = top_const) or
  10210. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10211. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10212. ) then
  10213. begin
  10214. { change
  10215. movx %reg2,%reg2
  10216. op const,%reg2
  10217. into
  10218. op const,%reg2 (smaller version)
  10219. movx %reg2,%reg2
  10220. also change
  10221. movx %reg1,%reg2
  10222. and/test (oper),%reg2
  10223. dealloc %reg2
  10224. into
  10225. and/test (oper),%reg1
  10226. }
  10227. case taicpu(p).opsize of
  10228. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10229. begin
  10230. NewSize := S_B;
  10231. NewRegSize := R_SUBL;
  10232. Limit := $FF;
  10233. end;
  10234. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10235. begin
  10236. NewSize := S_W;
  10237. NewRegSize := R_SUBW;
  10238. Limit := $FFFF;
  10239. end;
  10240. {$ifdef x86_64}
  10241. S_LQ:
  10242. begin
  10243. NewSize := S_L;
  10244. NewRegSize := R_SUBD;
  10245. Limit := $FFFFFFFF;
  10246. end;
  10247. {$endif x86_64}
  10248. else
  10249. Internalerror(2021120302);
  10250. end;
  10251. TransferUsedRegs(TmpUsedRegs);
  10252. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10253. if AndTest then
  10254. begin
  10255. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10256. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10257. end
  10258. else
  10259. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10260. if
  10261. (
  10262. (taicpu(p).opcode = A_MOVZX) and
  10263. (
  10264. (taicpu(hp1).opcode=A_AND) or
  10265. (taicpu(hp1).opcode=A_TEST)
  10266. ) and
  10267. not (
  10268. { If both are references, then the final instruction will have
  10269. both operands as references, which is not allowed }
  10270. (taicpu(p).oper[0]^.typ = top_ref) and
  10271. (taicpu(hp1).oper[0]^.typ = top_ref)
  10272. ) and
  10273. not RegUsed
  10274. ) or
  10275. (
  10276. (
  10277. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10278. not RegUsed
  10279. ) and
  10280. (taicpu(p).oper[0]^.typ = top_reg) and
  10281. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10282. (taicpu(hp1).oper[0]^.typ = top_const) and
  10283. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10284. ) then
  10285. begin
  10286. {$if defined(i386) or defined(i8086)}
  10287. { If the target size is 8-bit, make sure we can actually encode it }
  10288. 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
  10289. Exit;
  10290. {$endif i386 or i8086}
  10291. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10292. taicpu(hp1).opsize := NewSize;
  10293. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10294. if AndTest then
  10295. begin
  10296. RemoveInstruction(hp2);
  10297. if not RegUsed then
  10298. begin
  10299. taicpu(hp1).opcode := A_TEST;
  10300. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10301. begin
  10302. { Make sure the reference is the second operand }
  10303. SwapOper := taicpu(hp1).oper[0];
  10304. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10305. taicpu(hp1).oper[1] := SwapOper;
  10306. end;
  10307. end;
  10308. end;
  10309. case taicpu(hp1).oper[0]^.typ of
  10310. top_reg:
  10311. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10312. top_const:
  10313. { For the AND/TEST case }
  10314. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10315. else
  10316. ;
  10317. end;
  10318. if RegUsed then
  10319. begin
  10320. AsmL.Remove(p);
  10321. AsmL.InsertAfter(p, hp1);
  10322. p := hp1;
  10323. end
  10324. else
  10325. RemoveCurrentP(p, hp1);
  10326. result:=true;
  10327. exit;
  10328. end;
  10329. end;
  10330. end;
  10331. if reg_and_hp1_is_instr and
  10332. (taicpu(p).oper[0]^.typ = top_reg) and
  10333. (
  10334. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10335. ) and
  10336. (taicpu(hp1).oper[0]^.typ = top_const) and
  10337. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10338. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10339. { Minimum shift value allowed is the bit difference between the sizes }
  10340. (taicpu(hp1).oper[0]^.val >=
  10341. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10342. 8 * (
  10343. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10344. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10345. )
  10346. ) then
  10347. begin
  10348. { For:
  10349. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10350. shl/sal ##, %reg1
  10351. Remove the movsx/movzx instruction if the shift overwrites the
  10352. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10353. }
  10354. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10355. RemoveCurrentP(p, hp1);
  10356. Result := True;
  10357. Exit;
  10358. end
  10359. else if reg_and_hp1_is_instr and
  10360. (taicpu(p).oper[0]^.typ = top_reg) and
  10361. (
  10362. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10363. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10364. ) and
  10365. (taicpu(hp1).oper[0]^.typ = top_const) and
  10366. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10367. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10368. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10369. (taicpu(hp1).oper[0]^.val <
  10370. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10371. 8 * (
  10372. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10373. )
  10374. ) then
  10375. begin
  10376. { For:
  10377. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10378. sar ##, %reg1 shr ##, %reg1
  10379. Move the shift to before the movx instruction if the shift value
  10380. is not too large.
  10381. }
  10382. asml.Remove(hp1);
  10383. asml.InsertBefore(hp1, p);
  10384. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10385. case taicpu(p).opsize of
  10386. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10387. taicpu(hp1).opsize := S_B;
  10388. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10389. taicpu(hp1).opsize := S_W;
  10390. {$ifdef x86_64}
  10391. S_LQ:
  10392. taicpu(hp1).opsize := S_L;
  10393. {$endif}
  10394. else
  10395. InternalError(2020112401);
  10396. end;
  10397. if (taicpu(hp1).opcode = A_SHR) then
  10398. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10399. else
  10400. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10401. Result := True;
  10402. end;
  10403. if reg_and_hp1_is_instr and
  10404. (taicpu(p).oper[0]^.typ = top_reg) and
  10405. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10406. (
  10407. (taicpu(hp1).opcode = taicpu(p).opcode)
  10408. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10409. {$ifdef x86_64}
  10410. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10411. {$endif x86_64}
  10412. ) then
  10413. begin
  10414. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10415. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10416. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10417. begin
  10418. {
  10419. For example:
  10420. movzbw %al,%ax
  10421. movzwl %ax,%eax
  10422. Compress into:
  10423. movzbl %al,%eax
  10424. }
  10425. RegUsed := False;
  10426. case taicpu(p).opsize of
  10427. S_BW:
  10428. case taicpu(hp1).opsize of
  10429. S_WL:
  10430. begin
  10431. taicpu(p).opsize := S_BL;
  10432. RegUsed := True;
  10433. end;
  10434. {$ifdef x86_64}
  10435. S_WQ:
  10436. begin
  10437. if taicpu(p).opcode = A_MOVZX then
  10438. begin
  10439. taicpu(p).opsize := S_BL;
  10440. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10441. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10442. end
  10443. else
  10444. taicpu(p).opsize := S_BQ;
  10445. RegUsed := True;
  10446. end;
  10447. {$endif x86_64}
  10448. else
  10449. ;
  10450. end;
  10451. {$ifdef x86_64}
  10452. S_BL:
  10453. case taicpu(hp1).opsize of
  10454. S_LQ:
  10455. begin
  10456. if taicpu(p).opcode = A_MOVZX then
  10457. begin
  10458. taicpu(p).opsize := S_BL;
  10459. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10460. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10461. end
  10462. else
  10463. taicpu(p).opsize := S_BQ;
  10464. RegUsed := True;
  10465. end;
  10466. else
  10467. ;
  10468. end;
  10469. S_WL:
  10470. case taicpu(hp1).opsize of
  10471. S_LQ:
  10472. begin
  10473. if taicpu(p).opcode = A_MOVZX then
  10474. begin
  10475. taicpu(p).opsize := S_WL;
  10476. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10477. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10478. end
  10479. else
  10480. taicpu(p).opsize := S_WQ;
  10481. RegUsed := True;
  10482. end;
  10483. else
  10484. ;
  10485. end;
  10486. {$endif x86_64}
  10487. else
  10488. ;
  10489. end;
  10490. if RegUsed then
  10491. begin
  10492. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10493. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10494. RemoveInstruction(hp1);
  10495. Result := True;
  10496. Exit;
  10497. end;
  10498. end;
  10499. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10500. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10501. GetNextInstruction(hp1, hp2) and
  10502. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10503. (
  10504. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10505. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10506. {$ifdef x86_64}
  10507. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10508. {$endif x86_64}
  10509. ) and
  10510. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10511. (
  10512. (
  10513. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10514. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10515. ) or
  10516. (
  10517. { Only allow the operands in reverse order for TEST instructions }
  10518. (taicpu(hp2).opcode = A_TEST) and
  10519. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10520. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10521. )
  10522. ) then
  10523. begin
  10524. {
  10525. For example:
  10526. movzbl %al,%eax
  10527. movzbl (ref),%edx
  10528. andl %edx,%eax
  10529. (%edx deallocated)
  10530. Change to:
  10531. andb (ref),%al
  10532. movzbl %al,%eax
  10533. Rules are:
  10534. - First two instructions have the same opcode and opsize
  10535. - First instruction's operands are the same super-register
  10536. - Second instruction operates on a different register
  10537. - Third instruction is AND, OR, XOR or TEST
  10538. - Third instruction's operands are the destination registers of the first two instructions
  10539. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10540. - Second instruction's destination register is deallocated afterwards
  10541. }
  10542. TransferUsedRegs(TmpUsedRegs);
  10543. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10544. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10545. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10546. begin
  10547. case taicpu(p).opsize of
  10548. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10549. NewSize := S_B;
  10550. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10551. NewSize := S_W;
  10552. {$ifdef x86_64}
  10553. S_LQ:
  10554. NewSize := S_L;
  10555. {$endif x86_64}
  10556. else
  10557. InternalError(2021120301);
  10558. end;
  10559. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10560. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10561. taicpu(hp2).opsize := NewSize;
  10562. RemoveInstruction(hp1);
  10563. { With TEST, it's best to keep the MOVX instruction at the top }
  10564. if (taicpu(hp2).opcode <> A_TEST) then
  10565. begin
  10566. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10567. asml.Remove(p);
  10568. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10569. asml.InsertAfter(p, hp2);
  10570. p := hp2;
  10571. end
  10572. else
  10573. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10574. Result := True;
  10575. Exit;
  10576. end;
  10577. end;
  10578. end;
  10579. if taicpu(p).opcode=A_MOVZX then
  10580. begin
  10581. { removes superfluous And's after movzx's }
  10582. if reg_and_hp1_is_instr and
  10583. (taicpu(hp1).opcode = A_AND) and
  10584. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10585. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10586. {$ifdef x86_64}
  10587. { check for implicit extension to 64 bit }
  10588. or
  10589. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10590. (taicpu(hp1).opsize=S_Q) and
  10591. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10592. )
  10593. {$endif x86_64}
  10594. )
  10595. then
  10596. begin
  10597. case taicpu(p).opsize Of
  10598. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10599. if (taicpu(hp1).oper[0]^.val = $ff) then
  10600. begin
  10601. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10602. RemoveInstruction(hp1);
  10603. Result:=true;
  10604. exit;
  10605. end;
  10606. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10607. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10608. begin
  10609. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10610. RemoveInstruction(hp1);
  10611. Result:=true;
  10612. exit;
  10613. end;
  10614. {$ifdef x86_64}
  10615. S_LQ:
  10616. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10617. begin
  10618. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10619. RemoveInstruction(hp1);
  10620. Result:=true;
  10621. exit;
  10622. end;
  10623. {$endif x86_64}
  10624. else
  10625. ;
  10626. end;
  10627. { we cannot get rid of the and, but can we get rid of the movz ?}
  10628. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10629. begin
  10630. case taicpu(p).opsize Of
  10631. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10632. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10633. begin
  10634. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10635. RemoveCurrentP(p,hp1);
  10636. Result:=true;
  10637. exit;
  10638. end;
  10639. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10640. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10641. begin
  10642. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10643. RemoveCurrentP(p,hp1);
  10644. Result:=true;
  10645. exit;
  10646. end;
  10647. {$ifdef x86_64}
  10648. S_LQ:
  10649. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10650. begin
  10651. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10652. RemoveCurrentP(p,hp1);
  10653. Result:=true;
  10654. exit;
  10655. end;
  10656. {$endif x86_64}
  10657. else
  10658. ;
  10659. end;
  10660. end;
  10661. end;
  10662. { changes some movzx constructs to faster synonyms (all examples
  10663. are given with eax/ax, but are also valid for other registers)}
  10664. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10665. begin
  10666. case taicpu(p).opsize of
  10667. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10668. (the machine code is equivalent to movzbl %al,%eax), but the
  10669. code generator still generates that assembler instruction and
  10670. it is silently converted. This should probably be checked.
  10671. [Kit] }
  10672. S_BW:
  10673. begin
  10674. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10675. (
  10676. not IsMOVZXAcceptable
  10677. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10678. or (
  10679. (cs_opt_size in current_settings.optimizerswitches) and
  10680. (taicpu(p).oper[1]^.reg = NR_AX)
  10681. )
  10682. ) then
  10683. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10684. begin
  10685. DebugMsg(SPeepholeOptimization + 'var7',p);
  10686. taicpu(p).opcode := A_AND;
  10687. taicpu(p).changeopsize(S_W);
  10688. taicpu(p).loadConst(0,$ff);
  10689. Result := True;
  10690. end
  10691. else if not IsMOVZXAcceptable and
  10692. GetNextInstruction(p, hp1) and
  10693. (tai(hp1).typ = ait_instruction) and
  10694. (taicpu(hp1).opcode = A_AND) and
  10695. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10696. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10697. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10698. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10699. begin
  10700. DebugMsg(SPeepholeOptimization + 'var8',p);
  10701. taicpu(p).opcode := A_MOV;
  10702. taicpu(p).changeopsize(S_W);
  10703. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10704. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10705. Result := True;
  10706. end;
  10707. end;
  10708. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10709. S_BL:
  10710. begin
  10711. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10712. (
  10713. not IsMOVZXAcceptable
  10714. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10715. or (
  10716. (cs_opt_size in current_settings.optimizerswitches) and
  10717. (taicpu(p).oper[1]^.reg = NR_EAX)
  10718. )
  10719. ) then
  10720. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10721. begin
  10722. DebugMsg(SPeepholeOptimization + 'var9',p);
  10723. taicpu(p).opcode := A_AND;
  10724. taicpu(p).changeopsize(S_L);
  10725. taicpu(p).loadConst(0,$ff);
  10726. Result := True;
  10727. end
  10728. else if not IsMOVZXAcceptable and
  10729. GetNextInstruction(p, hp1) and
  10730. (tai(hp1).typ = ait_instruction) and
  10731. (taicpu(hp1).opcode = A_AND) and
  10732. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10733. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10734. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10735. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10736. begin
  10737. DebugMsg(SPeepholeOptimization + 'var10',p);
  10738. taicpu(p).opcode := A_MOV;
  10739. taicpu(p).changeopsize(S_L);
  10740. { do not use R_SUBWHOLE
  10741. as movl %rdx,%eax
  10742. is invalid in assembler PM }
  10743. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10744. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10745. Result := True;
  10746. end;
  10747. end;
  10748. {$endif i8086}
  10749. S_WL:
  10750. if not IsMOVZXAcceptable then
  10751. begin
  10752. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10753. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10754. begin
  10755. DebugMsg(SPeepholeOptimization + 'var11',p);
  10756. taicpu(p).opcode := A_AND;
  10757. taicpu(p).changeopsize(S_L);
  10758. taicpu(p).loadConst(0,$ffff);
  10759. Result := True;
  10760. end
  10761. else if GetNextInstruction(p, hp1) and
  10762. (tai(hp1).typ = ait_instruction) and
  10763. (taicpu(hp1).opcode = A_AND) and
  10764. (taicpu(hp1).oper[0]^.typ = top_const) and
  10765. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10766. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10767. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10768. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10769. begin
  10770. DebugMsg(SPeepholeOptimization + 'var12',p);
  10771. taicpu(p).opcode := A_MOV;
  10772. taicpu(p).changeopsize(S_L);
  10773. { do not use R_SUBWHOLE
  10774. as movl %rdx,%eax
  10775. is invalid in assembler PM }
  10776. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10777. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10778. Result := True;
  10779. end;
  10780. end;
  10781. else
  10782. InternalError(2017050705);
  10783. end;
  10784. end
  10785. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10786. begin
  10787. if GetNextInstruction(p, hp1) and
  10788. (tai(hp1).typ = ait_instruction) and
  10789. (taicpu(hp1).opcode = A_AND) and
  10790. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10791. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10792. begin
  10793. //taicpu(p).opcode := A_MOV;
  10794. case taicpu(p).opsize Of
  10795. S_BL:
  10796. begin
  10797. DebugMsg(SPeepholeOptimization + 'var13',p);
  10798. taicpu(hp1).changeopsize(S_L);
  10799. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10800. end;
  10801. S_WL:
  10802. begin
  10803. DebugMsg(SPeepholeOptimization + 'var14',p);
  10804. taicpu(hp1).changeopsize(S_L);
  10805. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10806. end;
  10807. S_BW:
  10808. begin
  10809. DebugMsg(SPeepholeOptimization + 'var15',p);
  10810. taicpu(hp1).changeopsize(S_W);
  10811. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10812. end;
  10813. else
  10814. Internalerror(2017050704)
  10815. end;
  10816. Result := True;
  10817. end;
  10818. end;
  10819. end;
  10820. end;
  10821. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10822. var
  10823. hp1, hp2 : tai;
  10824. MaskLength : Cardinal;
  10825. MaskedBits : TCgInt;
  10826. ActiveReg : TRegister;
  10827. begin
  10828. Result:=false;
  10829. { There are no optimisations for reference targets }
  10830. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10831. Exit;
  10832. while GetNextInstruction(p, hp1) and
  10833. (hp1.typ = ait_instruction) do
  10834. begin
  10835. if (taicpu(p).oper[0]^.typ = top_const) then
  10836. begin
  10837. case taicpu(hp1).opcode of
  10838. A_AND:
  10839. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10840. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10841. { the second register must contain the first one, so compare their subreg types }
  10842. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10843. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10844. { change
  10845. and const1, reg
  10846. and const2, reg
  10847. to
  10848. and (const1 and const2), reg
  10849. }
  10850. begin
  10851. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10852. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10853. RemoveCurrentP(p, hp1);
  10854. Result:=true;
  10855. exit;
  10856. end;
  10857. A_CMP:
  10858. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10859. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10860. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10861. { Just check that the condition on the next instruction is compatible }
  10862. GetNextInstruction(hp1, hp2) and
  10863. (hp2.typ = ait_instruction) and
  10864. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10865. then
  10866. { change
  10867. and 2^n, reg
  10868. cmp 2^n, reg
  10869. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10870. to
  10871. and 2^n, reg
  10872. test reg, reg
  10873. j(~c) / set(~c) / cmov(~c)
  10874. }
  10875. begin
  10876. { Keep TEST instruction in, rather than remove it, because
  10877. it may trigger other optimisations such as MovAndTest2Test }
  10878. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10879. taicpu(hp1).opcode := A_TEST;
  10880. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10881. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10882. Result := True;
  10883. Exit;
  10884. end;
  10885. A_MOVZX:
  10886. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10887. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10888. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10889. (
  10890. (
  10891. (taicpu(p).opsize=S_W) and
  10892. (taicpu(hp1).opsize=S_BW)
  10893. ) or
  10894. (
  10895. (taicpu(p).opsize=S_L) and
  10896. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10897. )
  10898. {$ifdef x86_64}
  10899. or
  10900. (
  10901. (taicpu(p).opsize=S_Q) and
  10902. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10903. )
  10904. {$endif x86_64}
  10905. ) then
  10906. begin
  10907. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10908. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10909. ) or
  10910. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10911. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10912. then
  10913. begin
  10914. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10915. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10916. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10917. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10918. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10919. }
  10920. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10921. RemoveInstruction(hp1);
  10922. { See if there are other optimisations possible }
  10923. Continue;
  10924. end;
  10925. end;
  10926. A_SHL:
  10927. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10928. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10929. begin
  10930. {$ifopt R+}
  10931. {$define RANGE_WAS_ON}
  10932. {$R-}
  10933. {$endif}
  10934. { get length of potential and mask }
  10935. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10936. { really a mask? }
  10937. {$ifdef RANGE_WAS_ON}
  10938. {$R+}
  10939. {$endif}
  10940. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10941. { unmasked part shifted out? }
  10942. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10943. begin
  10944. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10945. RemoveCurrentP(p, hp1);
  10946. Result:=true;
  10947. exit;
  10948. end;
  10949. end;
  10950. A_SHR:
  10951. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10952. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10953. (taicpu(hp1).oper[0]^.val <= 63) then
  10954. begin
  10955. { Does SHR combined with the AND cover all the bits?
  10956. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10957. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10958. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10959. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10960. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10961. begin
  10962. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10963. RemoveCurrentP(p, hp1);
  10964. Result := True;
  10965. Exit;
  10966. end;
  10967. end;
  10968. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10969. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10970. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10971. begin
  10972. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10973. (
  10974. (
  10975. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10976. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10977. ) or (
  10978. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10979. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10980. {$ifdef x86_64}
  10981. ) or (
  10982. (taicpu(hp1).opsize = S_LQ) and
  10983. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10984. {$endif x86_64}
  10985. )
  10986. ) then
  10987. begin
  10988. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10989. begin
  10990. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10991. RemoveInstruction(hp1);
  10992. { See if there are other optimisations possible }
  10993. Continue;
  10994. end;
  10995. { The super-registers are the same though.
  10996. Note that this change by itself doesn't improve
  10997. code speed, but it opens up other optimisations. }
  10998. {$ifdef x86_64}
  10999. { Convert 64-bit register to 32-bit }
  11000. case taicpu(hp1).opsize of
  11001. S_BQ:
  11002. begin
  11003. taicpu(hp1).opsize := S_BL;
  11004. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11005. end;
  11006. S_WQ:
  11007. begin
  11008. taicpu(hp1).opsize := S_WL;
  11009. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11010. end
  11011. else
  11012. ;
  11013. end;
  11014. {$endif x86_64}
  11015. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11016. taicpu(hp1).opcode := A_MOVZX;
  11017. { See if there are other optimisations possible }
  11018. Continue;
  11019. end;
  11020. end;
  11021. else
  11022. ;
  11023. end;
  11024. end
  11025. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11026. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11027. begin
  11028. {$ifdef x86_64}
  11029. if (taicpu(p).opsize = S_Q) then
  11030. begin
  11031. { Never necessary }
  11032. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11033. RemoveCurrentP(p, hp1);
  11034. Result := True;
  11035. Exit;
  11036. end;
  11037. {$endif x86_64}
  11038. { Forward check to determine necessity of and %reg,%reg }
  11039. TransferUsedRegs(TmpUsedRegs);
  11040. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11041. { Saves on a bunch of dereferences }
  11042. ActiveReg := taicpu(p).oper[1]^.reg;
  11043. case taicpu(hp1).opcode of
  11044. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11045. if (
  11046. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11047. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11048. ) and
  11049. (
  11050. (taicpu(hp1).opcode <> A_MOV) or
  11051. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11052. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11053. ) and
  11054. not (
  11055. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11056. (taicpu(hp1).opcode = A_MOV) and
  11057. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11058. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11059. ) and
  11060. (
  11061. (
  11062. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11063. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11064. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11065. ) or
  11066. (
  11067. {$ifdef x86_64}
  11068. (
  11069. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11070. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11071. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11072. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11073. ) and
  11074. {$endif x86_64}
  11075. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11076. )
  11077. ) then
  11078. begin
  11079. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11080. RemoveCurrentP(p, hp1);
  11081. Result := True;
  11082. Exit;
  11083. end;
  11084. A_ADD,
  11085. A_AND,
  11086. A_BSF,
  11087. A_BSR,
  11088. A_BTC,
  11089. A_BTR,
  11090. A_BTS,
  11091. A_OR,
  11092. A_SUB,
  11093. A_XOR:
  11094. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11095. if (
  11096. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11097. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11098. ) and
  11099. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11100. begin
  11101. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11102. RemoveCurrentP(p, hp1);
  11103. Result := True;
  11104. Exit;
  11105. end;
  11106. A_CMP,
  11107. A_TEST:
  11108. if (
  11109. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11110. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11111. ) and
  11112. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11113. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11114. begin
  11115. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11116. RemoveCurrentP(p, hp1);
  11117. Result := True;
  11118. Exit;
  11119. end;
  11120. A_BSWAP,
  11121. A_NEG,
  11122. A_NOT:
  11123. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11124. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11125. begin
  11126. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11127. RemoveCurrentP(p, hp1);
  11128. Result := True;
  11129. Exit;
  11130. end;
  11131. else
  11132. ;
  11133. end;
  11134. end;
  11135. if (taicpu(hp1).is_jmp) and
  11136. (taicpu(hp1).opcode<>A_JMP) and
  11137. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11138. begin
  11139. { change
  11140. and x, reg
  11141. jxx
  11142. to
  11143. test x, reg
  11144. jxx
  11145. if reg is deallocated before the
  11146. jump, but only if it's a conditional jump (PFV)
  11147. }
  11148. taicpu(p).opcode := A_TEST;
  11149. Exit;
  11150. end;
  11151. Break;
  11152. end;
  11153. { Lone AND tests }
  11154. if (taicpu(p).oper[0]^.typ = top_const) then
  11155. begin
  11156. {
  11157. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11158. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11159. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11160. }
  11161. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11162. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11163. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11164. begin
  11165. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11166. if taicpu(p).opsize = S_L then
  11167. begin
  11168. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11169. Result := True;
  11170. end;
  11171. end;
  11172. end;
  11173. { Backward check to determine necessity of and %reg,%reg }
  11174. if (taicpu(p).oper[0]^.typ = top_reg) and
  11175. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11176. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11177. GetLastInstruction(p, hp2) and
  11178. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11179. { Check size of adjacent instruction to determine if the AND is
  11180. effectively a null operation }
  11181. (
  11182. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11183. { Note: Don't include S_Q }
  11184. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11185. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11186. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11187. ) then
  11188. begin
  11189. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11190. { If GetNextInstruction returned False, hp1 will be nil }
  11191. RemoveCurrentP(p, hp1);
  11192. Result := True;
  11193. Exit;
  11194. end;
  11195. end;
  11196. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11197. var
  11198. hp1: tai; NewRef: TReference;
  11199. { This entire nested function is used in an if-statement below, but we
  11200. want to avoid all the used reg transfers and GetNextInstruction calls
  11201. until we really have to check }
  11202. function MemRegisterNotUsedLater: Boolean; inline;
  11203. var
  11204. hp2: tai;
  11205. begin
  11206. TransferUsedRegs(TmpUsedRegs);
  11207. hp2 := p;
  11208. repeat
  11209. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11210. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11211. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11212. end;
  11213. begin
  11214. Result := False;
  11215. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11216. Exit;
  11217. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11218. begin
  11219. { Change:
  11220. add %reg2,%reg1
  11221. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11222. To:
  11223. mov/s/z #(%reg1,%reg2),%reg1
  11224. }
  11225. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11226. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11227. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11228. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11229. (
  11230. (
  11231. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11232. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11233. { r/esp cannot be an index }
  11234. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11235. ) or (
  11236. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11237. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11238. )
  11239. ) and (
  11240. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11241. (
  11242. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11243. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11244. MemRegisterNotUsedLater
  11245. )
  11246. ) then
  11247. begin
  11248. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11249. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11250. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11251. RemoveCurrentp(p, hp1);
  11252. Result := True;
  11253. Exit;
  11254. end;
  11255. { Change:
  11256. addl/q $x,%reg1
  11257. movl/q %reg1,%reg2
  11258. To:
  11259. leal/q $x(%reg1),%reg2
  11260. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11261. Breaks the dependency chain.
  11262. }
  11263. if MatchOpType(taicpu(p),top_const,top_reg) and
  11264. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11265. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11266. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11267. (
  11268. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11269. not (cs_opt_size in current_settings.optimizerswitches) or
  11270. (
  11271. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11272. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11273. )
  11274. ) then
  11275. begin
  11276. { Change the MOV instruction to a LEA instruction, and update the
  11277. first operand }
  11278. reference_reset(NewRef, 1, []);
  11279. NewRef.base := taicpu(p).oper[1]^.reg;
  11280. NewRef.scalefactor := 1;
  11281. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11282. taicpu(hp1).opcode := A_LEA;
  11283. taicpu(hp1).loadref(0, NewRef);
  11284. TransferUsedRegs(TmpUsedRegs);
  11285. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11286. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11287. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11288. begin
  11289. { Move what is now the LEA instruction to before the SUB instruction }
  11290. Asml.Remove(hp1);
  11291. Asml.InsertBefore(hp1, p);
  11292. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11293. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11294. p := hp1;
  11295. end
  11296. else
  11297. begin
  11298. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11299. RemoveCurrentP(p, hp1);
  11300. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11301. end;
  11302. Result := True;
  11303. end;
  11304. end;
  11305. end;
  11306. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11307. var
  11308. SubReg: TSubRegister;
  11309. begin
  11310. Result:=false;
  11311. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11312. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11313. with taicpu(p).oper[0]^.ref^ do
  11314. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11315. begin
  11316. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11317. begin
  11318. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11319. taicpu(p).opcode := A_ADD;
  11320. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11321. Result := True;
  11322. end
  11323. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11324. begin
  11325. if (base <> NR_NO) then
  11326. begin
  11327. if (scalefactor <= 1) then
  11328. begin
  11329. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11330. taicpu(p).opcode := A_ADD;
  11331. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11332. Result := True;
  11333. end;
  11334. end
  11335. else
  11336. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11337. if (scalefactor in [2, 4, 8]) then
  11338. begin
  11339. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11340. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11341. taicpu(p).opcode := A_SHL;
  11342. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11343. Result := True;
  11344. end;
  11345. end;
  11346. end;
  11347. end;
  11348. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11349. var
  11350. hp1: tai; NewRef: TReference;
  11351. begin
  11352. { Change:
  11353. subl/q $x,%reg1
  11354. movl/q %reg1,%reg2
  11355. To:
  11356. leal/q $-x(%reg1),%reg2
  11357. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11358. Breaks the dependency chain and potentially permits the removal of
  11359. a CMP instruction if one follows.
  11360. }
  11361. Result := False;
  11362. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11363. MatchOpType(taicpu(p),top_const,top_reg) and
  11364. GetNextInstruction(p, hp1) and
  11365. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11366. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11367. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11368. (
  11369. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11370. not (cs_opt_size in current_settings.optimizerswitches) or
  11371. (
  11372. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11373. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11374. )
  11375. ) then
  11376. begin
  11377. { Change the MOV instruction to a LEA instruction, and update the
  11378. first operand }
  11379. reference_reset(NewRef, 1, []);
  11380. NewRef.base := taicpu(p).oper[1]^.reg;
  11381. NewRef.scalefactor := 1;
  11382. NewRef.offset := -taicpu(p).oper[0]^.val;
  11383. taicpu(hp1).opcode := A_LEA;
  11384. taicpu(hp1).loadref(0, NewRef);
  11385. TransferUsedRegs(TmpUsedRegs);
  11386. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11387. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11388. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11389. begin
  11390. { Move what is now the LEA instruction to before the SUB instruction }
  11391. Asml.Remove(hp1);
  11392. Asml.InsertBefore(hp1, p);
  11393. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11394. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11395. p := hp1;
  11396. end
  11397. else
  11398. begin
  11399. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11400. RemoveCurrentP(p, hp1);
  11401. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11402. end;
  11403. Result := True;
  11404. end;
  11405. end;
  11406. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11407. begin
  11408. { we can skip all instructions not messing with the stack pointer }
  11409. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11410. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11411. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11412. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11413. ({(taicpu(hp1).ops=0) or }
  11414. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11415. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11416. ) and }
  11417. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11418. )
  11419. ) do
  11420. GetNextInstruction(hp1,hp1);
  11421. Result:=assigned(hp1);
  11422. end;
  11423. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11424. var
  11425. hp1, hp2, hp3, hp4, hp5: tai;
  11426. begin
  11427. Result:=false;
  11428. hp5:=nil;
  11429. { replace
  11430. leal(q) x(<stackpointer>),<stackpointer>
  11431. call procname
  11432. leal(q) -x(<stackpointer>),<stackpointer>
  11433. ret
  11434. by
  11435. jmp procname
  11436. but do it only on level 4 because it destroys stack back traces
  11437. }
  11438. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11439. MatchOpType(taicpu(p),top_ref,top_reg) and
  11440. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11441. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11442. { the -8 or -24 are not required, but bail out early if possible,
  11443. higher values are unlikely }
  11444. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11445. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11446. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11447. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11448. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11449. GetNextInstruction(p, hp1) and
  11450. { Take a copy of hp1 }
  11451. SetAndTest(hp1, hp4) and
  11452. { trick to skip label }
  11453. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11454. SkipSimpleInstructions(hp1) and
  11455. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11456. GetNextInstruction(hp1, hp2) and
  11457. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11458. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11459. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11460. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11461. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11462. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11463. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11464. { Segment register will be NR_NO }
  11465. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11466. GetNextInstruction(hp2, hp3) and
  11467. { trick to skip label }
  11468. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11469. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11470. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11471. SetAndTest(hp3,hp5) and
  11472. GetNextInstruction(hp3,hp3) and
  11473. MatchInstruction(hp3,A_RET,[S_NO])
  11474. )
  11475. ) and
  11476. (taicpu(hp3).ops=0) then
  11477. begin
  11478. taicpu(hp1).opcode := A_JMP;
  11479. taicpu(hp1).is_jmp := true;
  11480. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11481. RemoveCurrentP(p, hp4);
  11482. RemoveInstruction(hp2);
  11483. RemoveInstruction(hp3);
  11484. if Assigned(hp5) then
  11485. begin
  11486. AsmL.Remove(hp5);
  11487. ASmL.InsertBefore(hp5,hp1)
  11488. end;
  11489. Result:=true;
  11490. end;
  11491. end;
  11492. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11493. {$ifdef x86_64}
  11494. var
  11495. hp1, hp2, hp3, hp4, hp5: tai;
  11496. {$endif x86_64}
  11497. begin
  11498. Result:=false;
  11499. {$ifdef x86_64}
  11500. hp5:=nil;
  11501. { replace
  11502. push %rax
  11503. call procname
  11504. pop %rcx
  11505. ret
  11506. by
  11507. jmp procname
  11508. but do it only on level 4 because it destroys stack back traces
  11509. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11510. for all supported calling conventions
  11511. }
  11512. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11513. MatchOpType(taicpu(p),top_reg) and
  11514. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11515. GetNextInstruction(p, hp1) and
  11516. { Take a copy of hp1 }
  11517. SetAndTest(hp1, hp4) and
  11518. { trick to skip label }
  11519. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11520. SkipSimpleInstructions(hp1) and
  11521. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11522. GetNextInstruction(hp1, hp2) and
  11523. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11524. MatchOpType(taicpu(hp2),top_reg) and
  11525. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11526. GetNextInstruction(hp2, hp3) and
  11527. { trick to skip label }
  11528. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11529. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11530. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11531. SetAndTest(hp3,hp5) and
  11532. GetNextInstruction(hp3,hp3) and
  11533. MatchInstruction(hp3,A_RET,[S_NO])
  11534. )
  11535. ) and
  11536. (taicpu(hp3).ops=0) then
  11537. begin
  11538. taicpu(hp1).opcode := A_JMP;
  11539. taicpu(hp1).is_jmp := true;
  11540. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11541. RemoveCurrentP(p, hp4);
  11542. RemoveInstruction(hp2);
  11543. RemoveInstruction(hp3);
  11544. if Assigned(hp5) then
  11545. begin
  11546. AsmL.Remove(hp5);
  11547. ASmL.InsertBefore(hp5,hp1)
  11548. end;
  11549. Result:=true;
  11550. end;
  11551. {$endif x86_64}
  11552. end;
  11553. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11554. var
  11555. Value, RegName: string;
  11556. begin
  11557. Result:=false;
  11558. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11559. begin
  11560. case taicpu(p).oper[0]^.val of
  11561. 0:
  11562. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11563. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11564. begin
  11565. { change "mov $0,%reg" into "xor %reg,%reg" }
  11566. taicpu(p).opcode := A_XOR;
  11567. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11568. Result := True;
  11569. {$ifdef x86_64}
  11570. end
  11571. else if (taicpu(p).opsize = S_Q) then
  11572. begin
  11573. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11574. { The actual optimization }
  11575. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11576. taicpu(p).changeopsize(S_L);
  11577. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11578. Result := True;
  11579. end;
  11580. $1..$FFFFFFFF:
  11581. begin
  11582. { Code size reduction by J. Gareth "Kit" Moreton }
  11583. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11584. case taicpu(p).opsize of
  11585. S_Q:
  11586. begin
  11587. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11588. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11589. { The actual optimization }
  11590. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11591. taicpu(p).changeopsize(S_L);
  11592. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11593. Result := True;
  11594. end;
  11595. else
  11596. { Do nothing };
  11597. end;
  11598. {$endif x86_64}
  11599. end;
  11600. -1:
  11601. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11602. if (cs_opt_size in current_settings.optimizerswitches) and
  11603. (taicpu(p).opsize <> S_B) and
  11604. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11605. begin
  11606. { change "mov $-1,%reg" into "or $-1,%reg" }
  11607. { NOTES:
  11608. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11609. - This operation creates a false dependency on the register, so only do it when optimising for size
  11610. - 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
  11611. }
  11612. taicpu(p).opcode := A_OR;
  11613. Result := True;
  11614. end;
  11615. else
  11616. { Do nothing };
  11617. end;
  11618. end;
  11619. end;
  11620. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11621. var
  11622. hp1: tai;
  11623. begin
  11624. { Detect:
  11625. andw x, %ax (0 <= x < $8000)
  11626. ...
  11627. movzwl %ax,%eax
  11628. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11629. }
  11630. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11631. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11632. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11633. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11634. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11635. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11636. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11637. begin
  11638. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11639. taicpu(hp1).opcode := A_CWDE;
  11640. taicpu(hp1).clearop(0);
  11641. taicpu(hp1).clearop(1);
  11642. taicpu(hp1).ops := 0;
  11643. { A change was made, but not with p, so move forward 1 }
  11644. p := tai(p.Next);
  11645. Result := True;
  11646. end;
  11647. end;
  11648. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11649. begin
  11650. Result := False;
  11651. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11652. Exit;
  11653. { Convert:
  11654. movswl %ax,%eax -> cwtl
  11655. movslq %eax,%rax -> cdqe
  11656. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11657. refer to the same opcode and depends only on the assembler's
  11658. current operand-size attribute. [Kit]
  11659. }
  11660. with taicpu(p) do
  11661. case opsize of
  11662. S_WL:
  11663. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11664. begin
  11665. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11666. opcode := A_CWDE;
  11667. clearop(0);
  11668. clearop(1);
  11669. ops := 0;
  11670. Result := True;
  11671. end;
  11672. {$ifdef x86_64}
  11673. S_LQ:
  11674. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11675. begin
  11676. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11677. opcode := A_CDQE;
  11678. clearop(0);
  11679. clearop(1);
  11680. ops := 0;
  11681. Result := True;
  11682. end;
  11683. {$endif x86_64}
  11684. else
  11685. ;
  11686. end;
  11687. end;
  11688. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11689. var
  11690. hp1: tai;
  11691. begin
  11692. { Detect:
  11693. shr x, %ax (x > 0)
  11694. ...
  11695. movzwl %ax,%eax
  11696. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11697. }
  11698. Result := False;
  11699. if MatchOpType(taicpu(p), top_const, top_reg) and
  11700. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11701. (taicpu(p).oper[0]^.val > 0) and
  11702. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11703. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11704. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11705. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11706. begin
  11707. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11708. taicpu(hp1).opcode := A_CWDE;
  11709. taicpu(hp1).clearop(0);
  11710. taicpu(hp1).clearop(1);
  11711. taicpu(hp1).ops := 0;
  11712. { A change was made, but not with p, so move forward 1 }
  11713. p := tai(p.Next);
  11714. Result := True;
  11715. end;
  11716. end;
  11717. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11718. var
  11719. hp1, hp2: tai;
  11720. Opposite, SecondOpposite: TAsmOp;
  11721. NewCond: TAsmCond;
  11722. begin
  11723. Result := False;
  11724. { Change:
  11725. add/sub 128,(dest)
  11726. To:
  11727. sub/add -128,(dest)
  11728. This generaally takes fewer bytes to encode because -128 can be stored
  11729. in a signed byte, whereas +128 cannot.
  11730. }
  11731. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11732. begin
  11733. if taicpu(p).opcode = A_ADD then
  11734. Opposite := A_SUB
  11735. else
  11736. Opposite := A_ADD;
  11737. { Be careful if the flags are in use, because the CF flag inverts
  11738. when changing from ADD to SUB and vice versa }
  11739. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11740. GetNextInstruction(p, hp1) then
  11741. begin
  11742. TransferUsedRegs(TmpUsedRegs);
  11743. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11744. hp2 := hp1;
  11745. { Scan ahead to check if everything's safe }
  11746. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11747. begin
  11748. if (hp1.typ <> ait_instruction) then
  11749. { Probably unsafe since the flags are still in use }
  11750. Exit;
  11751. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11752. { Stop searching at an unconditional jump }
  11753. Break;
  11754. if not
  11755. (
  11756. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11757. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11758. ) and
  11759. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11760. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11761. Exit;
  11762. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11763. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11764. { Move to the next instruction }
  11765. GetNextInstruction(hp1, hp1);
  11766. end;
  11767. while Assigned(hp2) and (hp2 <> hp1) do
  11768. begin
  11769. NewCond := C_None;
  11770. case taicpu(hp2).condition of
  11771. C_A, C_NBE:
  11772. NewCond := C_BE;
  11773. C_B, C_C, C_NAE:
  11774. NewCond := C_AE;
  11775. C_AE, C_NB, C_NC:
  11776. NewCond := C_B;
  11777. C_BE, C_NA:
  11778. NewCond := C_A;
  11779. else
  11780. { No change needed };
  11781. end;
  11782. if NewCond <> C_None then
  11783. begin
  11784. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11785. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11786. taicpu(hp2).condition := NewCond;
  11787. end
  11788. else
  11789. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11790. begin
  11791. { Because of the flipping of the carry bit, to ensure
  11792. the operation remains equivalent, ADC becomes SBB
  11793. and vice versa, and the constant is not-inverted.
  11794. If multiple ADCs or SBBs appear in a row, each one
  11795. changed causes the carry bit to invert, so they all
  11796. need to be flipped }
  11797. if taicpu(hp2).opcode = A_ADC then
  11798. SecondOpposite := A_SBB
  11799. else
  11800. SecondOpposite := A_ADC;
  11801. if taicpu(hp2).oper[0]^.typ <> top_const then
  11802. { Should have broken out of this optimisation already }
  11803. InternalError(2021112901);
  11804. 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]^) + ' -> ' +
  11805. 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);
  11806. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11807. taicpu(hp2).opcode := SecondOpposite;
  11808. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11809. end;
  11810. { Move to the next instruction }
  11811. GetNextInstruction(hp2, hp2);
  11812. end;
  11813. if (hp2 <> hp1) then
  11814. InternalError(2021111501);
  11815. end;
  11816. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11817. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11818. taicpu(p).opcode := Opposite;
  11819. taicpu(p).oper[0]^.val := -128;
  11820. { No further optimisations can be made on this instruction, so move
  11821. onto the next one to save time }
  11822. p := tai(p.Next);
  11823. UpdateUsedRegs(p);
  11824. Result := True;
  11825. Exit;
  11826. end;
  11827. { Detect:
  11828. add/sub %reg2,(dest)
  11829. add/sub x, (dest)
  11830. (dest can be a register or a reference)
  11831. Swap the instructions to minimise a pipeline stall. This reverses the
  11832. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11833. optimisations could be made.
  11834. }
  11835. if (taicpu(p).oper[0]^.typ = top_reg) and
  11836. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11837. (
  11838. (
  11839. (taicpu(p).oper[1]^.typ = top_reg) and
  11840. { We can try searching further ahead if we're writing to a register }
  11841. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11842. ) or
  11843. (
  11844. (taicpu(p).oper[1]^.typ = top_ref) and
  11845. GetNextInstruction(p, hp1)
  11846. )
  11847. ) and
  11848. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11849. (taicpu(hp1).oper[0]^.typ = top_const) and
  11850. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11851. begin
  11852. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11853. TransferUsedRegs(TmpUsedRegs);
  11854. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11855. hp2 := p;
  11856. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11857. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11858. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11859. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11860. begin
  11861. asml.remove(hp1);
  11862. asml.InsertBefore(hp1, p);
  11863. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11864. Result := True;
  11865. end;
  11866. end;
  11867. end;
  11868. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11869. begin
  11870. Result:=false;
  11871. { change "cmp $0, %reg" to "test %reg, %reg" }
  11872. if MatchOpType(taicpu(p),top_const,top_reg) and
  11873. (taicpu(p).oper[0]^.val = 0) then
  11874. begin
  11875. taicpu(p).opcode := A_TEST;
  11876. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11877. Result:=true;
  11878. end;
  11879. end;
  11880. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11881. var
  11882. IsTestConstX : Boolean;
  11883. hp1,hp2 : tai;
  11884. begin
  11885. Result:=false;
  11886. { removes the line marked with (x) from the sequence
  11887. and/or/xor/add/sub/... $x, %y
  11888. test/or %y, %y | test $-1, %y (x)
  11889. j(n)z _Label
  11890. as the first instruction already adjusts the ZF
  11891. %y operand may also be a reference }
  11892. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11893. MatchOperand(taicpu(p).oper[0]^,-1);
  11894. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11895. GetLastInstruction(p, hp1) and
  11896. (tai(hp1).typ = ait_instruction) and
  11897. GetNextInstruction(p,hp2) and
  11898. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11899. case taicpu(hp1).opcode Of
  11900. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11901. { These two instructions set the zero flag if the result is zero }
  11902. A_POPCNT, A_LZCNT:
  11903. begin
  11904. if (
  11905. { With POPCNT, an input of zero will set the zero flag
  11906. because the population count of zero is zero }
  11907. (taicpu(hp1).opcode = A_POPCNT) and
  11908. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11909. (
  11910. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11911. { Faster than going through the second half of the 'or'
  11912. condition below }
  11913. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11914. )
  11915. ) or (
  11916. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11917. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11918. { and in case of carry for A(E)/B(E)/C/NC }
  11919. (
  11920. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11921. (
  11922. (taicpu(hp1).opcode <> A_ADD) and
  11923. (taicpu(hp1).opcode <> A_SUB) and
  11924. (taicpu(hp1).opcode <> A_LZCNT)
  11925. )
  11926. )
  11927. ) then
  11928. begin
  11929. RemoveCurrentP(p, hp2);
  11930. Result:=true;
  11931. Exit;
  11932. end;
  11933. end;
  11934. A_SHL, A_SAL, A_SHR, A_SAR:
  11935. begin
  11936. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11937. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11938. { therefore, it's only safe to do this optimization for }
  11939. { shifts by a (nonzero) constant }
  11940. (taicpu(hp1).oper[0]^.typ = top_const) and
  11941. (taicpu(hp1).oper[0]^.val <> 0) and
  11942. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11943. { and in case of carry for A(E)/B(E)/C/NC }
  11944. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11945. begin
  11946. RemoveCurrentP(p, hp2);
  11947. Result:=true;
  11948. Exit;
  11949. end;
  11950. end;
  11951. A_DEC, A_INC, A_NEG:
  11952. begin
  11953. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11954. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11955. { and in case of carry for A(E)/B(E)/C/NC }
  11956. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11957. begin
  11958. RemoveCurrentP(p, hp2);
  11959. Result:=true;
  11960. Exit;
  11961. end;
  11962. end
  11963. else
  11964. ;
  11965. end; { case }
  11966. { change "test $-1,%reg" into "test %reg,%reg" }
  11967. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11968. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11969. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11970. if MatchInstruction(p, A_OR, []) and
  11971. { Can only match if they're both registers }
  11972. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11973. begin
  11974. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11975. taicpu(p).opcode := A_TEST;
  11976. { No need to set Result to True, as we've done all the optimisations we can }
  11977. end;
  11978. end;
  11979. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11980. var
  11981. hp1,hp3 : tai;
  11982. {$ifndef x86_64}
  11983. hp2 : taicpu;
  11984. {$endif x86_64}
  11985. begin
  11986. Result:=false;
  11987. hp3:=nil;
  11988. {$ifndef x86_64}
  11989. { don't do this on modern CPUs, this really hurts them due to
  11990. broken call/ret pairing }
  11991. if (current_settings.optimizecputype < cpu_Pentium2) and
  11992. not(cs_create_pic in current_settings.moduleswitches) and
  11993. GetNextInstruction(p, hp1) and
  11994. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11995. MatchOpType(taicpu(hp1),top_ref) and
  11996. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11997. begin
  11998. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11999. InsertLLItem(p.previous, p, hp2);
  12000. taicpu(p).opcode := A_JMP;
  12001. taicpu(p).is_jmp := true;
  12002. RemoveInstruction(hp1);
  12003. Result:=true;
  12004. end
  12005. else
  12006. {$endif x86_64}
  12007. { replace
  12008. call procname
  12009. ret
  12010. by
  12011. jmp procname
  12012. but do it only on level 4 because it destroys stack back traces
  12013. else if the subroutine is marked as no return, remove the ret
  12014. }
  12015. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12016. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12017. GetNextInstruction(p, hp1) and
  12018. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12019. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12020. SetAndTest(hp1,hp3) and
  12021. GetNextInstruction(hp1,hp1) and
  12022. MatchInstruction(hp1,A_RET,[S_NO])
  12023. )
  12024. ) and
  12025. (taicpu(hp1).ops=0) then
  12026. begin
  12027. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12028. { we might destroy stack alignment here if we do not do a call }
  12029. (target_info.stackalign<=sizeof(SizeUInt)) then
  12030. begin
  12031. taicpu(p).opcode := A_JMP;
  12032. taicpu(p).is_jmp := true;
  12033. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12034. end
  12035. else
  12036. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12037. RemoveInstruction(hp1);
  12038. if Assigned(hp3) then
  12039. begin
  12040. AsmL.Remove(hp3);
  12041. AsmL.InsertBefore(hp3,p)
  12042. end;
  12043. Result:=true;
  12044. end;
  12045. end;
  12046. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12047. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12048. begin
  12049. case OpSize of
  12050. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12051. Result := (Val <= $FF) and (Val >= -128);
  12052. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12053. Result := (Val <= $FFFF) and (Val >= -32768);
  12054. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12055. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12056. else
  12057. Result := True;
  12058. end;
  12059. end;
  12060. var
  12061. hp1, hp2 : tai;
  12062. SizeChange: Boolean;
  12063. PreMessage: string;
  12064. begin
  12065. Result := False;
  12066. if (taicpu(p).oper[0]^.typ = top_reg) and
  12067. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12068. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12069. begin
  12070. { Change (using movzbl %al,%eax as an example):
  12071. movzbl %al, %eax movzbl %al, %eax
  12072. cmpl x, %eax testl %eax,%eax
  12073. To:
  12074. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12075. movzbl %al, %eax movzbl %al, %eax
  12076. Smaller instruction and minimises pipeline stall as the CPU
  12077. doesn't have to wait for the register to get zero-extended. [Kit]
  12078. Also allow if the smaller of the two registers is being checked,
  12079. as this still removes the false dependency.
  12080. }
  12081. if
  12082. (
  12083. (
  12084. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12085. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12086. ) or (
  12087. { If MatchOperand returns True, they must both be registers }
  12088. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12089. )
  12090. ) and
  12091. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12092. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12093. begin
  12094. 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);
  12095. asml.Remove(hp1);
  12096. asml.InsertBefore(hp1, p);
  12097. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12098. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12099. begin
  12100. taicpu(hp1).opcode := A_TEST;
  12101. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12102. end;
  12103. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12104. case taicpu(p).opsize of
  12105. S_BW, S_BL:
  12106. begin
  12107. SizeChange := taicpu(hp1).opsize <> S_B;
  12108. taicpu(hp1).changeopsize(S_B);
  12109. end;
  12110. S_WL:
  12111. begin
  12112. SizeChange := taicpu(hp1).opsize <> S_W;
  12113. taicpu(hp1).changeopsize(S_W);
  12114. end
  12115. else
  12116. InternalError(2020112701);
  12117. end;
  12118. UpdateUsedRegs(tai(p.Next));
  12119. { Check if the register is used aferwards - if not, we can
  12120. remove the movzx instruction completely }
  12121. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12122. begin
  12123. { Hp1 is a better position than p for debugging purposes }
  12124. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12125. RemoveCurrentp(p, hp1);
  12126. Result := True;
  12127. end;
  12128. if SizeChange then
  12129. DebugMsg(SPeepholeOptimization + PreMessage +
  12130. 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)
  12131. else
  12132. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12133. Exit;
  12134. end;
  12135. { Change (using movzwl %ax,%eax as an example):
  12136. movzwl %ax, %eax
  12137. movb %al, (dest) (Register is smaller than read register in movz)
  12138. To:
  12139. movb %al, (dest) (Move one back to avoid a false dependency)
  12140. movzwl %ax, %eax
  12141. }
  12142. if (taicpu(hp1).opcode = A_MOV) and
  12143. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12144. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12145. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12146. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12147. begin
  12148. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12149. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12150. asml.Remove(hp1);
  12151. asml.InsertBefore(hp1, p);
  12152. if taicpu(hp1).oper[1]^.typ = top_reg then
  12153. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12154. { Check if the register is used aferwards - if not, we can
  12155. remove the movzx instruction completely }
  12156. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12157. begin
  12158. { Hp1 is a better position than p for debugging purposes }
  12159. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12160. RemoveCurrentp(p, hp1);
  12161. Result := True;
  12162. end;
  12163. Exit;
  12164. end;
  12165. end;
  12166. end;
  12167. {$ifdef x86_64}
  12168. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12169. var
  12170. PreMessage, RegName: string;
  12171. begin
  12172. { Code size reduction by J. Gareth "Kit" Moreton }
  12173. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12174. as this removes the REX prefix }
  12175. Result := False;
  12176. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12177. Exit;
  12178. if taicpu(p).oper[0]^.typ <> top_reg then
  12179. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12180. InternalError(2018011500);
  12181. case taicpu(p).opsize of
  12182. S_Q:
  12183. begin
  12184. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12185. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12186. { The actual optimization }
  12187. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12188. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12189. taicpu(p).changeopsize(S_L);
  12190. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12191. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12192. end;
  12193. else
  12194. ;
  12195. end;
  12196. end;
  12197. {$endif}
  12198. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12199. var
  12200. XReg: TRegister;
  12201. begin
  12202. Result := False;
  12203. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12204. Smaller encoding and slightly faster on some platforms (also works for
  12205. ZMM-sized registers) }
  12206. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12207. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12208. begin
  12209. XReg := taicpu(p).oper[0]^.reg;
  12210. if (taicpu(p).oper[1]^.reg = XReg) then
  12211. begin
  12212. taicpu(p).changeopsize(S_XMM);
  12213. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12214. if (cs_opt_size in current_settings.optimizerswitches) then
  12215. begin
  12216. { Change input registers to %xmm0 to reduce size. Note that
  12217. there's a risk of a false dependency doing this, so only
  12218. optimise for size here }
  12219. XReg := NR_XMM0;
  12220. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12221. end
  12222. else
  12223. begin
  12224. setsubreg(XReg, R_SUBMMX);
  12225. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12226. end;
  12227. taicpu(p).oper[0]^.reg := XReg;
  12228. taicpu(p).oper[1]^.reg := XReg;
  12229. Result := True;
  12230. end;
  12231. end;
  12232. end;
  12233. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12234. var
  12235. OperIdx: Integer;
  12236. begin
  12237. for OperIdx := 0 to p.ops - 1 do
  12238. if p.oper[OperIdx]^.typ = top_ref then
  12239. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12240. end;
  12241. end.