aoptx86.pas 547 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function PrePeepholeOptSxx(var p : tai) : boolean;
  108. function PrePeepholeOptIMUL(var p : tai) : boolean;
  109. function PrePeepholeOptAND(var p : tai) : boolean;
  110. function OptPass1Test(var p: tai): boolean;
  111. function OptPass1Add(var p: tai): boolean;
  112. function OptPass1AND(var p : tai) : boolean;
  113. function OptPass1_V_MOVAP(var p : tai) : boolean;
  114. function OptPass1VOP(var p : tai) : boolean;
  115. function OptPass1MOV(var p : tai) : boolean;
  116. function OptPass1Movx(var p : tai) : boolean;
  117. function OptPass1MOVXX(var p : tai) : boolean;
  118. function OptPass1OP(var p : tai) : boolean;
  119. function OptPass1LEA(var p : tai) : boolean;
  120. function OptPass1Sub(var p : tai) : boolean;
  121. function OptPass1SHLSAL(var p : tai) : boolean;
  122. function OptPass1FSTP(var p : tai) : boolean;
  123. function OptPass1FLD(var p : tai) : boolean;
  124. function OptPass1Cmp(var p : tai) : boolean;
  125. function OptPass1PXor(var p : tai) : boolean;
  126. function OptPass1VPXor(var p: tai): boolean;
  127. function OptPass1Imul(var p : tai) : boolean;
  128. function OptPass1Jcc(var p : tai) : boolean;
  129. function OptPass1SHXX(var p: tai): boolean;
  130. function OptPass1VMOVDQ(var p: tai): Boolean;
  131. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  132. function OptPass2Movx(var p : tai): Boolean;
  133. function OptPass2MOV(var p : tai) : boolean;
  134. function OptPass2Imul(var p : tai) : boolean;
  135. function OptPass2Jmp(var p : tai) : boolean;
  136. function OptPass2Jcc(var p : tai) : boolean;
  137. function OptPass2Lea(var p: tai): Boolean;
  138. function OptPass2SUB(var p: tai): Boolean;
  139. function OptPass2ADD(var p : tai): Boolean;
  140. function OptPass2SETcc(var p : tai) : boolean;
  141. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  142. function PostPeepholeOptMov(var p : tai) : Boolean;
  143. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  144. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  145. function PostPeepholeOptXor(var p : tai) : Boolean;
  146. {$endif x86_64}
  147. function PostPeepholeOptAnd(var p : tai) : boolean;
  148. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  149. function PostPeepholeOptCmp(var p : tai) : Boolean;
  150. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  151. function PostPeepholeOptCall(var p : tai) : Boolean;
  152. function PostPeepholeOptLea(var p : tai) : Boolean;
  153. function PostPeepholeOptPush(var p: tai): Boolean;
  154. function PostPeepholeOptShr(var p : tai) : boolean;
  155. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  156. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  157. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  158. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  159. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  160. { Processor-dependent reference optimisation }
  161. class procedure OptimizeRefs(var p: taicpu); static;
  162. end;
  163. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  167. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  168. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  169. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  170. {$if max_operands>2}
  171. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  172. {$endif max_operands>2}
  173. function RefsEqual(const r1, r2: treference): boolean;
  174. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  175. { returns true, if ref is a reference using only the registers passed as base and index
  176. and having an offset }
  177. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  178. implementation
  179. uses
  180. cutils,verbose,
  181. systems,
  182. globals,
  183. cpuinfo,
  184. procinfo,
  185. paramgr,
  186. aasmbase,
  187. aoptbase,aoptutils,
  188. symconst,symsym,
  189. cgx86,
  190. itcpugas;
  191. {$ifdef DEBUG_AOPTCPU}
  192. const
  193. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  194. {$else DEBUG_AOPTCPU}
  195. { Empty strings help the optimizer to remove string concatenations that won't
  196. ever appear to the user on release builds. [Kit] }
  197. const
  198. SPeepholeOptimization = '';
  199. {$endif DEBUG_AOPTCPU}
  200. LIST_STEP_SIZE = 4;
  201. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  202. begin
  203. result :=
  204. (instr.typ = ait_instruction) and
  205. (taicpu(instr).opcode = op) and
  206. ((opsize = []) or (taicpu(instr).opsize in opsize));
  207. end;
  208. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  209. begin
  210. result :=
  211. (instr.typ = ait_instruction) and
  212. ((taicpu(instr).opcode = op1) or
  213. (taicpu(instr).opcode = op2)
  214. ) and
  215. ((opsize = []) or (taicpu(instr).opsize in opsize));
  216. end;
  217. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  218. begin
  219. result :=
  220. (instr.typ = ait_instruction) and
  221. ((taicpu(instr).opcode = op1) or
  222. (taicpu(instr).opcode = op2) or
  223. (taicpu(instr).opcode = op3)
  224. ) and
  225. ((opsize = []) or (taicpu(instr).opsize in opsize));
  226. end;
  227. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  228. const opsize : topsizes) : boolean;
  229. var
  230. op : TAsmOp;
  231. begin
  232. result:=false;
  233. if (instr.typ <> ait_instruction) or
  234. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  235. exit;
  236. for op in ops do
  237. begin
  238. if taicpu(instr).opcode = op then
  239. begin
  240. result:=true;
  241. exit;
  242. end;
  243. end;
  244. end;
  245. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  246. begin
  247. result := (oper.typ = top_reg) and (oper.reg = reg);
  248. end;
  249. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  250. begin
  251. result := (oper.typ = top_const) and (oper.val = a);
  252. end;
  253. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  254. begin
  255. result := oper1.typ = oper2.typ;
  256. if result then
  257. case oper1.typ of
  258. top_const:
  259. Result:=oper1.val = oper2.val;
  260. top_reg:
  261. Result:=oper1.reg = oper2.reg;
  262. top_ref:
  263. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  264. else
  265. internalerror(2013102801);
  266. end
  267. end;
  268. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  269. begin
  270. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  271. if result then
  272. case oper1.typ of
  273. top_const:
  274. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  275. top_reg:
  276. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  277. top_ref:
  278. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  279. else
  280. internalerror(2020052401);
  281. end
  282. end;
  283. function RefsEqual(const r1, r2: treference): boolean;
  284. begin
  285. RefsEqual :=
  286. (r1.offset = r2.offset) and
  287. (r1.segment = r2.segment) and (r1.base = r2.base) and
  288. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  289. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  290. (r1.relsymbol = r2.relsymbol) and
  291. (r1.volatility=[]) and
  292. (r2.volatility=[]);
  293. end;
  294. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  295. begin
  296. Result:=(ref.offset=0) and
  297. (ref.scalefactor in [0,1]) and
  298. (ref.segment=NR_NO) and
  299. (ref.symbol=nil) and
  300. (ref.relsymbol=nil) and
  301. ((base=NR_INVALID) or
  302. (ref.base=base)) and
  303. ((index=NR_INVALID) or
  304. (ref.index=index)) and
  305. (ref.volatility=[]);
  306. end;
  307. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  308. begin
  309. Result:=(ref.scalefactor in [0,1]) and
  310. (ref.segment=NR_NO) and
  311. (ref.symbol=nil) and
  312. (ref.relsymbol=nil) and
  313. ((base=NR_INVALID) or
  314. (ref.base=base)) and
  315. ((index=NR_INVALID) or
  316. (ref.index=index)) and
  317. (ref.volatility=[]);
  318. end;
  319. function InstrReadsFlags(p: tai): boolean;
  320. begin
  321. InstrReadsFlags := true;
  322. case p.typ of
  323. ait_instruction:
  324. if InsProp[taicpu(p).opcode].Ch*
  325. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  326. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  327. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  328. exit;
  329. ait_label:
  330. exit;
  331. else
  332. ;
  333. end;
  334. InstrReadsFlags := false;
  335. end;
  336. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  337. begin
  338. Next:=Current;
  339. repeat
  340. Result:=GetNextInstruction(Next,Next);
  341. until not (Result) or
  342. not(cs_opt_level3 in current_settings.optimizerswitches) or
  343. (Next.typ<>ait_instruction) or
  344. RegInInstruction(reg,Next) or
  345. is_calljmp(taicpu(Next).opcode);
  346. end;
  347. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  348. begin
  349. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  350. Next := Current;
  351. repeat
  352. Result := GetNextInstruction(Next,Next);
  353. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  354. if is_calljmpuncondret(taicpu(Next).opcode) then
  355. begin
  356. Result := False;
  357. Exit;
  358. end
  359. else
  360. CrossJump := True;
  361. until not Result or
  362. not (cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ <> ait_instruction) or
  364. RegInInstruction(reg,Next);
  365. end;
  366. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  367. begin
  368. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  369. begin
  370. Result:=GetNextInstruction(Current,Next);
  371. exit;
  372. end;
  373. Next:=tai(Current.Next);
  374. Result:=false;
  375. while assigned(Next) do
  376. begin
  377. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  378. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  379. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  380. exit
  381. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  382. begin
  383. Result:=true;
  384. exit;
  385. end;
  386. Next:=tai(Next.Next);
  387. end;
  388. end;
  389. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  390. begin
  391. Result:=RegReadByInstruction(reg,hp);
  392. end;
  393. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  394. var
  395. p: taicpu;
  396. opcount: longint;
  397. begin
  398. RegReadByInstruction := false;
  399. if hp.typ <> ait_instruction then
  400. exit;
  401. p := taicpu(hp);
  402. case p.opcode of
  403. A_CALL:
  404. regreadbyinstruction := true;
  405. A_IMUL:
  406. case p.ops of
  407. 1:
  408. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  409. (
  410. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  411. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  412. );
  413. 2,3:
  414. regReadByInstruction :=
  415. reginop(reg,p.oper[0]^) or
  416. reginop(reg,p.oper[1]^);
  417. else
  418. InternalError(2019112801);
  419. end;
  420. A_MUL:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  425. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  426. );
  427. end;
  428. A_IDIV,A_DIV:
  429. begin
  430. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  431. (
  432. (getregtype(reg)=R_INTREGISTER) and
  433. (
  434. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  435. )
  436. );
  437. end;
  438. else
  439. begin
  440. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  441. begin
  442. RegReadByInstruction := false;
  443. exit;
  444. end;
  445. for opcount := 0 to p.ops-1 do
  446. if (p.oper[opCount]^.typ = top_ref) and
  447. RegInRef(reg,p.oper[opcount]^.ref^) then
  448. begin
  449. RegReadByInstruction := true;
  450. exit
  451. end;
  452. { special handling for SSE MOVSD }
  453. if (p.opcode=A_MOVSD) and (p.ops>0) then
  454. begin
  455. if p.ops<>2 then
  456. internalerror(2017042702);
  457. regReadByInstruction := reginop(reg,p.oper[0]^) or
  458. (
  459. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  460. );
  461. exit;
  462. end;
  463. with insprop[p.opcode] do
  464. begin
  465. case getregtype(reg) of
  466. R_INTREGISTER:
  467. begin
  468. case getsupreg(reg) of
  469. RS_EAX:
  470. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ECX:
  476. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EDX:
  482. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_EBX:
  488. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_ESP:
  494. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. RS_EBP:
  500. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  501. begin
  502. RegReadByInstruction := true;
  503. exit
  504. end;
  505. RS_ESI:
  506. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  507. begin
  508. RegReadByInstruction := true;
  509. exit
  510. end;
  511. RS_EDI:
  512. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  513. begin
  514. RegReadByInstruction := true;
  515. exit
  516. end;
  517. end;
  518. end;
  519. R_MMREGISTER:
  520. begin
  521. case getsupreg(reg) of
  522. RS_XMM0:
  523. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  524. begin
  525. RegReadByInstruction := true;
  526. exit
  527. end;
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  534. begin
  535. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  536. begin
  537. case p.condition of
  538. C_A,C_NBE, { CF=0 and ZF=0 }
  539. C_BE,C_NA: { CF=1 or ZF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  541. C_AE,C_NB,C_NC, { CF=0 }
  542. C_B,C_NAE,C_C: { CF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  544. C_NE,C_NZ, { ZF=0 }
  545. C_E,C_Z: { ZF=1 }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  547. C_G,C_NLE, { ZF=0 and SF=OF }
  548. C_LE,C_NG: { ZF=1 or SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_GE,C_NL, { SF=OF }
  551. C_L,C_NGE: { SF<>OF }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  553. C_NO, { OF=0 }
  554. C_O: { OF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  556. C_NP,C_PO, { PF=0 }
  557. C_P,C_PE: { PF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  559. C_NS, { SF=0 }
  560. C_S: { SF=1 }
  561. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  562. else
  563. internalerror(2017042701);
  564. end;
  565. if RegReadByInstruction then
  566. exit;
  567. end;
  568. case getsubreg(reg) of
  569. R_SUBW,R_SUBD,R_SUBQ:
  570. RegReadByInstruction :=
  571. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  572. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  573. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  574. R_SUBFLAGCARRY:
  575. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  576. R_SUBFLAGPARITY:
  577. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  578. R_SUBFLAGAUXILIARY:
  579. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  580. R_SUBFLAGZERO:
  581. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  582. R_SUBFLAGSIGN:
  583. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  584. R_SUBFLAGOVERFLOW:
  585. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  586. R_SUBFLAGINTERRUPT:
  587. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  588. R_SUBFLAGDIRECTION:
  589. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  590. else
  591. internalerror(2017042601);
  592. end;
  593. exit;
  594. end;
  595. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  596. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  597. (p.oper[0]^.reg=p.oper[1]^.reg) then
  598. exit;
  599. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  615. begin
  616. RegReadByInstruction := true;
  617. exit
  618. end;
  619. end;
  620. end;
  621. end;
  622. end;
  623. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  624. begin
  625. result:=false;
  626. if p1.typ<>ait_instruction then
  627. exit;
  628. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  629. exit(true);
  630. if (getregtype(reg)=R_INTREGISTER) and
  631. { change information for xmm movsd are not correct }
  632. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  633. begin
  634. case getsupreg(reg) of
  635. { RS_EAX = RS_RAX on x86-64 }
  636. RS_EAX:
  637. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. RS_ECX:
  639. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. RS_EDX:
  641. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. RS_EBX:
  643. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. RS_ESP:
  645. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. RS_EBP:
  647. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. RS_ESI:
  649. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. RS_EDI:
  651. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. else
  653. ;
  654. end;
  655. if result then
  656. exit;
  657. end
  658. else if getregtype(reg)=R_MMREGISTER then
  659. begin
  660. case getsupreg(reg) of
  661. RS_XMM0:
  662. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  663. else
  664. ;
  665. end;
  666. if result then
  667. exit;
  668. end
  669. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  670. begin
  671. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  672. exit(true);
  673. case getsubreg(reg) of
  674. R_SUBFLAGCARRY:
  675. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  676. R_SUBFLAGPARITY:
  677. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  678. R_SUBFLAGAUXILIARY:
  679. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  680. R_SUBFLAGZERO:
  681. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  682. R_SUBFLAGSIGN:
  683. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  684. R_SUBFLAGOVERFLOW:
  685. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  686. R_SUBFLAGINTERRUPT:
  687. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  688. R_SUBFLAGDIRECTION:
  689. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  690. R_SUBW,R_SUBD,R_SUBQ:
  691. { Everything except the direction bits }
  692. Result:=
  693. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  694. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  695. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  696. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  697. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  698. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  699. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. else
  701. ;
  702. end;
  703. if result then
  704. exit;
  705. end
  706. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  707. exit(true);
  708. Result:=inherited RegInInstruction(Reg, p1);
  709. end;
  710. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  711. const
  712. WriteOps: array[0..3] of set of TInsChange =
  713. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  714. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  715. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  716. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  717. var
  718. OperIdx: Integer;
  719. begin
  720. Result := False;
  721. if p1.typ <> ait_instruction then
  722. exit;
  723. with insprop[taicpu(p1).opcode] do
  724. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  725. begin
  726. case getsubreg(reg) of
  727. R_SUBW,R_SUBD,R_SUBQ:
  728. Result :=
  729. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  730. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  731. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  732. R_SUBFLAGCARRY:
  733. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  734. R_SUBFLAGPARITY:
  735. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  736. R_SUBFLAGAUXILIARY:
  737. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  738. R_SUBFLAGZERO:
  739. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  740. R_SUBFLAGSIGN:
  741. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  742. R_SUBFLAGOVERFLOW:
  743. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  744. R_SUBFLAGINTERRUPT:
  745. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  746. R_SUBFLAGDIRECTION:
  747. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  748. else
  749. internalerror(2017042602);
  750. end;
  751. exit;
  752. end;
  753. case taicpu(p1).opcode of
  754. A_CALL:
  755. { We could potentially set Result to False if the register in
  756. question is non-volatile for the subroutine's calling convention,
  757. but this would require detecting the calling convention in use and
  758. also assuming that the routine doesn't contain malformed assembly
  759. language, for example... so it could only be done under -O4 as it
  760. would be considered a side-effect. [Kit] }
  761. Result := True;
  762. A_MOVSD:
  763. { special handling for SSE MOVSD }
  764. if (taicpu(p1).ops>0) then
  765. begin
  766. if taicpu(p1).ops<>2 then
  767. internalerror(2017042703);
  768. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  769. end;
  770. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  771. so fix it here (FK)
  772. }
  773. A_VMOVSS,
  774. A_VMOVSD:
  775. begin
  776. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  777. exit;
  778. end;
  779. A_IMUL:
  780. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  781. else
  782. ;
  783. end;
  784. if Result then
  785. exit;
  786. with insprop[taicpu(p1).opcode] do
  787. begin
  788. if getregtype(reg)=R_INTREGISTER then
  789. begin
  790. case getsupreg(reg) of
  791. RS_EAX:
  792. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  793. begin
  794. Result := True;
  795. exit
  796. end;
  797. RS_ECX:
  798. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  799. begin
  800. Result := True;
  801. exit
  802. end;
  803. RS_EDX:
  804. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  805. begin
  806. Result := True;
  807. exit
  808. end;
  809. RS_EBX:
  810. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  811. begin
  812. Result := True;
  813. exit
  814. end;
  815. RS_ESP:
  816. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  817. begin
  818. Result := True;
  819. exit
  820. end;
  821. RS_EBP:
  822. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  823. begin
  824. Result := True;
  825. exit
  826. end;
  827. RS_ESI:
  828. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  829. begin
  830. Result := True;
  831. exit
  832. end;
  833. RS_EDI:
  834. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  835. begin
  836. Result := True;
  837. exit
  838. end;
  839. end;
  840. end;
  841. for OperIdx := 0 to taicpu(p1).ops - 1 do
  842. if (WriteOps[OperIdx]*Ch<>[]) and
  843. { The register doesn't get modified inside a reference }
  844. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  845. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  846. begin
  847. Result := true;
  848. exit
  849. end;
  850. end;
  851. end;
  852. {$ifdef DEBUG_AOPTCPU}
  853. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  854. begin
  855. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  856. end;
  857. function debug_tostr(i: tcgint): string; inline;
  858. begin
  859. Result := tostr(i);
  860. end;
  861. function debug_regname(r: TRegister): string; inline;
  862. begin
  863. Result := '%' + std_regname(r);
  864. end;
  865. { Debug output function - creates a string representation of an operator }
  866. function debug_operstr(oper: TOper): string;
  867. begin
  868. case oper.typ of
  869. top_const:
  870. Result := '$' + debug_tostr(oper.val);
  871. top_reg:
  872. Result := debug_regname(oper.reg);
  873. top_ref:
  874. begin
  875. if oper.ref^.offset <> 0 then
  876. Result := debug_tostr(oper.ref^.offset) + '('
  877. else
  878. Result := '(';
  879. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  880. begin
  881. Result := Result + debug_regname(oper.ref^.base);
  882. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  883. Result := Result + ',' + debug_regname(oper.ref^.index);
  884. end
  885. else
  886. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  887. Result := Result + debug_regname(oper.ref^.index);
  888. if (oper.ref^.scalefactor > 1) then
  889. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  890. else
  891. Result := Result + ')';
  892. end;
  893. else
  894. Result := '[UNKNOWN]';
  895. end;
  896. end;
  897. function debug_op2str(opcode: tasmop): string; inline;
  898. begin
  899. Result := std_op2str[opcode];
  900. end;
  901. function debug_opsize2str(opsize: topsize): string; inline;
  902. begin
  903. Result := gas_opsize2str[opsize];
  904. end;
  905. {$else DEBUG_AOPTCPU}
  906. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  907. begin
  908. end;
  909. function debug_tostr(i: tcgint): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_regname(r: TRegister): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. function debug_operstr(oper: TOper): string; inline;
  918. begin
  919. Result := '';
  920. end;
  921. function debug_op2str(opcode: tasmop): string; inline;
  922. begin
  923. Result := '';
  924. end;
  925. function debug_opsize2str(opsize: topsize): string; inline;
  926. begin
  927. Result := '';
  928. end;
  929. {$endif DEBUG_AOPTCPU}
  930. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  931. begin
  932. {$ifdef x86_64}
  933. { Always fine on x86-64 }
  934. Result := True;
  935. {$else x86_64}
  936. Result :=
  937. {$ifdef i8086}
  938. (current_settings.cputype >= cpu_386) and
  939. {$endif i8086}
  940. (
  941. { Always accept if optimising for size }
  942. (cs_opt_size in current_settings.optimizerswitches) or
  943. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  944. (current_settings.optimizecputype >= cpu_Pentium2)
  945. );
  946. {$endif x86_64}
  947. end;
  948. { Attempts to allocate a volatile integer register for use between p and hp,
  949. using AUsedRegs for the current register usage information. Returns NR_NO
  950. if no free register could be found }
  951. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  952. var
  953. RegSet: TCPURegisterSet;
  954. CurrentSuperReg: Integer;
  955. CurrentReg: TRegister;
  956. Currentp: tai;
  957. Breakout: Boolean;
  958. begin
  959. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  960. Result := NR_NO;
  961. RegSet :=
  962. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  963. current_procinfo.saved_regs_int;
  964. for CurrentSuperReg in RegSet do
  965. begin
  966. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  967. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  968. {$if defined(i386) or defined(i8086)}
  969. { If the target size is 8-bit, make sure we can actually encode it }
  970. and (
  971. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  972. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  973. )
  974. {$endif i386 or i8086}
  975. then
  976. begin
  977. Currentp := p;
  978. Breakout := False;
  979. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  980. begin
  981. case Currentp.typ of
  982. ait_instruction:
  983. begin
  984. if RegInInstruction(CurrentReg, Currentp) then
  985. begin
  986. Breakout := True;
  987. Break;
  988. end;
  989. { Cannot allocate across an unconditional jump }
  990. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  991. Exit;
  992. end;
  993. ait_marker:
  994. { Don't try anything more if a marker is hit }
  995. Exit;
  996. ait_regalloc:
  997. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  998. begin
  999. Breakout := True;
  1000. Break;
  1001. end;
  1002. else
  1003. ;
  1004. end;
  1005. end;
  1006. if Breakout then
  1007. { Try the next register }
  1008. Continue;
  1009. { We have a free register available }
  1010. Result := CurrentReg;
  1011. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1012. Exit;
  1013. end;
  1014. end;
  1015. end;
  1016. { Attempts to allocate a volatile MM register for use between p and hp,
  1017. using AUsedRegs for the current register usage information. Returns NR_NO
  1018. if no free register could be found }
  1019. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1020. var
  1021. RegSet: TCPURegisterSet;
  1022. CurrentSuperReg: Integer;
  1023. CurrentReg: TRegister;
  1024. Currentp: tai;
  1025. Breakout: Boolean;
  1026. begin
  1027. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1028. Result := NR_NO;
  1029. RegSet :=
  1030. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1031. current_procinfo.saved_regs_mm;
  1032. for CurrentSuperReg in RegSet do
  1033. begin
  1034. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1035. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1036. begin
  1037. Currentp := p;
  1038. Breakout := False;
  1039. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1040. begin
  1041. case Currentp.typ of
  1042. ait_instruction:
  1043. begin
  1044. if RegInInstruction(CurrentReg, Currentp) then
  1045. begin
  1046. Breakout := True;
  1047. Break;
  1048. end;
  1049. { Cannot allocate across an unconditional jump }
  1050. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1051. Exit;
  1052. end;
  1053. ait_marker:
  1054. { Don't try anything more if a marker is hit }
  1055. Exit;
  1056. ait_regalloc:
  1057. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1058. begin
  1059. Breakout := True;
  1060. Break;
  1061. end;
  1062. else
  1063. ;
  1064. end;
  1065. end;
  1066. if Breakout then
  1067. { Try the next register }
  1068. Continue;
  1069. { We have a free register available }
  1070. Result := CurrentReg;
  1071. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1072. Exit;
  1073. end;
  1074. end;
  1075. end;
  1076. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1077. begin
  1078. if not SuperRegistersEqual(reg1,reg2) then
  1079. exit(false);
  1080. if getregtype(reg1)<>R_INTREGISTER then
  1081. exit(true); {because SuperRegisterEqual is true}
  1082. case getsubreg(reg1) of
  1083. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1084. higher, it preserves the high bits, so the new value depends on
  1085. reg2's previous value. In other words, it is equivalent to doing:
  1086. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1087. R_SUBL:
  1088. exit(getsubreg(reg2)=R_SUBL);
  1089. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1090. higher, it actually does a:
  1091. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1092. R_SUBH:
  1093. exit(getsubreg(reg2)=R_SUBH);
  1094. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1095. bits of reg2:
  1096. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1097. R_SUBW:
  1098. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1099. { a write to R_SUBD always overwrites every other subregister,
  1100. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1101. R_SUBD,
  1102. R_SUBQ:
  1103. exit(true);
  1104. else
  1105. internalerror(2017042801);
  1106. end;
  1107. end;
  1108. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1109. begin
  1110. if not SuperRegistersEqual(reg1,reg2) then
  1111. exit(false);
  1112. if getregtype(reg1)<>R_INTREGISTER then
  1113. exit(true); {because SuperRegisterEqual is true}
  1114. case getsubreg(reg1) of
  1115. R_SUBL:
  1116. exit(getsubreg(reg2)<>R_SUBH);
  1117. R_SUBH:
  1118. exit(getsubreg(reg2)<>R_SUBL);
  1119. R_SUBW,
  1120. R_SUBD,
  1121. R_SUBQ:
  1122. exit(true);
  1123. else
  1124. internalerror(2017042802);
  1125. end;
  1126. end;
  1127. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1128. var
  1129. hp1 : tai;
  1130. l : TCGInt;
  1131. begin
  1132. result:=false;
  1133. { changes the code sequence
  1134. shr/sar const1, x
  1135. shl const2, x
  1136. to
  1137. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1138. if GetNextInstruction(p, hp1) and
  1139. MatchInstruction(hp1,A_SHL,[]) and
  1140. (taicpu(p).oper[0]^.typ = top_const) and
  1141. (taicpu(hp1).oper[0]^.typ = top_const) and
  1142. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1143. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1144. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1145. begin
  1146. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1147. not(cs_opt_size in current_settings.optimizerswitches) then
  1148. begin
  1149. { shr/sar const1, %reg
  1150. shl const2, %reg
  1151. with const1 > const2 }
  1152. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1153. taicpu(hp1).opcode := A_AND;
  1154. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1155. case taicpu(p).opsize Of
  1156. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1157. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1158. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1159. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1160. else
  1161. Internalerror(2017050703)
  1162. end;
  1163. end
  1164. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1165. not(cs_opt_size in current_settings.optimizerswitches) then
  1166. begin
  1167. { shr/sar const1, %reg
  1168. shl const2, %reg
  1169. with const1 < const2 }
  1170. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1171. taicpu(p).opcode := A_AND;
  1172. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1173. case taicpu(p).opsize Of
  1174. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1175. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1176. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1177. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1178. else
  1179. Internalerror(2017050702)
  1180. end;
  1181. end
  1182. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1183. begin
  1184. { shr/sar const1, %reg
  1185. shl const2, %reg
  1186. with const1 = const2 }
  1187. taicpu(p).opcode := A_AND;
  1188. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1189. case taicpu(p).opsize Of
  1190. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1191. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1192. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1193. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1194. else
  1195. Internalerror(2017050701)
  1196. end;
  1197. RemoveInstruction(hp1);
  1198. end;
  1199. end;
  1200. end;
  1201. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1202. var
  1203. opsize : topsize;
  1204. hp1 : tai;
  1205. tmpref : treference;
  1206. ShiftValue : Cardinal;
  1207. BaseValue : TCGInt;
  1208. begin
  1209. result:=false;
  1210. opsize:=taicpu(p).opsize;
  1211. { changes certain "imul const, %reg"'s to lea sequences }
  1212. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1213. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1214. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1215. if (taicpu(p).oper[0]^.val = 1) then
  1216. if (taicpu(p).ops = 2) then
  1217. { remove "imul $1, reg" }
  1218. begin
  1219. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1220. Result := RemoveCurrentP(p);
  1221. end
  1222. else
  1223. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1224. begin
  1225. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1226. InsertLLItem(p.previous, p.next, hp1);
  1227. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1228. p.free;
  1229. p := hp1;
  1230. end
  1231. else if ((taicpu(p).ops <= 2) or
  1232. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1233. not(cs_opt_size in current_settings.optimizerswitches) and
  1234. (not(GetNextInstruction(p, hp1)) or
  1235. not((tai(hp1).typ = ait_instruction) and
  1236. ((taicpu(hp1).opcode=A_Jcc) and
  1237. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1238. begin
  1239. {
  1240. imul X, reg1, reg2 to
  1241. lea (reg1,reg1,Y), reg2
  1242. shl ZZ,reg2
  1243. imul XX, reg1 to
  1244. lea (reg1,reg1,YY), reg1
  1245. shl ZZ,reg2
  1246. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1247. it does not exist as a separate optimization target in FPC though.
  1248. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1249. at most two zeros
  1250. }
  1251. reference_reset(tmpref,1,[]);
  1252. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1253. begin
  1254. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1255. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1256. TmpRef.base := taicpu(p).oper[1]^.reg;
  1257. TmpRef.index := taicpu(p).oper[1]^.reg;
  1258. if not(BaseValue in [3,5,9]) then
  1259. Internalerror(2018110101);
  1260. TmpRef.ScaleFactor := BaseValue-1;
  1261. if (taicpu(p).ops = 2) then
  1262. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1263. else
  1264. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1265. AsmL.InsertAfter(hp1,p);
  1266. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1267. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1268. RemoveCurrentP(p, hp1);
  1269. if ShiftValue>0 then
  1270. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1271. end;
  1272. end;
  1273. end;
  1274. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1275. begin
  1276. Result := False;
  1277. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1278. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1279. begin
  1280. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1281. taicpu(p).opcode := A_MOV;
  1282. Result := True;
  1283. end;
  1284. end;
  1285. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1286. var
  1287. p: taicpu absolute hp;
  1288. i: Integer;
  1289. begin
  1290. Result := False;
  1291. if not assigned(hp) or
  1292. (hp.typ <> ait_instruction) then
  1293. Exit;
  1294. // p := taicpu(hp);
  1295. Prefetch(insprop[p.opcode]);
  1296. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1297. with insprop[p.opcode] do
  1298. begin
  1299. case getsubreg(reg) of
  1300. R_SUBW,R_SUBD,R_SUBQ:
  1301. Result:=
  1302. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1303. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1304. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1305. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1306. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1307. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1308. R_SUBFLAGCARRY:
  1309. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1310. R_SUBFLAGPARITY:
  1311. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1312. R_SUBFLAGAUXILIARY:
  1313. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1314. R_SUBFLAGZERO:
  1315. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1316. R_SUBFLAGSIGN:
  1317. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1318. R_SUBFLAGOVERFLOW:
  1319. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1320. R_SUBFLAGINTERRUPT:
  1321. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1322. R_SUBFLAGDIRECTION:
  1323. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1324. else
  1325. begin
  1326. writeln(getsubreg(reg));
  1327. internalerror(2017050501);
  1328. end;
  1329. end;
  1330. exit;
  1331. end;
  1332. { Handle special cases first }
  1333. case p.opcode of
  1334. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1335. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1336. begin
  1337. Result :=
  1338. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1339. (p.oper[1]^.typ = top_reg) and
  1340. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1341. (
  1342. (p.oper[0]^.typ = top_const) or
  1343. (
  1344. (p.oper[0]^.typ = top_reg) and
  1345. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1346. ) or (
  1347. (p.oper[0]^.typ = top_ref) and
  1348. not RegInRef(reg,p.oper[0]^.ref^)
  1349. )
  1350. );
  1351. end;
  1352. A_MUL, A_IMUL:
  1353. Result :=
  1354. (
  1355. (p.ops=3) and { IMUL only }
  1356. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1357. (
  1358. (
  1359. (p.oper[1]^.typ=top_reg) and
  1360. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1361. ) or (
  1362. (p.oper[1]^.typ=top_ref) and
  1363. not RegInRef(reg,p.oper[1]^.ref^)
  1364. )
  1365. )
  1366. ) or (
  1367. (
  1368. (p.ops=1) and
  1369. (
  1370. (
  1371. (
  1372. (p.oper[0]^.typ=top_reg) and
  1373. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1374. )
  1375. ) or (
  1376. (p.oper[0]^.typ=top_ref) and
  1377. not RegInRef(reg,p.oper[0]^.ref^)
  1378. )
  1379. ) and (
  1380. (
  1381. (p.opsize=S_B) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1383. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1384. ) or (
  1385. (p.opsize=S_W) and
  1386. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1387. ) or (
  1388. (p.opsize=S_L) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1390. {$ifdef x86_64}
  1391. ) or (
  1392. (p.opsize=S_Q) and
  1393. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1394. {$endif x86_64}
  1395. )
  1396. )
  1397. )
  1398. );
  1399. A_CBW:
  1400. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1401. {$ifndef x86_64}
  1402. A_LDS:
  1403. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1404. A_LES:
  1405. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1406. {$endif not x86_64}
  1407. A_LFS:
  1408. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LGS:
  1410. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1411. A_LSS:
  1412. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1413. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1415. A_LODSB:
  1416. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1417. A_LODSW:
  1418. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1419. {$ifdef x86_64}
  1420. A_LODSQ:
  1421. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1422. {$endif x86_64}
  1423. A_LODSD:
  1424. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1425. A_FSTSW, A_FNSTSW:
  1426. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1427. else
  1428. begin
  1429. with insprop[p.opcode] do
  1430. begin
  1431. if (
  1432. { xor %reg,%reg etc. is classed as a new value }
  1433. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1434. MatchOpType(p, top_reg, top_reg) and
  1435. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1436. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1437. ) then
  1438. begin
  1439. Result := True;
  1440. Exit;
  1441. end;
  1442. { Make sure the entire register is overwritten }
  1443. if (getregtype(reg) = R_INTREGISTER) then
  1444. begin
  1445. if (p.ops > 0) then
  1446. begin
  1447. if RegInOp(reg, p.oper[0]^) then
  1448. begin
  1449. if (p.oper[0]^.typ = top_ref) then
  1450. begin
  1451. if RegInRef(reg, p.oper[0]^.ref^) then
  1452. begin
  1453. Result := False;
  1454. Exit;
  1455. end;
  1456. end
  1457. else if (p.oper[0]^.typ = top_reg) then
  1458. begin
  1459. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1460. begin
  1461. Result := False;
  1462. Exit;
  1463. end
  1464. else if ([Ch_WOp1]*Ch<>[]) then
  1465. begin
  1466. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1467. Result := True
  1468. else
  1469. begin
  1470. Result := False;
  1471. Exit;
  1472. end;
  1473. end;
  1474. end;
  1475. end;
  1476. if (p.ops > 1) then
  1477. begin
  1478. if RegInOp(reg, p.oper[1]^) then
  1479. begin
  1480. if (p.oper[1]^.typ = top_ref) then
  1481. begin
  1482. if RegInRef(reg, p.oper[1]^.ref^) then
  1483. begin
  1484. Result := False;
  1485. Exit;
  1486. end;
  1487. end
  1488. else if (p.oper[1]^.typ = top_reg) then
  1489. begin
  1490. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1491. begin
  1492. Result := False;
  1493. Exit;
  1494. end
  1495. else if ([Ch_WOp2]*Ch<>[]) then
  1496. begin
  1497. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1498. Result := True
  1499. else
  1500. begin
  1501. Result := False;
  1502. Exit;
  1503. end;
  1504. end;
  1505. end;
  1506. end;
  1507. if (p.ops > 2) then
  1508. begin
  1509. if RegInOp(reg, p.oper[2]^) then
  1510. begin
  1511. if (p.oper[2]^.typ = top_ref) then
  1512. begin
  1513. if RegInRef(reg, p.oper[2]^.ref^) then
  1514. begin
  1515. Result := False;
  1516. Exit;
  1517. end;
  1518. end
  1519. else if (p.oper[2]^.typ = top_reg) then
  1520. begin
  1521. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1522. begin
  1523. Result := False;
  1524. Exit;
  1525. end
  1526. else if ([Ch_WOp3]*Ch<>[]) then
  1527. begin
  1528. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1529. Result := True
  1530. else
  1531. begin
  1532. Result := False;
  1533. Exit;
  1534. end;
  1535. end;
  1536. end;
  1537. end;
  1538. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1539. begin
  1540. if (p.oper[3]^.typ = top_ref) then
  1541. begin
  1542. if RegInRef(reg, p.oper[3]^.ref^) then
  1543. begin
  1544. Result := False;
  1545. Exit;
  1546. end;
  1547. end
  1548. else if (p.oper[3]^.typ = top_reg) then
  1549. begin
  1550. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1551. begin
  1552. Result := False;
  1553. Exit;
  1554. end
  1555. else if ([Ch_WOp4]*Ch<>[]) then
  1556. begin
  1557. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1558. Result := True
  1559. else
  1560. begin
  1561. Result := False;
  1562. Exit;
  1563. end;
  1564. end;
  1565. end;
  1566. end;
  1567. end;
  1568. end;
  1569. end;
  1570. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1571. case getsupreg(reg) of
  1572. RS_EAX:
  1573. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1574. begin
  1575. Result := True;
  1576. Exit;
  1577. end;
  1578. RS_ECX:
  1579. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1580. begin
  1581. Result := True;
  1582. Exit;
  1583. end;
  1584. RS_EDX:
  1585. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1586. begin
  1587. Result := True;
  1588. Exit;
  1589. end;
  1590. RS_EBX:
  1591. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1592. begin
  1593. Result := True;
  1594. Exit;
  1595. end;
  1596. RS_ESP:
  1597. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1598. begin
  1599. Result := True;
  1600. Exit;
  1601. end;
  1602. RS_EBP:
  1603. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1604. begin
  1605. Result := True;
  1606. Exit;
  1607. end;
  1608. RS_ESI:
  1609. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1610. begin
  1611. Result := True;
  1612. Exit;
  1613. end;
  1614. RS_EDI:
  1615. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1616. begin
  1617. Result := True;
  1618. Exit;
  1619. end;
  1620. else
  1621. ;
  1622. end;
  1623. end;
  1624. end;
  1625. end;
  1626. end;
  1627. end;
  1628. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1629. var
  1630. hp2,hp3 : tai;
  1631. begin
  1632. { some x86-64 issue a NOP before the real exit code }
  1633. if MatchInstruction(p,A_NOP,[]) then
  1634. GetNextInstruction(p,p);
  1635. result:=assigned(p) and (p.typ=ait_instruction) and
  1636. ((taicpu(p).opcode = A_RET) or
  1637. ((taicpu(p).opcode=A_LEAVE) and
  1638. GetNextInstruction(p,hp2) and
  1639. MatchInstruction(hp2,A_RET,[S_NO])
  1640. ) or
  1641. (((taicpu(p).opcode=A_LEA) and
  1642. MatchOpType(taicpu(p),top_ref,top_reg) and
  1643. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1644. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1645. ) and
  1646. GetNextInstruction(p,hp2) and
  1647. MatchInstruction(hp2,A_RET,[S_NO])
  1648. ) or
  1649. ((((taicpu(p).opcode=A_MOV) and
  1650. MatchOpType(taicpu(p),top_reg,top_reg) and
  1651. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1653. ((taicpu(p).opcode=A_LEA) and
  1654. MatchOpType(taicpu(p),top_ref,top_reg) and
  1655. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1656. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1657. )
  1658. ) and
  1659. GetNextInstruction(p,hp2) and
  1660. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1661. MatchOpType(taicpu(hp2),top_reg) and
  1662. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1663. GetNextInstruction(hp2,hp3) and
  1664. MatchInstruction(hp3,A_RET,[S_NO])
  1665. )
  1666. );
  1667. end;
  1668. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1669. begin
  1670. isFoldableArithOp := False;
  1671. case hp1.opcode of
  1672. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1673. isFoldableArithOp :=
  1674. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1675. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1676. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1677. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[1]^.reg = reg);
  1679. A_INC,A_DEC,A_NEG,A_NOT:
  1680. isFoldableArithOp :=
  1681. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1682. (taicpu(hp1).oper[0]^.reg = reg);
  1683. else
  1684. ;
  1685. end;
  1686. end;
  1687. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1688. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1689. var
  1690. hp2: tai;
  1691. begin
  1692. hp2 := p;
  1693. repeat
  1694. hp2 := tai(hp2.previous);
  1695. if assigned(hp2) and
  1696. (hp2.typ = ait_regalloc) and
  1697. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1698. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1699. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1700. begin
  1701. RemoveInstruction(hp2);
  1702. break;
  1703. end;
  1704. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1705. end;
  1706. begin
  1707. case current_procinfo.procdef.returndef.typ of
  1708. arraydef,recorddef,pointerdef,
  1709. stringdef,enumdef,procdef,objectdef,errordef,
  1710. filedef,setdef,procvardef,
  1711. classrefdef,forwarddef:
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. orddef:
  1714. if current_procinfo.procdef.returndef.size <> 0 then
  1715. begin
  1716. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1717. { for int64/qword }
  1718. if current_procinfo.procdef.returndef.size = 8 then
  1719. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1720. end;
  1721. else
  1722. ;
  1723. end;
  1724. end;
  1725. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1726. var
  1727. hp1,hp2 : tai;
  1728. begin
  1729. result:=false;
  1730. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1731. begin
  1732. { vmova* reg1,reg1
  1733. =>
  1734. <nop> }
  1735. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1736. begin
  1737. RemoveCurrentP(p);
  1738. result:=true;
  1739. exit;
  1740. end
  1741. else if GetNextInstruction(p,hp1) then
  1742. begin
  1743. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1744. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1745. begin
  1746. { vmova* reg1,reg2
  1747. vmova* reg2,reg3
  1748. dealloc reg2
  1749. =>
  1750. vmova* reg1,reg3 }
  1751. TransferUsedRegs(TmpUsedRegs);
  1752. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1753. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1754. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1755. begin
  1756. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1757. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1758. RemoveInstruction(hp1);
  1759. result:=true;
  1760. exit;
  1761. end
  1762. { special case:
  1763. vmova* reg1,<op>
  1764. vmova* <op>,reg1
  1765. =>
  1766. vmova* reg1,<op> }
  1767. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1768. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1769. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1770. ) then
  1771. begin
  1772. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1773. RemoveInstruction(hp1);
  1774. result:=true;
  1775. exit;
  1776. end
  1777. end
  1778. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1779. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1780. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1781. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1782. ) and
  1783. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1784. begin
  1785. { vmova* reg1,reg2
  1786. vmovs* reg2,<op>
  1787. dealloc reg2
  1788. =>
  1789. vmovs* reg1,reg3 }
  1790. TransferUsedRegs(TmpUsedRegs);
  1791. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1792. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1793. begin
  1794. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1795. taicpu(p).opcode:=taicpu(hp1).opcode;
  1796. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1797. RemoveInstruction(hp1);
  1798. result:=true;
  1799. exit;
  1800. end
  1801. end;
  1802. end;
  1803. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1804. begin
  1805. if MatchInstruction(hp1,[A_VFMADDPD,
  1806. A_VFMADD132PD,
  1807. A_VFMADD132PS,
  1808. A_VFMADD132SD,
  1809. A_VFMADD132SS,
  1810. A_VFMADD213PD,
  1811. A_VFMADD213PS,
  1812. A_VFMADD213SD,
  1813. A_VFMADD213SS,
  1814. A_VFMADD231PD,
  1815. A_VFMADD231PS,
  1816. A_VFMADD231SD,
  1817. A_VFMADD231SS,
  1818. A_VFMADDSUB132PD,
  1819. A_VFMADDSUB132PS,
  1820. A_VFMADDSUB213PD,
  1821. A_VFMADDSUB213PS,
  1822. A_VFMADDSUB231PD,
  1823. A_VFMADDSUB231PS,
  1824. A_VFMSUB132PD,
  1825. A_VFMSUB132PS,
  1826. A_VFMSUB132SD,
  1827. A_VFMSUB132SS,
  1828. A_VFMSUB213PD,
  1829. A_VFMSUB213PS,
  1830. A_VFMSUB213SD,
  1831. A_VFMSUB213SS,
  1832. A_VFMSUB231PD,
  1833. A_VFMSUB231PS,
  1834. A_VFMSUB231SD,
  1835. A_VFMSUB231SS,
  1836. A_VFMSUBADD132PD,
  1837. A_VFMSUBADD132PS,
  1838. A_VFMSUBADD213PD,
  1839. A_VFMSUBADD213PS,
  1840. A_VFMSUBADD231PD,
  1841. A_VFMSUBADD231PS,
  1842. A_VFNMADD132PD,
  1843. A_VFNMADD132PS,
  1844. A_VFNMADD132SD,
  1845. A_VFNMADD132SS,
  1846. A_VFNMADD213PD,
  1847. A_VFNMADD213PS,
  1848. A_VFNMADD213SD,
  1849. A_VFNMADD213SS,
  1850. A_VFNMADD231PD,
  1851. A_VFNMADD231PS,
  1852. A_VFNMADD231SD,
  1853. A_VFNMADD231SS,
  1854. A_VFNMSUB132PD,
  1855. A_VFNMSUB132PS,
  1856. A_VFNMSUB132SD,
  1857. A_VFNMSUB132SS,
  1858. A_VFNMSUB213PD,
  1859. A_VFNMSUB213PS,
  1860. A_VFNMSUB213SD,
  1861. A_VFNMSUB213SS,
  1862. A_VFNMSUB231PD,
  1863. A_VFNMSUB231PS,
  1864. A_VFNMSUB231SD,
  1865. A_VFNMSUB231SS],[S_NO]) and
  1866. { we mix single and double opperations here because we assume that the compiler
  1867. generates vmovapd only after double operations and vmovaps only after single operations }
  1868. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1869. GetNextInstruction(hp1,hp2) and
  1870. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1871. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1872. begin
  1873. TransferUsedRegs(TmpUsedRegs);
  1874. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1875. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1876. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1877. begin
  1878. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1879. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1880. RemoveInstruction(hp2);
  1881. end;
  1882. end
  1883. else if (hp1.typ = ait_instruction) and
  1884. GetNextInstruction(hp1, hp2) and
  1885. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1886. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1887. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1888. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1889. (((taicpu(p).opcode=A_MOVAPS) and
  1890. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1891. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1892. ((taicpu(p).opcode=A_MOVAPD) and
  1893. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1894. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1895. ) then
  1896. { change
  1897. movapX reg,reg2
  1898. addsX/subsX/... reg3, reg2
  1899. movapX reg2,reg
  1900. to
  1901. addsX/subsX/... reg3,reg
  1902. }
  1903. begin
  1904. TransferUsedRegs(TmpUsedRegs);
  1905. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1906. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1907. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1908. begin
  1909. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1910. debug_op2str(taicpu(p).opcode)+' '+
  1911. debug_op2str(taicpu(hp1).opcode)+' '+
  1912. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1913. { we cannot eliminate the first move if
  1914. the operations uses the same register for source and dest }
  1915. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1916. RemoveCurrentP(p, nil);
  1917. p:=hp1;
  1918. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1919. RemoveInstruction(hp2);
  1920. result:=true;
  1921. end;
  1922. end;
  1923. end;
  1924. end;
  1925. end;
  1926. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1927. var
  1928. hp1 : tai;
  1929. begin
  1930. result:=false;
  1931. { replace
  1932. V<Op>X %mreg1,%mreg2,%mreg3
  1933. VMovX %mreg3,%mreg4
  1934. dealloc %mreg3
  1935. by
  1936. V<Op>X %mreg1,%mreg2,%mreg4
  1937. ?
  1938. }
  1939. if GetNextInstruction(p,hp1) and
  1940. { we mix single and double operations here because we assume that the compiler
  1941. generates vmovapd only after double operations and vmovaps only after single operations }
  1942. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1943. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1944. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1945. begin
  1946. TransferUsedRegs(TmpUsedRegs);
  1947. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1948. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1949. begin
  1950. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1951. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1952. RemoveInstruction(hp1);
  1953. result:=true;
  1954. end;
  1955. end;
  1956. end;
  1957. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1958. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1959. begin
  1960. Result := False;
  1961. { For safety reasons, only check for exact register matches }
  1962. { Check base register }
  1963. if (ref.base = AOldReg) then
  1964. begin
  1965. ref.base := ANewReg;
  1966. Result := True;
  1967. end;
  1968. { Check index register }
  1969. if (ref.index = AOldReg) then
  1970. begin
  1971. ref.index := ANewReg;
  1972. Result := True;
  1973. end;
  1974. end;
  1975. { Replaces all references to AOldReg in an operand to ANewReg }
  1976. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1977. var
  1978. OldSupReg, NewSupReg: TSuperRegister;
  1979. OldSubReg, NewSubReg: TSubRegister;
  1980. OldRegType: TRegisterType;
  1981. ThisOper: POper;
  1982. begin
  1983. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1984. Result := False;
  1985. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1986. InternalError(2020011801);
  1987. OldSupReg := getsupreg(AOldReg);
  1988. OldSubReg := getsubreg(AOldReg);
  1989. OldRegType := getregtype(AOldReg);
  1990. NewSupReg := getsupreg(ANewReg);
  1991. NewSubReg := getsubreg(ANewReg);
  1992. if OldRegType <> getregtype(ANewReg) then
  1993. InternalError(2020011802);
  1994. if OldSubReg <> NewSubReg then
  1995. InternalError(2020011803);
  1996. case ThisOper^.typ of
  1997. top_reg:
  1998. if (
  1999. (ThisOper^.reg = AOldReg) or
  2000. (
  2001. (OldRegType = R_INTREGISTER) and
  2002. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2003. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2004. (
  2005. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2006. {$ifndef x86_64}
  2007. and (
  2008. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2009. don't have an 8-bit representation }
  2010. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2011. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2012. )
  2013. {$endif x86_64}
  2014. )
  2015. )
  2016. ) then
  2017. begin
  2018. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2019. Result := True;
  2020. end;
  2021. top_ref:
  2022. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2023. Result := True;
  2024. else
  2025. ;
  2026. end;
  2027. end;
  2028. { Replaces all references to AOldReg in an instruction to ANewReg }
  2029. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2030. const
  2031. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2032. var
  2033. OperIdx: Integer;
  2034. begin
  2035. Result := False;
  2036. for OperIdx := 0 to p.ops - 1 do
  2037. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2038. begin
  2039. { The shift and rotate instructions can only use CL }
  2040. if not (
  2041. (OperIdx = 0) and
  2042. { This second condition just helps to avoid unnecessarily
  2043. calling MatchInstruction for 10 different opcodes }
  2044. (p.oper[0]^.reg = NR_CL) and
  2045. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2046. ) then
  2047. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2048. end
  2049. else if p.oper[OperIdx]^.typ = top_ref then
  2050. { It's okay to replace registers in references that get written to }
  2051. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2052. end;
  2053. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2054. begin
  2055. with ref^ do
  2056. Result :=
  2057. (index = NR_NO) and
  2058. (
  2059. {$ifdef x86_64}
  2060. (
  2061. (base = NR_RIP) and
  2062. (refaddr in [addr_pic, addr_pic_no_got])
  2063. ) or
  2064. {$endif x86_64}
  2065. (base = NR_STACK_POINTER_REG) or
  2066. (base = current_procinfo.framepointer)
  2067. );
  2068. end;
  2069. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2070. var
  2071. l: asizeint;
  2072. begin
  2073. Result := False;
  2074. { Should have been checked previously }
  2075. if p.opcode <> A_LEA then
  2076. InternalError(2020072501);
  2077. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2078. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2079. not(cs_opt_size in current_settings.optimizerswitches) then
  2080. exit;
  2081. with p.oper[0]^.ref^ do
  2082. begin
  2083. if (base <> p.oper[1]^.reg) or
  2084. (index <> NR_NO) or
  2085. assigned(symbol) then
  2086. exit;
  2087. l:=offset;
  2088. if (l=1) and UseIncDec then
  2089. begin
  2090. p.opcode:=A_INC;
  2091. p.loadreg(0,p.oper[1]^.reg);
  2092. p.ops:=1;
  2093. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2094. end
  2095. else if (l=-1) and UseIncDec then
  2096. begin
  2097. p.opcode:=A_DEC;
  2098. p.loadreg(0,p.oper[1]^.reg);
  2099. p.ops:=1;
  2100. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2101. end
  2102. else
  2103. begin
  2104. if (l<0) and (l<>-2147483648) then
  2105. begin
  2106. p.opcode:=A_SUB;
  2107. p.loadConst(0,-l);
  2108. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2109. end
  2110. else
  2111. begin
  2112. p.opcode:=A_ADD;
  2113. p.loadConst(0,l);
  2114. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2115. end;
  2116. end;
  2117. end;
  2118. Result := True;
  2119. end;
  2120. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2121. var
  2122. CurrentReg, ReplaceReg: TRegister;
  2123. begin
  2124. Result := False;
  2125. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2126. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2127. case hp.opcode of
  2128. A_FSTSW, A_FNSTSW,
  2129. A_IN, A_INS, A_OUT, A_OUTS,
  2130. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2131. { These routines have explicit operands, but they are restricted in
  2132. what they can be (e.g. IN and OUT can only read from AL, AX or
  2133. EAX. }
  2134. Exit;
  2135. A_IMUL:
  2136. begin
  2137. { The 1-operand version writes to implicit registers
  2138. The 2-operand version reads from the first operator, and reads
  2139. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2140. the 3-operand version reads from a register that it doesn't write to
  2141. }
  2142. case hp.ops of
  2143. 1:
  2144. if (
  2145. (
  2146. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2147. ) or
  2148. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2149. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2150. begin
  2151. Result := True;
  2152. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2153. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2154. end;
  2155. 2:
  2156. { Only modify the first parameter }
  2157. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2158. begin
  2159. Result := True;
  2160. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2161. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2162. end;
  2163. 3:
  2164. { Only modify the second parameter }
  2165. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2166. begin
  2167. Result := True;
  2168. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2169. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2170. end;
  2171. else
  2172. InternalError(2020012901);
  2173. end;
  2174. end;
  2175. else
  2176. if (hp.ops > 0) and
  2177. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2178. begin
  2179. Result := True;
  2180. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2181. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2182. end;
  2183. end;
  2184. end;
  2185. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2186. var
  2187. hp1, hp2, hp3: tai;
  2188. DoOptimisation, TempBool: Boolean;
  2189. {$ifdef x86_64}
  2190. NewConst: TCGInt;
  2191. {$endif x86_64}
  2192. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2193. begin
  2194. if taicpu(hp1).opcode = signed_movop then
  2195. begin
  2196. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2197. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2198. end
  2199. else
  2200. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2201. end;
  2202. function TryConstMerge(var p1, p2: tai): Boolean;
  2203. var
  2204. ThisRef: TReference;
  2205. begin
  2206. Result := False;
  2207. ThisRef := taicpu(p2).oper[1]^.ref^;
  2208. { Only permit writes to the stack, since we can guarantee alignment with that }
  2209. if (ThisRef.index = NR_NO) and
  2210. (
  2211. (ThisRef.base = NR_STACK_POINTER_REG) or
  2212. (ThisRef.base = current_procinfo.framepointer)
  2213. ) then
  2214. begin
  2215. case taicpu(p).opsize of
  2216. S_B:
  2217. begin
  2218. { Word writes must be on a 2-byte boundary }
  2219. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2220. begin
  2221. { Reduce offset of second reference to see if it is sequential with the first }
  2222. Dec(ThisRef.offset, 1);
  2223. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2224. begin
  2225. { Make sure the constants aren't represented as a
  2226. negative number, as these won't merge properly }
  2227. taicpu(p1).opsize := S_W;
  2228. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2229. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2230. RemoveInstruction(p2);
  2231. Result := True;
  2232. end;
  2233. end;
  2234. end;
  2235. S_W:
  2236. begin
  2237. { Longword writes must be on a 4-byte boundary }
  2238. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2239. begin
  2240. { Reduce offset of second reference to see if it is sequential with the first }
  2241. Dec(ThisRef.offset, 2);
  2242. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2243. begin
  2244. { Make sure the constants aren't represented as a
  2245. negative number, as these won't merge properly }
  2246. taicpu(p1).opsize := S_L;
  2247. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2248. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2249. RemoveInstruction(p2);
  2250. Result := True;
  2251. end;
  2252. end;
  2253. end;
  2254. {$ifdef x86_64}
  2255. S_L:
  2256. begin
  2257. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2258. see if the constants can be encoded this way. }
  2259. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2260. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2261. { Quadword writes must be on an 8-byte boundary }
  2262. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2263. begin
  2264. { Reduce offset of second reference to see if it is sequential with the first }
  2265. Dec(ThisRef.offset, 4);
  2266. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2267. begin
  2268. { Make sure the constants aren't represented as a
  2269. negative number, as these won't merge properly }
  2270. taicpu(p1).opsize := S_Q;
  2271. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2272. taicpu(p1).oper[0]^.val := NewConst;
  2273. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2274. RemoveInstruction(p2);
  2275. Result := True;
  2276. end;
  2277. end;
  2278. end;
  2279. {$endif x86_64}
  2280. else
  2281. ;
  2282. end;
  2283. end;
  2284. end;
  2285. var
  2286. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2287. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2288. NewSize: topsize;
  2289. CurrentReg, ActiveReg: TRegister;
  2290. SourceRef, TargetRef: TReference;
  2291. MovAligned, MovUnaligned: TAsmOp;
  2292. begin
  2293. Result:=false;
  2294. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2295. { remove mov reg1,reg1? }
  2296. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2297. then
  2298. begin
  2299. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2300. { take care of the register (de)allocs following p }
  2301. RemoveCurrentP(p, hp1);
  2302. Result:=true;
  2303. exit;
  2304. end;
  2305. { All the next optimisations require a next instruction }
  2306. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2307. Exit;
  2308. { Look for:
  2309. mov %reg1,%reg2
  2310. ??? %reg2,r/m
  2311. Change to:
  2312. mov %reg1,%reg2
  2313. ??? %reg1,r/m
  2314. }
  2315. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2316. begin
  2317. CurrentReg := taicpu(p).oper[1]^.reg;
  2318. if RegReadByInstruction(CurrentReg, hp1) and
  2319. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2320. begin
  2321. { A change has occurred, just not in p }
  2322. Result := True;
  2323. TransferUsedRegs(TmpUsedRegs);
  2324. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2325. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2326. { Just in case something didn't get modified (e.g. an
  2327. implicit register) }
  2328. not RegReadByInstruction(CurrentReg, hp1) then
  2329. begin
  2330. { We can remove the original MOV }
  2331. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2332. RemoveCurrentp(p, hp1);
  2333. { UsedRegs got updated by RemoveCurrentp }
  2334. Result := True;
  2335. Exit;
  2336. end;
  2337. { If we know a MOV instruction has become a null operation, we might as well
  2338. get rid of it now to save time. }
  2339. if (taicpu(hp1).opcode = A_MOV) and
  2340. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2341. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2342. { Just being a register is enough to confirm it's a null operation }
  2343. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2344. begin
  2345. Result := True;
  2346. { Speed-up to reduce a pipeline stall... if we had something like...
  2347. movl %eax,%edx
  2348. movw %dx,%ax
  2349. ... the second instruction would change to movw %ax,%ax, but
  2350. given that it is now %ax that's active rather than %eax,
  2351. penalties might occur due to a partial register write, so instead,
  2352. change it to a MOVZX instruction when optimising for speed.
  2353. }
  2354. if not (cs_opt_size in current_settings.optimizerswitches) and
  2355. IsMOVZXAcceptable and
  2356. (taicpu(hp1).opsize < taicpu(p).opsize)
  2357. {$ifdef x86_64}
  2358. { operations already implicitly set the upper 64 bits to zero }
  2359. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2360. {$endif x86_64}
  2361. then
  2362. begin
  2363. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2364. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2365. case taicpu(p).opsize of
  2366. S_W:
  2367. if taicpu(hp1).opsize = S_B then
  2368. taicpu(hp1).opsize := S_BL
  2369. else
  2370. InternalError(2020012911);
  2371. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2372. case taicpu(hp1).opsize of
  2373. S_B:
  2374. taicpu(hp1).opsize := S_BL;
  2375. S_W:
  2376. taicpu(hp1).opsize := S_WL;
  2377. else
  2378. InternalError(2020012912);
  2379. end;
  2380. else
  2381. InternalError(2020012910);
  2382. end;
  2383. taicpu(hp1).opcode := A_MOVZX;
  2384. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2385. end
  2386. else
  2387. begin
  2388. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2389. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2390. RemoveInstruction(hp1);
  2391. { The instruction after what was hp1 is now the immediate next instruction,
  2392. so we can continue to make optimisations if it's present }
  2393. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2394. Exit;
  2395. hp1 := hp2;
  2396. end;
  2397. end;
  2398. end;
  2399. end;
  2400. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2401. overwrites the original destination register. e.g.
  2402. movl ###,%reg2d
  2403. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2404. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2405. }
  2406. if (taicpu(p).oper[1]^.typ = top_reg) and
  2407. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2408. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2409. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2410. begin
  2411. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2412. begin
  2413. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2414. case taicpu(p).oper[0]^.typ of
  2415. top_const:
  2416. { We have something like:
  2417. movb $x, %regb
  2418. movzbl %regb,%regd
  2419. Change to:
  2420. movl $x, %regd
  2421. }
  2422. begin
  2423. case taicpu(hp1).opsize of
  2424. S_BW:
  2425. begin
  2426. convert_mov_value(A_MOVSX, $FF);
  2427. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2428. taicpu(p).opsize := S_W;
  2429. end;
  2430. S_BL:
  2431. begin
  2432. convert_mov_value(A_MOVSX, $FF);
  2433. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2434. taicpu(p).opsize := S_L;
  2435. end;
  2436. S_WL:
  2437. begin
  2438. convert_mov_value(A_MOVSX, $FFFF);
  2439. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2440. taicpu(p).opsize := S_L;
  2441. end;
  2442. {$ifdef x86_64}
  2443. S_BQ:
  2444. begin
  2445. convert_mov_value(A_MOVSX, $FF);
  2446. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2447. taicpu(p).opsize := S_Q;
  2448. end;
  2449. S_WQ:
  2450. begin
  2451. convert_mov_value(A_MOVSX, $FFFF);
  2452. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2453. taicpu(p).opsize := S_Q;
  2454. end;
  2455. S_LQ:
  2456. begin
  2457. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2458. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2459. taicpu(p).opsize := S_Q;
  2460. end;
  2461. {$endif x86_64}
  2462. else
  2463. { If hp1 was a MOV instruction, it should have been
  2464. optimised already }
  2465. InternalError(2020021001);
  2466. end;
  2467. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2468. RemoveInstruction(hp1);
  2469. Result := True;
  2470. Exit;
  2471. end;
  2472. top_ref:
  2473. { We have something like:
  2474. movb mem, %regb
  2475. movzbl %regb,%regd
  2476. Change to:
  2477. movzbl mem, %regd
  2478. }
  2479. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2480. begin
  2481. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2482. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2483. RemoveCurrentP(p, hp1);
  2484. Result:=True;
  2485. Exit;
  2486. end;
  2487. else
  2488. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2489. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2490. Exit;
  2491. end;
  2492. end
  2493. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2494. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2495. optimised }
  2496. else
  2497. begin
  2498. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2499. RemoveCurrentP(p, hp1);
  2500. Result := True;
  2501. Exit;
  2502. end;
  2503. end;
  2504. if (taicpu(hp1).opcode = A_AND) and
  2505. (taicpu(p).oper[1]^.typ = top_reg) and
  2506. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2507. begin
  2508. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2509. begin
  2510. case taicpu(p).opsize of
  2511. S_L:
  2512. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2513. begin
  2514. { Optimize out:
  2515. mov x, %reg
  2516. and ffffffffh, %reg
  2517. }
  2518. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2519. RemoveInstruction(hp1);
  2520. Result:=true;
  2521. exit;
  2522. end;
  2523. S_Q: { TODO: Confirm if this is even possible }
  2524. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2525. begin
  2526. { Optimize out:
  2527. mov x, %reg
  2528. and ffffffffffffffffh, %reg
  2529. }
  2530. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2531. RemoveInstruction(hp1);
  2532. Result:=true;
  2533. exit;
  2534. end;
  2535. else
  2536. ;
  2537. end;
  2538. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2539. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2540. GetNextInstruction(hp1,hp2) and
  2541. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2542. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2543. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2544. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2545. GetNextInstruction(hp2,hp3) and
  2546. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2547. (taicpu(hp3).condition in [C_E,C_NE]) then
  2548. begin
  2549. TransferUsedRegs(TmpUsedRegs);
  2550. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2551. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2552. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2553. begin
  2554. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2555. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2556. taicpu(hp1).opcode:=A_TEST;
  2557. RemoveInstruction(hp2);
  2558. RemoveCurrentP(p, hp1);
  2559. Result:=true;
  2560. exit;
  2561. end;
  2562. end;
  2563. end
  2564. else if IsMOVZXAcceptable and
  2565. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2566. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2567. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2568. then
  2569. begin
  2570. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2571. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2572. case taicpu(p).opsize of
  2573. S_B:
  2574. if (taicpu(hp1).oper[0]^.val = $ff) then
  2575. begin
  2576. { Convert:
  2577. movb x, %regl movb x, %regl
  2578. andw ffh, %regw andl ffh, %regd
  2579. To:
  2580. movzbw x, %regd movzbl x, %regd
  2581. (Identical registers, just different sizes)
  2582. }
  2583. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2584. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2585. case taicpu(hp1).opsize of
  2586. S_W: NewSize := S_BW;
  2587. S_L: NewSize := S_BL;
  2588. {$ifdef x86_64}
  2589. S_Q: NewSize := S_BQ;
  2590. {$endif x86_64}
  2591. else
  2592. InternalError(2018011510);
  2593. end;
  2594. end
  2595. else
  2596. NewSize := S_NO;
  2597. S_W:
  2598. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2599. begin
  2600. { Convert:
  2601. movw x, %regw
  2602. andl ffffh, %regd
  2603. To:
  2604. movzwl x, %regd
  2605. (Identical registers, just different sizes)
  2606. }
  2607. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2608. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2609. case taicpu(hp1).opsize of
  2610. S_L: NewSize := S_WL;
  2611. {$ifdef x86_64}
  2612. S_Q: NewSize := S_WQ;
  2613. {$endif x86_64}
  2614. else
  2615. InternalError(2018011511);
  2616. end;
  2617. end
  2618. else
  2619. NewSize := S_NO;
  2620. else
  2621. NewSize := S_NO;
  2622. end;
  2623. if NewSize <> S_NO then
  2624. begin
  2625. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2626. { The actual optimization }
  2627. taicpu(p).opcode := A_MOVZX;
  2628. taicpu(p).changeopsize(NewSize);
  2629. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2630. { Safeguard if "and" is followed by a conditional command }
  2631. TransferUsedRegs(TmpUsedRegs);
  2632. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2633. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2634. begin
  2635. { At this point, the "and" command is effectively equivalent to
  2636. "test %reg,%reg". This will be handled separately by the
  2637. Peephole Optimizer. [Kit] }
  2638. DebugMsg(SPeepholeOptimization + PreMessage +
  2639. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2640. end
  2641. else
  2642. begin
  2643. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2644. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2645. RemoveInstruction(hp1);
  2646. end;
  2647. Result := True;
  2648. Exit;
  2649. end;
  2650. end;
  2651. end;
  2652. if (taicpu(hp1).opcode = A_OR) and
  2653. (taicpu(p).oper[1]^.typ = top_reg) and
  2654. MatchOperand(taicpu(p).oper[0]^, 0) and
  2655. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2656. begin
  2657. { mov 0, %reg
  2658. or ###,%reg
  2659. Change to (only if the flags are not used):
  2660. mov ###,%reg
  2661. }
  2662. TransferUsedRegs(TmpUsedRegs);
  2663. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2664. DoOptimisation := True;
  2665. { Even if the flags are used, we might be able to do the optimisation
  2666. if the conditions are predictable }
  2667. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2668. begin
  2669. { Only perform if ### = %reg (the same register) or equal to 0,
  2670. so %reg is guaranteed to still have a value of zero }
  2671. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2672. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2673. begin
  2674. hp2 := hp1;
  2675. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2676. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2677. GetNextInstruction(hp2, hp3) do
  2678. begin
  2679. { Don't continue modifying if the flags state is getting changed }
  2680. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2681. Break;
  2682. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2683. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2684. begin
  2685. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2686. begin
  2687. { Condition is always true }
  2688. case taicpu(hp3).opcode of
  2689. A_Jcc:
  2690. begin
  2691. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2692. { Check for jump shortcuts before we destroy the condition }
  2693. DoJumpOptimizations(hp3, TempBool);
  2694. MakeUnconditional(taicpu(hp3));
  2695. Result := True;
  2696. end;
  2697. A_CMOVcc:
  2698. begin
  2699. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2700. taicpu(hp3).opcode := A_MOV;
  2701. taicpu(hp3).condition := C_None;
  2702. Result := True;
  2703. end;
  2704. A_SETcc:
  2705. begin
  2706. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2707. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2708. taicpu(hp3).opcode := A_MOV;
  2709. taicpu(hp3).ops := 2;
  2710. taicpu(hp3).condition := C_None;
  2711. taicpu(hp3).opsize := S_B;
  2712. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2713. taicpu(hp3).loadconst(0, 1);
  2714. Result := True;
  2715. end;
  2716. else
  2717. InternalError(2021090701);
  2718. end;
  2719. end
  2720. 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
  2721. begin
  2722. { Condition is always false }
  2723. case taicpu(hp3).opcode of
  2724. A_Jcc:
  2725. begin
  2726. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2727. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2728. RemoveInstruction(hp3);
  2729. Result := True;
  2730. { Since hp3 was deleted, hp2 must not be updated }
  2731. Continue;
  2732. end;
  2733. A_CMOVcc:
  2734. begin
  2735. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2736. RemoveInstruction(hp3);
  2737. Result := True;
  2738. { Since hp3 was deleted, hp2 must not be updated }
  2739. Continue;
  2740. end;
  2741. A_SETcc:
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2744. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2745. taicpu(hp3).opcode := A_MOV;
  2746. taicpu(hp3).ops := 2;
  2747. taicpu(hp3).condition := C_None;
  2748. taicpu(hp3).opsize := S_B;
  2749. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2750. taicpu(hp3).loadconst(0, 0);
  2751. Result := True;
  2752. end;
  2753. else
  2754. InternalError(2021090702);
  2755. end;
  2756. end
  2757. else
  2758. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2759. DoOptimisation := False;
  2760. end;
  2761. hp2 := hp3;
  2762. end;
  2763. { Flags are still in use - don't optimise }
  2764. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2765. DoOptimisation := False;
  2766. end
  2767. else
  2768. DoOptimisation := False;
  2769. end;
  2770. if DoOptimisation then
  2771. begin
  2772. {$ifdef x86_64}
  2773. { OR only supports 32-bit sign-extended constants for 64-bit
  2774. instructions, so compensate for this if the constant is
  2775. encoded as a value greater than or equal to 2^31 }
  2776. if (taicpu(hp1).opsize = S_Q) and
  2777. (taicpu(hp1).oper[0]^.typ = top_const) and
  2778. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2779. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2780. {$endif x86_64}
  2781. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2782. taicpu(hp1).opcode := A_MOV;
  2783. RemoveCurrentP(p, hp1);
  2784. Result := True;
  2785. Exit;
  2786. end;
  2787. end;
  2788. { Next instruction is also a MOV ? }
  2789. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2790. begin
  2791. if MatchOpType(taicpu(p), top_const, top_ref) and
  2792. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2793. TryConstMerge(p, hp1) then
  2794. begin
  2795. Result := True;
  2796. { In case we have four byte writes in a row, check for 2 more
  2797. right now so we don't have to wait for another iteration of
  2798. pass 1
  2799. }
  2800. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2801. case taicpu(p).opsize of
  2802. S_W:
  2803. begin
  2804. if GetNextInstruction(p, hp1) and
  2805. MatchInstruction(hp1, A_MOV, [S_B]) and
  2806. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2807. GetNextInstruction(hp1, hp2) and
  2808. MatchInstruction(hp2, A_MOV, [S_B]) and
  2809. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2810. { Try to merge the two bytes }
  2811. TryConstMerge(hp1, hp2) then
  2812. { Now try to merge the two words (hp2 will get deleted) }
  2813. TryConstMerge(p, hp1);
  2814. end;
  2815. S_L:
  2816. begin
  2817. { Though this only really benefits x86_64 and not i386, it
  2818. gets a potential optimisation done faster and hence
  2819. reduces the number of times OptPass1MOV is entered }
  2820. if GetNextInstruction(p, hp1) and
  2821. MatchInstruction(hp1, A_MOV, [S_W]) and
  2822. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2823. GetNextInstruction(hp1, hp2) and
  2824. MatchInstruction(hp2, A_MOV, [S_W]) and
  2825. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2826. { Try to merge the two words }
  2827. TryConstMerge(hp1, hp2) then
  2828. { This will always fail on i386, so don't bother
  2829. calling it unless we're doing x86_64 }
  2830. {$ifdef x86_64}
  2831. { Now try to merge the two longwords (hp2 will get deleted) }
  2832. TryConstMerge(p, hp1)
  2833. {$endif x86_64}
  2834. ;
  2835. end;
  2836. else
  2837. ;
  2838. end;
  2839. Exit;
  2840. end;
  2841. if (taicpu(p).oper[1]^.typ = top_reg) and
  2842. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2843. begin
  2844. CurrentReg := taicpu(p).oper[1]^.reg;
  2845. TransferUsedRegs(TmpUsedRegs);
  2846. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2847. { we have
  2848. mov x, %treg
  2849. mov %treg, y
  2850. }
  2851. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2852. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2853. { we've got
  2854. mov x, %treg
  2855. mov %treg, y
  2856. with %treg is not used after }
  2857. case taicpu(p).oper[0]^.typ Of
  2858. { top_reg is covered by DeepMOVOpt }
  2859. top_const:
  2860. begin
  2861. { change
  2862. mov const, %treg
  2863. mov %treg, y
  2864. to
  2865. mov const, y
  2866. }
  2867. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2868. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2869. begin
  2870. if taicpu(hp1).oper[1]^.typ=top_reg then
  2871. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2872. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2873. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2874. RemoveInstruction(hp1);
  2875. Result:=true;
  2876. Exit;
  2877. end;
  2878. end;
  2879. top_ref:
  2880. case taicpu(hp1).oper[1]^.typ of
  2881. top_reg:
  2882. begin
  2883. { change
  2884. mov mem, %treg
  2885. mov %treg, %reg
  2886. to
  2887. mov mem, %reg"
  2888. }
  2889. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2890. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2891. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2892. RemoveInstruction(hp1);
  2893. Result:=true;
  2894. Exit;
  2895. end;
  2896. top_ref:
  2897. begin
  2898. {$ifdef x86_64}
  2899. { Look for the following to simplify:
  2900. mov x(mem1), %reg
  2901. mov %reg, y(mem2)
  2902. mov x+8(mem1), %reg
  2903. mov %reg, y+8(mem2)
  2904. Change to:
  2905. movdqu x(mem1), %xmmreg
  2906. movdqu %xmmreg, y(mem2)
  2907. }
  2908. SourceRef := taicpu(p).oper[0]^.ref^;
  2909. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2910. if (taicpu(p).opsize = S_Q) and
  2911. GetNextInstruction(hp1, hp2) and
  2912. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2913. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2914. begin
  2915. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2917. Inc(SourceRef.offset, 8);
  2918. if UseAVX then
  2919. begin
  2920. MovAligned := A_VMOVDQA;
  2921. MovUnaligned := A_VMOVDQU;
  2922. end
  2923. else
  2924. begin
  2925. MovAligned := A_MOVDQA;
  2926. MovUnaligned := A_MOVDQU;
  2927. end;
  2928. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2929. begin
  2930. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2931. Inc(TargetRef.offset, 8);
  2932. if GetNextInstruction(hp2, hp3) and
  2933. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2934. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2935. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2936. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2937. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2938. begin
  2939. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2940. if CurrentReg <> NR_NO then
  2941. begin
  2942. { Remember that the offsets are 8 ahead }
  2943. if ((SourceRef.offset mod 16) = 8) and
  2944. (
  2945. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2946. (SourceRef.base = current_procinfo.framepointer) or
  2947. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2948. ) then
  2949. taicpu(p).opcode := MovAligned
  2950. else
  2951. taicpu(p).opcode := MovUnaligned;
  2952. taicpu(p).opsize := S_XMM;
  2953. taicpu(p).oper[1]^.reg := CurrentReg;
  2954. if ((TargetRef.offset mod 16) = 8) and
  2955. (
  2956. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2957. (TargetRef.base = current_procinfo.framepointer) or
  2958. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2959. ) then
  2960. taicpu(hp1).opcode := MovAligned
  2961. else
  2962. taicpu(hp1).opcode := MovUnaligned;
  2963. taicpu(hp1).opsize := S_XMM;
  2964. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2965. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2966. RemoveInstruction(hp2);
  2967. RemoveInstruction(hp3);
  2968. Result := True;
  2969. Exit;
  2970. end;
  2971. end;
  2972. end
  2973. else
  2974. begin
  2975. { See if the next references are 8 less rather than 8 greater }
  2976. Dec(SourceRef.offset, 16); { -8 the other way }
  2977. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2978. begin
  2979. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2980. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2981. if GetNextInstruction(hp2, hp3) and
  2982. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2983. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2984. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2985. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2986. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2987. begin
  2988. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2989. if CurrentReg <> NR_NO then
  2990. begin
  2991. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2992. if ((SourceRef.offset mod 16) = 0) and
  2993. (
  2994. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2995. (SourceRef.base = current_procinfo.framepointer) or
  2996. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2997. ) then
  2998. taicpu(hp2).opcode := MovAligned
  2999. else
  3000. taicpu(hp2).opcode := MovUnaligned;
  3001. taicpu(hp2).opsize := S_XMM;
  3002. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3003. if ((TargetRef.offset mod 16) = 0) and
  3004. (
  3005. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3006. (TargetRef.base = current_procinfo.framepointer) or
  3007. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3008. ) then
  3009. taicpu(hp3).opcode := MovAligned
  3010. else
  3011. taicpu(hp3).opcode := MovUnaligned;
  3012. taicpu(hp3).opsize := S_XMM;
  3013. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3014. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3015. RemoveInstruction(hp1);
  3016. RemoveCurrentP(p, hp2);
  3017. Result := True;
  3018. Exit;
  3019. end;
  3020. end;
  3021. end;
  3022. end;
  3023. end;
  3024. {$endif x86_64}
  3025. end;
  3026. else
  3027. { The write target should be a reg or a ref }
  3028. InternalError(2021091601);
  3029. end;
  3030. else
  3031. ;
  3032. end
  3033. else
  3034. { %treg is used afterwards, but all eventualities
  3035. other than the first MOV instruction being a constant
  3036. are covered by DeepMOVOpt, so only check for that }
  3037. if (taicpu(p).oper[0]^.typ = top_const) and
  3038. (
  3039. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3040. not (cs_opt_size in current_settings.optimizerswitches) or
  3041. (taicpu(hp1).opsize = S_B)
  3042. ) and
  3043. (
  3044. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3045. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3046. ) then
  3047. begin
  3048. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3049. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3050. end;
  3051. end;
  3052. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3053. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3054. { mov reg1, mem1 or mov mem1, reg1
  3055. mov mem2, reg2 mov reg2, mem2}
  3056. begin
  3057. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3058. { mov reg1, mem1 or mov mem1, reg1
  3059. mov mem2, reg1 mov reg2, mem1}
  3060. begin
  3061. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3062. { Removes the second statement from
  3063. mov reg1, mem1/reg2
  3064. mov mem1/reg2, reg1 }
  3065. begin
  3066. if taicpu(p).oper[0]^.typ=top_reg then
  3067. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3068. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3069. RemoveInstruction(hp1);
  3070. Result:=true;
  3071. exit;
  3072. end
  3073. else
  3074. begin
  3075. TransferUsedRegs(TmpUsedRegs);
  3076. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3077. if (taicpu(p).oper[1]^.typ = top_ref) and
  3078. { mov reg1, mem1
  3079. mov mem2, reg1 }
  3080. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3081. GetNextInstruction(hp1, hp2) and
  3082. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3083. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3084. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3085. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3086. { change to
  3087. mov reg1, mem1 mov reg1, mem1
  3088. mov mem2, reg1 cmp reg1, mem2
  3089. cmp mem1, reg1
  3090. }
  3091. begin
  3092. RemoveInstruction(hp2);
  3093. taicpu(hp1).opcode := A_CMP;
  3094. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3095. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3096. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3097. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3098. end;
  3099. end;
  3100. end
  3101. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3102. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3103. begin
  3104. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3105. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3106. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3107. end
  3108. else
  3109. begin
  3110. TransferUsedRegs(TmpUsedRegs);
  3111. if GetNextInstruction(hp1, hp2) and
  3112. MatchOpType(taicpu(p),top_ref,top_reg) and
  3113. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3114. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3115. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3116. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3117. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3118. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3119. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3120. { mov mem1, %reg1
  3121. mov %reg1, mem2
  3122. mov mem2, reg2
  3123. to:
  3124. mov mem1, reg2
  3125. mov reg2, mem2}
  3126. begin
  3127. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3128. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3129. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3130. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3131. RemoveInstruction(hp2);
  3132. Result := True;
  3133. end
  3134. {$ifdef i386}
  3135. { this is enabled for i386 only, as the rules to create the reg sets below
  3136. are too complicated for x86-64, so this makes this code too error prone
  3137. on x86-64
  3138. }
  3139. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3140. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3141. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3142. { mov mem1, reg1 mov mem1, reg1
  3143. mov reg1, mem2 mov reg1, mem2
  3144. mov mem2, reg2 mov mem2, reg1
  3145. to: to:
  3146. mov mem1, reg1 mov mem1, reg1
  3147. mov mem1, reg2 mov reg1, mem2
  3148. mov reg1, mem2
  3149. or (if mem1 depends on reg1
  3150. and/or if mem2 depends on reg2)
  3151. to:
  3152. mov mem1, reg1
  3153. mov reg1, mem2
  3154. mov reg1, reg2
  3155. }
  3156. begin
  3157. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3158. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3159. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3160. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3161. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3162. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3163. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3164. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3165. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3166. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3167. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3168. end
  3169. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3170. begin
  3171. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3172. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3173. end
  3174. else
  3175. begin
  3176. RemoveInstruction(hp2);
  3177. end
  3178. {$endif i386}
  3179. ;
  3180. end;
  3181. end
  3182. { movl [mem1],reg1
  3183. movl [mem1],reg2
  3184. to
  3185. movl [mem1],reg1
  3186. movl reg1,reg2
  3187. }
  3188. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3189. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3190. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3191. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3192. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3193. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3194. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3195. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3196. begin
  3197. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3198. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3199. end;
  3200. { movl const1,[mem1]
  3201. movl [mem1],reg1
  3202. to
  3203. movl const1,reg1
  3204. movl reg1,[mem1]
  3205. }
  3206. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3207. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3208. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3209. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3210. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3211. begin
  3212. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3213. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3214. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3215. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3216. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3217. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3218. Result:=true;
  3219. exit;
  3220. end;
  3221. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3222. { Change:
  3223. movl %reg1,%reg2
  3224. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3225. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3226. To:
  3227. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3228. movl x(%reg1),%reg1
  3229. movl %reg1,%regX
  3230. }
  3231. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3232. begin
  3233. CurrentReg := taicpu(p).oper[0]^.reg;
  3234. ActiveReg := taicpu(p).oper[1]^.reg;
  3235. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3236. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3237. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3238. GetNextInstruction(hp1, hp2) and
  3239. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3240. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3241. begin
  3242. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3243. if RegInRef(ActiveReg, SourceRef) and
  3244. { If %reg1 also appears in the second reference, then it will
  3245. not refer to the same memory block as the first reference }
  3246. not RegInRef(CurrentReg, SourceRef) then
  3247. begin
  3248. { Check to see if the references match if %reg2 is changed to %reg1 }
  3249. if SourceRef.base = ActiveReg then
  3250. SourceRef.base := CurrentReg;
  3251. if SourceRef.index = ActiveReg then
  3252. SourceRef.index := CurrentReg;
  3253. { RefsEqual also checks to ensure both references are non-volatile }
  3254. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3255. begin
  3256. taicpu(hp2).loadreg(0, CurrentReg);
  3257. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3258. Result := True;
  3259. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3260. begin
  3261. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3262. RemoveCurrentP(p, hp1);
  3263. Exit;
  3264. end
  3265. else
  3266. begin
  3267. { Check to see if %reg2 is no longer in use }
  3268. TransferUsedRegs(TmpUsedRegs);
  3269. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3270. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3271. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3272. begin
  3273. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3274. RemoveCurrentP(p, hp1);
  3275. Exit;
  3276. end;
  3277. end;
  3278. { If we reach this point, p and hp1 weren't actually modified,
  3279. so we can do a bit more work on this pass }
  3280. end;
  3281. end;
  3282. end;
  3283. end;
  3284. end;
  3285. { search further than the next instruction for a mov (as long as it's not a jump) }
  3286. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3287. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3288. (taicpu(p).oper[1]^.typ = top_reg) and
  3289. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3290. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3291. begin
  3292. { we work with hp2 here, so hp1 can be still used later on when
  3293. checking for GetNextInstruction_p }
  3294. hp3 := hp1;
  3295. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3296. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3297. { Saves on a large number of dereferences }
  3298. ActiveReg := taicpu(p).oper[1]^.reg;
  3299. TransferUsedRegs(TmpUsedRegs);
  3300. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3301. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3302. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3303. (hp2.typ=ait_instruction) do
  3304. begin
  3305. case taicpu(hp2).opcode of
  3306. A_POP:
  3307. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3308. begin
  3309. if not CrossJump and
  3310. not RegUsedBetween(ActiveReg, p, hp2) then
  3311. begin
  3312. { We can remove the original MOV since the register
  3313. wasn't used between it and its popping from the stack }
  3314. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3315. RemoveCurrentp(p, hp1);
  3316. Result := True;
  3317. Exit;
  3318. end;
  3319. { Can't go any further }
  3320. Break;
  3321. end;
  3322. A_MOV:
  3323. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3324. ((taicpu(p).oper[0]^.typ=top_const) or
  3325. ((taicpu(p).oper[0]^.typ=top_reg) and
  3326. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3327. )
  3328. ) then
  3329. begin
  3330. { we have
  3331. mov x, %treg
  3332. mov %treg, y
  3333. }
  3334. { We don't need to call UpdateUsedRegs for every instruction between
  3335. p and hp2 because the register we're concerned about will not
  3336. become deallocated (otherwise GetNextInstructionUsingReg would
  3337. have stopped at an earlier instruction). [Kit] }
  3338. TempRegUsed :=
  3339. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3340. RegReadByInstruction(ActiveReg, hp3) or
  3341. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3342. case taicpu(p).oper[0]^.typ Of
  3343. top_reg:
  3344. begin
  3345. { change
  3346. mov %reg, %treg
  3347. mov %treg, y
  3348. to
  3349. mov %reg, y
  3350. }
  3351. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3352. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3353. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3354. begin
  3355. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3356. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3357. if TempRegUsed then
  3358. begin
  3359. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3360. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3361. { Set the start of the next GetNextInstructionUsingRegCond search
  3362. to start at the entry right before hp2 (which is about to be removed) }
  3363. hp3 := tai(hp2.Previous);
  3364. RemoveInstruction(hp2);
  3365. { See if there's more we can optimise }
  3366. Continue;
  3367. end
  3368. else
  3369. begin
  3370. RemoveInstruction(hp2);
  3371. { We can remove the original MOV too }
  3372. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3373. RemoveCurrentP(p, hp1);
  3374. Result:=true;
  3375. Exit;
  3376. end;
  3377. end
  3378. else
  3379. begin
  3380. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3381. taicpu(hp2).loadReg(0, CurrentReg);
  3382. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3383. { Check to see if the register also appears in the reference }
  3384. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3385. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3386. { Don't remove the first instruction if the temporary register is in use }
  3387. if not TempRegUsed and
  3388. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3389. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3390. begin
  3391. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3392. RemoveCurrentP(p, hp1);
  3393. Result:=true;
  3394. Exit;
  3395. end;
  3396. { No need to set Result to True here. If there's another instruction later
  3397. on that can be optimised, it will be detected when the main Pass 1 loop
  3398. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3399. end;
  3400. end;
  3401. top_const:
  3402. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3403. begin
  3404. { change
  3405. mov const, %treg
  3406. mov %treg, y
  3407. to
  3408. mov const, y
  3409. }
  3410. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3411. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3412. begin
  3413. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3414. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3415. if TempRegUsed then
  3416. begin
  3417. { Don't remove the first instruction if the temporary register is in use }
  3418. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3419. { No need to set Result to True. If there's another instruction later on
  3420. that can be optimised, it will be detected when the main Pass 1 loop
  3421. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3422. end
  3423. else
  3424. begin
  3425. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3426. RemoveCurrentP(p, hp1);
  3427. Result:=true;
  3428. Exit;
  3429. end;
  3430. end;
  3431. end;
  3432. else
  3433. Internalerror(2019103001);
  3434. end;
  3435. end
  3436. else
  3437. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3438. begin
  3439. if not CrossJump and
  3440. not RegUsedBetween(ActiveReg, p, hp2) and
  3441. not RegReadByInstruction(ActiveReg, hp2) then
  3442. begin
  3443. { Register is not used before it is overwritten }
  3444. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3445. RemoveCurrentp(p, hp1);
  3446. Result := True;
  3447. Exit;
  3448. end;
  3449. if (taicpu(p).oper[0]^.typ = top_const) and
  3450. (taicpu(hp2).oper[0]^.typ = top_const) then
  3451. begin
  3452. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3453. begin
  3454. { Same value - register hasn't changed }
  3455. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3456. RemoveInstruction(hp2);
  3457. Result := True;
  3458. { See if there's more we can optimise }
  3459. Continue;
  3460. end;
  3461. end;
  3462. end;
  3463. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3464. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3465. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3466. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3467. begin
  3468. {
  3469. Change from:
  3470. mov ###, %reg
  3471. ...
  3472. movs/z %reg,%reg (Same register, just different sizes)
  3473. To:
  3474. movs/z ###, %reg (Longer version)
  3475. ...
  3476. (remove)
  3477. }
  3478. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3479. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3480. { Keep the first instruction as mov if ### is a constant }
  3481. if taicpu(p).oper[0]^.typ = top_const then
  3482. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3483. else
  3484. begin
  3485. taicpu(p).opcode := taicpu(hp2).opcode;
  3486. taicpu(p).opsize := taicpu(hp2).opsize;
  3487. end;
  3488. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3489. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3490. RemoveInstruction(hp2);
  3491. Result := True;
  3492. Exit;
  3493. end;
  3494. else
  3495. { Move down to the MatchOpType if-block below };
  3496. end;
  3497. { Also catches MOV/S/Z instructions that aren't modified }
  3498. if taicpu(p).oper[0]^.typ = top_reg then
  3499. begin
  3500. CurrentReg := taicpu(p).oper[0]^.reg;
  3501. if
  3502. not RegModifiedByInstruction(CurrentReg, hp3) and
  3503. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3504. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3505. begin
  3506. Result := True;
  3507. { Just in case something didn't get modified (e.g. an
  3508. implicit register). Also, if it does read from this
  3509. register, then there's no longer an advantage to
  3510. changing the register on subsequent instructions.}
  3511. if not RegReadByInstruction(ActiveReg, hp2) then
  3512. begin
  3513. { If a conditional jump was crossed, do not delete
  3514. the original MOV no matter what }
  3515. if not CrossJump and
  3516. { RegEndOfLife returns True if the register is
  3517. deallocated before the next instruction or has
  3518. been loaded with a new value }
  3519. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3520. begin
  3521. { We can remove the original MOV }
  3522. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3523. RemoveCurrentp(p, hp1);
  3524. Exit;
  3525. end;
  3526. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3527. begin
  3528. { See if there's more we can optimise }
  3529. hp3 := hp2;
  3530. Continue;
  3531. end;
  3532. end;
  3533. end;
  3534. end;
  3535. { Break out of the while loop under normal circumstances }
  3536. Break;
  3537. end;
  3538. end;
  3539. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3540. (taicpu(p).oper[1]^.typ = top_reg) and
  3541. (taicpu(p).opsize = S_L) and
  3542. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3543. (taicpu(hp2).opcode = A_AND) and
  3544. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3545. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3546. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3547. ) then
  3548. begin
  3549. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3550. begin
  3551. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3552. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3553. begin
  3554. { Optimize out:
  3555. mov x, %reg
  3556. and ffffffffh, %reg
  3557. }
  3558. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3559. RemoveInstruction(hp2);
  3560. Result:=true;
  3561. exit;
  3562. end;
  3563. end;
  3564. end;
  3565. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3566. x >= RetOffset) as it doesn't do anything (it writes either to a
  3567. parameter or to the temporary storage room for the function
  3568. result)
  3569. }
  3570. if IsExitCode(hp1) and
  3571. (taicpu(p).oper[1]^.typ = top_ref) and
  3572. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3573. (
  3574. (
  3575. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3576. not (
  3577. assigned(current_procinfo.procdef.funcretsym) and
  3578. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3579. )
  3580. ) or
  3581. { Also discard writes to the stack that are below the base pointer,
  3582. as this is temporary storage rather than a function result on the
  3583. stack, say. }
  3584. (
  3585. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3586. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3587. )
  3588. ) then
  3589. begin
  3590. RemoveCurrentp(p, hp1);
  3591. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3592. RemoveLastDeallocForFuncRes(p);
  3593. Result:=true;
  3594. exit;
  3595. end;
  3596. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3597. begin
  3598. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3599. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3600. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3601. begin
  3602. { change
  3603. mov reg1, mem1
  3604. test/cmp x, mem1
  3605. to
  3606. mov reg1, mem1
  3607. test/cmp x, reg1
  3608. }
  3609. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3610. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3611. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3612. Result := True;
  3613. Exit;
  3614. end;
  3615. if DoMovCmpMemOpt(p, hp1, True) then
  3616. begin
  3617. Result := True;
  3618. Exit;
  3619. end;
  3620. end;
  3621. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3622. { If the flags register is in use, don't change the instruction to an
  3623. ADD otherwise this will scramble the flags. [Kit] }
  3624. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3625. begin
  3626. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3627. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3628. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3629. ) or
  3630. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3631. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3632. )
  3633. ) then
  3634. { mov reg1,ref
  3635. lea reg2,[reg1,reg2]
  3636. to
  3637. add reg2,ref}
  3638. begin
  3639. TransferUsedRegs(TmpUsedRegs);
  3640. { reg1 may not be used afterwards }
  3641. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3642. begin
  3643. Taicpu(hp1).opcode:=A_ADD;
  3644. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3645. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3646. RemoveCurrentp(p, hp1);
  3647. result:=true;
  3648. exit;
  3649. end;
  3650. end;
  3651. { If the LEA instruction can be converted into an arithmetic instruction,
  3652. it may be possible to then fold it in the next optimisation, otherwise
  3653. there's nothing more that can be optimised here. }
  3654. if not ConvertLEA(taicpu(hp1)) then
  3655. Exit;
  3656. end;
  3657. if (taicpu(p).oper[1]^.typ = top_reg) and
  3658. (hp1.typ = ait_instruction) and
  3659. GetNextInstruction(hp1, hp2) and
  3660. MatchInstruction(hp2,A_MOV,[]) and
  3661. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3662. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3663. (
  3664. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3665. {$ifdef x86_64}
  3666. or
  3667. (
  3668. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3669. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3670. )
  3671. {$endif x86_64}
  3672. ) then
  3673. begin
  3674. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3675. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3676. { change movsX/movzX reg/ref, reg2
  3677. add/sub/or/... reg3/$const, reg2
  3678. mov reg2 reg/ref
  3679. dealloc reg2
  3680. to
  3681. add/sub/or/... reg3/$const, reg/ref }
  3682. begin
  3683. TransferUsedRegs(TmpUsedRegs);
  3684. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3685. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3686. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3687. begin
  3688. { by example:
  3689. movswl %si,%eax movswl %si,%eax p
  3690. decl %eax addl %edx,%eax hp1
  3691. movw %ax,%si movw %ax,%si hp2
  3692. ->
  3693. movswl %si,%eax movswl %si,%eax p
  3694. decw %eax addw %edx,%eax hp1
  3695. movw %ax,%si movw %ax,%si hp2
  3696. }
  3697. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3698. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3699. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3700. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3701. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3702. {
  3703. ->
  3704. movswl %si,%eax movswl %si,%eax p
  3705. decw %si addw %dx,%si hp1
  3706. movw %ax,%si movw %ax,%si hp2
  3707. }
  3708. case taicpu(hp1).ops of
  3709. 1:
  3710. begin
  3711. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3712. if taicpu(hp1).oper[0]^.typ=top_reg then
  3713. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3714. end;
  3715. 2:
  3716. begin
  3717. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3718. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3719. (taicpu(hp1).opcode<>A_SHL) and
  3720. (taicpu(hp1).opcode<>A_SHR) and
  3721. (taicpu(hp1).opcode<>A_SAR) then
  3722. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3723. end;
  3724. else
  3725. internalerror(2008042701);
  3726. end;
  3727. {
  3728. ->
  3729. decw %si addw %dx,%si p
  3730. }
  3731. RemoveInstruction(hp2);
  3732. RemoveCurrentP(p, hp1);
  3733. Result:=True;
  3734. Exit;
  3735. end;
  3736. end;
  3737. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3738. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3739. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3740. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3741. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3742. )
  3743. {$ifdef i386}
  3744. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3745. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3746. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3747. {$endif i386}
  3748. then
  3749. { change movsX/movzX reg/ref, reg2
  3750. add/sub/or/... regX/$const, reg2
  3751. mov reg2, reg3
  3752. dealloc reg2
  3753. to
  3754. movsX/movzX reg/ref, reg3
  3755. add/sub/or/... reg3/$const, reg3
  3756. }
  3757. begin
  3758. TransferUsedRegs(TmpUsedRegs);
  3759. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3760. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3761. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3762. begin
  3763. { by example:
  3764. movswl %si,%eax movswl %si,%eax p
  3765. decl %eax addl %edx,%eax hp1
  3766. movw %ax,%si movw %ax,%si hp2
  3767. ->
  3768. movswl %si,%eax movswl %si,%eax p
  3769. decw %eax addw %edx,%eax hp1
  3770. movw %ax,%si movw %ax,%si hp2
  3771. }
  3772. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3773. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3774. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3775. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3776. { limit size of constants as well to avoid assembler errors, but
  3777. check opsize to avoid overflow when left shifting the 1 }
  3778. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3779. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3780. {$ifdef x86_64}
  3781. { Be careful of, for example:
  3782. movl %reg1,%reg2
  3783. addl %reg3,%reg2
  3784. movq %reg2,%reg4
  3785. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3786. }
  3787. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3788. begin
  3789. taicpu(hp2).changeopsize(S_L);
  3790. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3791. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3792. end;
  3793. {$endif x86_64}
  3794. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3795. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3796. if taicpu(p).oper[0]^.typ=top_reg then
  3797. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3798. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3799. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3800. {
  3801. ->
  3802. movswl %si,%eax movswl %si,%eax p
  3803. decw %si addw %dx,%si hp1
  3804. movw %ax,%si movw %ax,%si hp2
  3805. }
  3806. case taicpu(hp1).ops of
  3807. 1:
  3808. begin
  3809. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3810. if taicpu(hp1).oper[0]^.typ=top_reg then
  3811. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3812. end;
  3813. 2:
  3814. begin
  3815. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3816. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3817. (taicpu(hp1).opcode<>A_SHL) and
  3818. (taicpu(hp1).opcode<>A_SHR) and
  3819. (taicpu(hp1).opcode<>A_SAR) then
  3820. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3821. end;
  3822. else
  3823. internalerror(2018111801);
  3824. end;
  3825. {
  3826. ->
  3827. decw %si addw %dx,%si p
  3828. }
  3829. RemoveInstruction(hp2);
  3830. end;
  3831. end;
  3832. end;
  3833. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3834. GetNextInstruction(hp1, hp2) and
  3835. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3836. MatchOperand(Taicpu(p).oper[0]^,0) and
  3837. (Taicpu(p).oper[1]^.typ = top_reg) and
  3838. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3839. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3840. { mov reg1,0
  3841. bts reg1,operand1 --> mov reg1,operand2
  3842. or reg1,operand2 bts reg1,operand1}
  3843. begin
  3844. Taicpu(hp2).opcode:=A_MOV;
  3845. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3846. asml.remove(hp1);
  3847. insertllitem(hp2,hp2.next,hp1);
  3848. RemoveCurrentp(p, hp1);
  3849. Result:=true;
  3850. exit;
  3851. end;
  3852. {
  3853. mov ref,reg0
  3854. <op> reg0,reg1
  3855. dealloc reg0
  3856. to
  3857. <op> ref,reg1
  3858. }
  3859. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3860. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3861. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3862. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3863. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3864. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3865. begin
  3866. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3867. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3868. RemoveCurrentp(p, hp1);
  3869. Result:=true;
  3870. exit;
  3871. end;
  3872. {$ifdef x86_64}
  3873. { Convert:
  3874. movq x(ref),%reg64
  3875. shrq y,%reg64
  3876. To:
  3877. movl x+4(ref),%reg32
  3878. shrl y-32,%reg32 (Remove if y = 32)
  3879. }
  3880. if (taicpu(p).opsize = S_Q) and
  3881. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3882. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3883. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3884. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3885. (taicpu(hp1).oper[0]^.val >= 32) and
  3886. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3887. begin
  3888. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3889. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3890. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3891. { Convert to 32-bit }
  3892. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3893. taicpu(p).opsize := S_L;
  3894. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3895. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3896. if (taicpu(hp1).oper[0]^.val = 32) then
  3897. begin
  3898. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3899. RemoveInstruction(hp1);
  3900. end
  3901. else
  3902. begin
  3903. { This will potentially open up more arithmetic operations since
  3904. the peephole optimizer now has a big hint that only the lower
  3905. 32 bits are currently in use (and opcodes are smaller in size) }
  3906. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3907. taicpu(hp1).opsize := S_L;
  3908. Dec(taicpu(hp1).oper[0]^.val, 32);
  3909. DebugMsg(SPeepholeOptimization + PreMessage +
  3910. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3911. end;
  3912. Result := True;
  3913. Exit;
  3914. end;
  3915. {$endif x86_64}
  3916. { Backward optimisation. If we have:
  3917. func. %reg1,%reg2
  3918. mov %reg2,%reg3
  3919. (dealloc %reg2)
  3920. Change to:
  3921. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3922. }
  3923. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3924. begin
  3925. CurrentReg := taicpu(p).oper[0]^.reg;
  3926. ActiveReg := taicpu(p).oper[1]^.reg;
  3927. TransferUsedRegs(TmpUsedRegs);
  3928. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3929. GetLastInstruction(p, hp2) and
  3930. (hp2.typ = ait_instruction) and
  3931. { Have to make sure it's an instruction that only reads from
  3932. operand 1 and only writes (not reads or modifies) from operand 2;
  3933. in essence, a one-operand pure function such as BSR or POPCNT }
  3934. (taicpu(hp2).ops = 2) and
  3935. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3936. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3937. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3938. begin
  3939. case taicpu(hp2).opcode of
  3940. A_FSTSW, A_FNSTSW,
  3941. A_IN, A_INS, A_OUT, A_OUTS,
  3942. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3943. { These routines have explicit operands, but they are restricted in
  3944. what they can be (e.g. IN and OUT can only read from AL, AX or
  3945. EAX. }
  3946. A_CMOVcc:
  3947. { CMOV is not valid either because then CurrentReg will depend
  3948. on an unknown value if the condition is False and hence is
  3949. not a pure write }
  3950. ;
  3951. else
  3952. begin
  3953. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3954. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3955. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3956. RemoveCurrentp(p, hp1);
  3957. Result := True;
  3958. Exit;
  3959. end;
  3960. end;
  3961. end;
  3962. end;
  3963. end;
  3964. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3965. var
  3966. hp1 : tai;
  3967. begin
  3968. Result:=false;
  3969. if taicpu(p).ops <> 2 then
  3970. exit;
  3971. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3972. GetNextInstruction(p,hp1) then
  3973. begin
  3974. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3975. (taicpu(hp1).ops = 2) then
  3976. begin
  3977. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3978. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3979. { movXX reg1, mem1 or movXX mem1, reg1
  3980. movXX mem2, reg2 movXX reg2, mem2}
  3981. begin
  3982. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3983. { movXX reg1, mem1 or movXX mem1, reg1
  3984. movXX mem2, reg1 movXX reg2, mem1}
  3985. begin
  3986. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3987. begin
  3988. { Removes the second statement from
  3989. movXX reg1, mem1/reg2
  3990. movXX mem1/reg2, reg1
  3991. }
  3992. if taicpu(p).oper[0]^.typ=top_reg then
  3993. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3994. { Removes the second statement from
  3995. movXX mem1/reg1, reg2
  3996. movXX reg2, mem1/reg1
  3997. }
  3998. if (taicpu(p).oper[1]^.typ=top_reg) and
  3999. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4000. begin
  4001. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4002. RemoveInstruction(hp1);
  4003. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4004. Result:=true;
  4005. exit;
  4006. end
  4007. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4008. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4009. begin
  4010. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4011. RemoveInstruction(hp1);
  4012. Result:=true;
  4013. exit;
  4014. end;
  4015. end
  4016. end;
  4017. end;
  4018. end;
  4019. end;
  4020. end;
  4021. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4022. var
  4023. hp1 : tai;
  4024. begin
  4025. result:=false;
  4026. { replace
  4027. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4028. MovX %mreg2,%mreg1
  4029. dealloc %mreg2
  4030. by
  4031. <Op>X %mreg2,%mreg1
  4032. ?
  4033. }
  4034. if GetNextInstruction(p,hp1) and
  4035. { we mix single and double opperations here because we assume that the compiler
  4036. generates vmovapd only after double operations and vmovaps only after single operations }
  4037. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4038. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4039. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4040. (taicpu(p).oper[0]^.typ=top_reg) then
  4041. begin
  4042. TransferUsedRegs(TmpUsedRegs);
  4043. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4044. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4045. begin
  4046. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4047. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4048. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4049. RemoveInstruction(hp1);
  4050. result:=true;
  4051. end;
  4052. end;
  4053. end;
  4054. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4055. var
  4056. hp1, p_label, p_dist, hp1_dist: tai;
  4057. JumpLabel, JumpLabel_dist: TAsmLabel;
  4058. FirstValue, SecondValue: TCGInt;
  4059. begin
  4060. Result := False;
  4061. if (taicpu(p).oper[0]^.typ = top_const) and
  4062. (taicpu(p).oper[0]^.val <> -1) then
  4063. begin
  4064. { Convert unsigned maximum constants to -1 to aid optimisation }
  4065. case taicpu(p).opsize of
  4066. S_B:
  4067. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4068. begin
  4069. taicpu(p).oper[0]^.val := -1;
  4070. Result := True;
  4071. Exit;
  4072. end;
  4073. S_W:
  4074. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4075. begin
  4076. taicpu(p).oper[0]^.val := -1;
  4077. Result := True;
  4078. Exit;
  4079. end;
  4080. S_L:
  4081. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4082. begin
  4083. taicpu(p).oper[0]^.val := -1;
  4084. Result := True;
  4085. Exit;
  4086. end;
  4087. {$ifdef x86_64}
  4088. S_Q:
  4089. { Storing anything greater than $7FFFFFFF is not possible so do
  4090. nothing };
  4091. {$endif x86_64}
  4092. else
  4093. InternalError(2021121001);
  4094. end;
  4095. end;
  4096. if GetNextInstruction(p, hp1) and
  4097. TrySwapMovCmp(p, hp1) then
  4098. begin
  4099. Result := True;
  4100. Exit;
  4101. end;
  4102. { Search for:
  4103. test $x,(reg/ref)
  4104. jne @lbl1
  4105. test $y,(reg/ref) (same register or reference)
  4106. jne @lbl1
  4107. Change to:
  4108. test $(x or y),(reg/ref)
  4109. jne @lbl1
  4110. (Note, this doesn't work with je instead of jne)
  4111. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4112. Also search for:
  4113. test $x,(reg/ref)
  4114. je @lbl1
  4115. test $y,(reg/ref)
  4116. je/jne @lbl2
  4117. If (x or y) = x, then the second jump is deterministic
  4118. }
  4119. if (
  4120. (
  4121. (taicpu(p).oper[0]^.typ = top_const) or
  4122. (
  4123. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4124. (taicpu(p).oper[0]^.typ = top_reg) and
  4125. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4126. )
  4127. ) and
  4128. MatchInstruction(hp1, A_JCC, [])
  4129. ) then
  4130. begin
  4131. if (taicpu(p).oper[0]^.typ = top_reg) and
  4132. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4133. FirstValue := -1
  4134. else
  4135. FirstValue := taicpu(p).oper[0]^.val;
  4136. { If we have several test/jne's in a row, it might be the case that
  4137. the second label doesn't go to the same location, but the one
  4138. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4139. so accommodate for this with a while loop.
  4140. }
  4141. hp1_dist := hp1;
  4142. if GetNextInstruction(hp1, p_dist) and
  4143. (p_dist.typ = ait_instruction) and
  4144. (
  4145. (
  4146. (taicpu(p_dist).opcode = A_TEST) and
  4147. (
  4148. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4149. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4150. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4151. )
  4152. ) or
  4153. (
  4154. { cmp 0,%reg = test %reg,%reg }
  4155. (taicpu(p_dist).opcode = A_CMP) and
  4156. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4157. )
  4158. ) and
  4159. { Make sure the destination operands are actually the same }
  4160. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4161. GetNextInstruction(p_dist, hp1_dist) and
  4162. MatchInstruction(hp1_dist, A_JCC, []) then
  4163. begin
  4164. if
  4165. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4166. (
  4167. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4168. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4169. ) then
  4170. SecondValue := -1
  4171. else
  4172. SecondValue := taicpu(p_dist).oper[0]^.val;
  4173. { If both of the TEST constants are identical, delete the second
  4174. TEST that is unnecessary. }
  4175. if (FirstValue = SecondValue) then
  4176. begin
  4177. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4178. RemoveInstruction(p_dist);
  4179. { Don't let the flags register become deallocated and reallocated between the jumps }
  4180. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4181. Result := True;
  4182. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4183. begin
  4184. { Since the second jump's condition is a subset of the first, we
  4185. know it will never branch because the first jump dominates it.
  4186. Get it out of the way now rather than wait for the jump
  4187. optimisations for a speed boost. }
  4188. if IsJumpToLabel(taicpu(hp1_dist)) then
  4189. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4190. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4191. RemoveInstruction(hp1_dist);
  4192. end
  4193. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4194. begin
  4195. { If the inverse of the first condition is a subset of the second,
  4196. the second one will definitely branch if the first one doesn't }
  4197. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4198. MakeUnconditional(taicpu(hp1_dist));
  4199. RemoveDeadCodeAfterJump(hp1_dist);
  4200. end;
  4201. Exit;
  4202. end;
  4203. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4204. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4205. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4206. then the second jump will never branch, so it can also be
  4207. removed regardless of where it goes }
  4208. (
  4209. (FirstValue = -1) or
  4210. (SecondValue = -1) or
  4211. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4212. ) then
  4213. begin
  4214. { Same jump location... can be a register since nothing's changed }
  4215. { If any of the entries are equivalent to test %reg,%reg, then the
  4216. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4217. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4218. if IsJumpToLabel(taicpu(hp1_dist)) then
  4219. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4220. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4221. RemoveInstruction(hp1_dist);
  4222. { Only remove the second test if no jumps or other conditional instructions follow }
  4223. TransferUsedRegs(TmpUsedRegs);
  4224. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4225. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4226. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4227. RemoveInstruction(p_dist);
  4228. Result := True;
  4229. Exit;
  4230. end;
  4231. end;
  4232. end;
  4233. { Search for:
  4234. test %reg,%reg
  4235. j(c1) @lbl1
  4236. ...
  4237. @lbl:
  4238. test %reg,%reg (same register)
  4239. j(c2) @lbl2
  4240. If c2 is a subset of c1, change to:
  4241. test %reg,%reg
  4242. j(c1) @lbl2
  4243. (@lbl1 may become a dead label as a result)
  4244. }
  4245. if (taicpu(p).oper[1]^.typ = top_reg) and
  4246. (taicpu(p).oper[0]^.typ = top_reg) and
  4247. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4248. MatchInstruction(hp1, A_JCC, []) and
  4249. IsJumpToLabel(taicpu(hp1)) then
  4250. begin
  4251. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4252. p_label := nil;
  4253. if Assigned(JumpLabel) then
  4254. p_label := getlabelwithsym(JumpLabel);
  4255. if Assigned(p_label) and
  4256. GetNextInstruction(p_label, p_dist) and
  4257. MatchInstruction(p_dist, A_TEST, []) and
  4258. { It's fine if the second test uses smaller sub-registers }
  4259. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4260. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4261. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4262. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4263. GetNextInstruction(p_dist, hp1_dist) and
  4264. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4265. begin
  4266. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4267. if JumpLabel = JumpLabel_dist then
  4268. { This is an infinite loop }
  4269. Exit;
  4270. { Best optimisation when the first condition is a subset (or equal) of the second }
  4271. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4272. begin
  4273. { Any registers used here will already be allocated }
  4274. if Assigned(JumpLabel_dist) then
  4275. JumpLabel_dist.IncRefs;
  4276. if Assigned(JumpLabel) then
  4277. JumpLabel.DecRefs;
  4278. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4279. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4280. Result := True;
  4281. Exit;
  4282. end;
  4283. end;
  4284. end;
  4285. end;
  4286. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4287. var
  4288. hp1, hp2: tai;
  4289. ActiveReg: TRegister;
  4290. OldOffset: asizeint;
  4291. ThisConst: TCGInt;
  4292. function RegDeallocated: Boolean;
  4293. begin
  4294. TransferUsedRegs(TmpUsedRegs);
  4295. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4296. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4297. end;
  4298. begin
  4299. result:=false;
  4300. hp1 := nil;
  4301. { replace
  4302. addX const,%reg1
  4303. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4304. dealloc %reg1
  4305. by
  4306. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4307. }
  4308. if MatchOpType(taicpu(p),top_const,top_reg) then
  4309. begin
  4310. ActiveReg := taicpu(p).oper[1]^.reg;
  4311. { Ensures the entire register was updated }
  4312. if (taicpu(p).opsize >= S_L) and
  4313. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4314. MatchInstruction(hp1,A_LEA,[]) and
  4315. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4316. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4317. (
  4318. { Cover the case where the register in the reference is also the destination register }
  4319. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4320. (
  4321. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4322. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4323. RegDeallocated
  4324. )
  4325. ) then
  4326. begin
  4327. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4328. {$push}
  4329. {$R-}{$Q-}
  4330. { Explicitly disable overflow checking for these offset calculation
  4331. as those do not matter for the final result }
  4332. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4333. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4334. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4335. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4336. {$pop}
  4337. {$ifdef x86_64}
  4338. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4339. begin
  4340. { Overflow; abort }
  4341. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4342. end
  4343. else
  4344. {$endif x86_64}
  4345. begin
  4346. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4347. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4348. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4349. RemoveCurrentP(p, hp1)
  4350. else
  4351. RemoveCurrentP(p);
  4352. result:=true;
  4353. Exit;
  4354. end;
  4355. end;
  4356. if (
  4357. { Save calling GetNextInstructionUsingReg again }
  4358. Assigned(hp1) or
  4359. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4360. ) and
  4361. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4362. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4363. begin
  4364. if taicpu(hp1).oper[0]^.typ = top_const then
  4365. begin
  4366. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4367. if taicpu(hp1).opcode = A_ADD then
  4368. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4369. else
  4370. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4371. Result := True;
  4372. { Handle any overflows }
  4373. case taicpu(p).opsize of
  4374. S_B:
  4375. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4376. S_W:
  4377. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4378. S_L:
  4379. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4380. {$ifdef x86_64}
  4381. S_Q:
  4382. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4383. { Overflow; abort }
  4384. Result := False
  4385. else
  4386. taicpu(p).oper[0]^.val := ThisConst;
  4387. {$endif x86_64}
  4388. else
  4389. InternalError(2021102610);
  4390. end;
  4391. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4392. if Result then
  4393. begin
  4394. if (taicpu(p).oper[0]^.val < 0) and
  4395. (
  4396. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4397. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4398. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4399. ) then
  4400. begin
  4401. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4402. taicpu(p).opcode := A_SUB;
  4403. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4404. end
  4405. else
  4406. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4407. RemoveInstruction(hp1);
  4408. end;
  4409. end
  4410. else
  4411. begin
  4412. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4413. TransferUsedRegs(TmpUsedRegs);
  4414. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4415. hp2 := p;
  4416. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4417. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4418. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4419. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4420. begin
  4421. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4422. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4423. Asml.Remove(p);
  4424. Asml.InsertAfter(p, hp1);
  4425. p := hp1;
  4426. Result := True;
  4427. end;
  4428. end;
  4429. end;
  4430. end;
  4431. end;
  4432. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4433. var
  4434. hp1: tai;
  4435. ref: Integer;
  4436. saveref: treference;
  4437. TempReg: TRegister;
  4438. Multiple: TCGInt;
  4439. begin
  4440. Result:=false;
  4441. { removes seg register prefixes from LEA operations, as they
  4442. don't do anything}
  4443. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4444. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4445. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4446. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4447. (
  4448. { do not mess with leas accessing the stack pointer
  4449. unless it's a null operation }
  4450. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4451. (
  4452. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4453. (taicpu(p).oper[0]^.ref^.offset = 0)
  4454. )
  4455. ) and
  4456. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4457. begin
  4458. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4459. begin
  4460. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4461. begin
  4462. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4463. taicpu(p).oper[1]^.reg);
  4464. InsertLLItem(p.previous,p.next, hp1);
  4465. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4466. p.free;
  4467. p:=hp1;
  4468. end
  4469. else
  4470. begin
  4471. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4472. RemoveCurrentP(p);
  4473. end;
  4474. Result:=true;
  4475. exit;
  4476. end
  4477. else if (
  4478. { continue to use lea to adjust the stack pointer,
  4479. it is the recommended way, but only if not optimizing for size }
  4480. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4481. (cs_opt_size in current_settings.optimizerswitches)
  4482. ) and
  4483. { If the flags register is in use, don't change the instruction
  4484. to an ADD otherwise this will scramble the flags. [Kit] }
  4485. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4486. ConvertLEA(taicpu(p)) then
  4487. begin
  4488. Result:=true;
  4489. exit;
  4490. end;
  4491. end;
  4492. if GetNextInstruction(p,hp1) and
  4493. (hp1.typ=ait_instruction) then
  4494. begin
  4495. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4496. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4497. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4498. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4499. begin
  4500. TransferUsedRegs(TmpUsedRegs);
  4501. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4502. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4503. begin
  4504. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4505. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4506. RemoveInstruction(hp1);
  4507. result:=true;
  4508. exit;
  4509. end;
  4510. end;
  4511. { changes
  4512. lea <ref1>, reg1
  4513. <op> ...,<ref. with reg1>,...
  4514. to
  4515. <op> ...,<ref1>,... }
  4516. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4517. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4518. not(MatchInstruction(hp1,A_LEA,[])) then
  4519. begin
  4520. { find a reference which uses reg1 }
  4521. 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
  4522. ref:=0
  4523. 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
  4524. ref:=1
  4525. else
  4526. ref:=-1;
  4527. if (ref<>-1) and
  4528. { reg1 must be either the base or the index }
  4529. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4530. begin
  4531. { reg1 can be removed from the reference }
  4532. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4533. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4534. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4535. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4536. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4537. else
  4538. Internalerror(2019111201);
  4539. { check if the can insert all data of the lea into the second instruction }
  4540. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4541. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4542. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4543. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4544. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4545. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4546. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4547. {$ifdef x86_64}
  4548. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4549. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4550. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4551. )
  4552. {$endif x86_64}
  4553. then
  4554. begin
  4555. { reg1 might not used by the second instruction after it is remove from the reference }
  4556. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4557. begin
  4558. TransferUsedRegs(TmpUsedRegs);
  4559. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4560. { reg1 is not updated so it might not be used afterwards }
  4561. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4562. begin
  4563. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4564. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4565. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4566. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4567. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4568. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4569. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4570. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4571. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4572. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4573. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4574. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4575. RemoveCurrentP(p, hp1);
  4576. result:=true;
  4577. exit;
  4578. end
  4579. end;
  4580. end;
  4581. { recover }
  4582. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4583. end;
  4584. end;
  4585. end;
  4586. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4587. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4588. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4589. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4590. begin
  4591. { Check common LEA/LEA conditions }
  4592. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4593. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4594. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4595. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4596. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4597. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4598. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4599. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4600. (
  4601. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4602. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4603. ) and (
  4604. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4605. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4606. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4607. ) then
  4608. begin
  4609. { changes
  4610. lea (regX,scale), reg1
  4611. lea offset(reg1,reg1), reg1
  4612. to
  4613. lea offset(regX,scale*2), reg1
  4614. and
  4615. lea (regX,scale1), reg1
  4616. lea offset(reg1,scale2), reg1
  4617. to
  4618. lea offset(regX,scale1*scale2), reg1
  4619. ... so long as the final scale does not exceed 8
  4620. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4621. }
  4622. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4623. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4624. (
  4625. (
  4626. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4627. ) or (
  4628. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4629. (
  4630. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4631. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4632. )
  4633. )
  4634. ) and (
  4635. (
  4636. { lea (reg1,scale2), reg1 variant }
  4637. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4638. (
  4639. (
  4640. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4641. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4642. ) or (
  4643. { lea (regX,regX), reg1 variant }
  4644. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4645. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4646. )
  4647. )
  4648. ) or (
  4649. { lea (reg1,reg1), reg1 variant }
  4650. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4651. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4652. )
  4653. ) then
  4654. begin
  4655. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4656. { Make everything homogeneous to make calculations easier }
  4657. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4658. begin
  4659. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4660. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4661. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4662. else
  4663. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4664. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4665. end;
  4666. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4667. begin
  4668. { Just to prevent miscalculations }
  4669. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4670. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4671. else
  4672. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4673. end
  4674. else
  4675. begin
  4676. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4677. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4678. end;
  4679. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4680. RemoveCurrentP(p);
  4681. result:=true;
  4682. exit;
  4683. end
  4684. { changes
  4685. lea offset1(regX), reg1
  4686. lea offset2(reg1), reg1
  4687. to
  4688. lea offset1+offset2(regX), reg1 }
  4689. else if
  4690. (
  4691. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4692. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4693. ) or (
  4694. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4695. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4696. (
  4697. (
  4698. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4699. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4700. ) or (
  4701. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4702. (
  4703. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4704. (
  4705. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4706. (
  4707. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4708. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4709. )
  4710. )
  4711. )
  4712. )
  4713. )
  4714. ) then
  4715. begin
  4716. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4717. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4718. begin
  4719. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4720. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4721. { if the register is used as index and base, we have to increase for base as well
  4722. and adapt base }
  4723. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4724. begin
  4725. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4726. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4727. end;
  4728. end
  4729. else
  4730. begin
  4731. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4732. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4733. end;
  4734. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4735. begin
  4736. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4737. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4738. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4739. end;
  4740. RemoveCurrentP(p);
  4741. result:=true;
  4742. exit;
  4743. end;
  4744. end;
  4745. { Change:
  4746. leal/q $x(%reg1),%reg2
  4747. ...
  4748. shll/q $y,%reg2
  4749. To:
  4750. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4751. }
  4752. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4753. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4754. (taicpu(hp1).oper[0]^.val <= 3) then
  4755. begin
  4756. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4757. TransferUsedRegs(TmpUsedRegs);
  4758. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4759. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4760. if
  4761. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4762. (this works even if scalefactor is zero) }
  4763. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4764. { Ensure offset doesn't go out of bounds }
  4765. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4766. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4767. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4768. (
  4769. (
  4770. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4771. (
  4772. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4773. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4774. (
  4775. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4776. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4777. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4778. )
  4779. )
  4780. ) or (
  4781. (
  4782. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4783. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4784. ) and
  4785. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4786. )
  4787. ) then
  4788. begin
  4789. repeat
  4790. with taicpu(p).oper[0]^.ref^ do
  4791. begin
  4792. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4793. if index = base then
  4794. begin
  4795. if Multiple > 4 then
  4796. { Optimisation will no longer work because resultant
  4797. scale factor will exceed 8 }
  4798. Break;
  4799. base := NR_NO;
  4800. scalefactor := 2;
  4801. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4802. end
  4803. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4804. begin
  4805. { Scale factor only works on the index register }
  4806. index := base;
  4807. base := NR_NO;
  4808. end;
  4809. { For safety }
  4810. if scalefactor <= 1 then
  4811. begin
  4812. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4813. scalefactor := Multiple;
  4814. end
  4815. else
  4816. begin
  4817. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4818. scalefactor := scalefactor * Multiple;
  4819. end;
  4820. offset := offset * Multiple;
  4821. end;
  4822. RemoveInstruction(hp1);
  4823. Result := True;
  4824. Exit;
  4825. { This repeat..until loop exists for the benefit of Break }
  4826. until True;
  4827. end;
  4828. end;
  4829. end;
  4830. end;
  4831. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4832. var
  4833. hp1 : tai;
  4834. begin
  4835. DoSubAddOpt := False;
  4836. if taicpu(p).oper[0]^.typ <> top_const then
  4837. { Should have been confirmed before calling }
  4838. InternalError(2021102601);
  4839. if GetLastInstruction(p, hp1) and
  4840. (hp1.typ = ait_instruction) and
  4841. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4842. case taicpu(hp1).opcode Of
  4843. A_DEC:
  4844. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4845. begin
  4846. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4847. RemoveInstruction(hp1);
  4848. end;
  4849. A_SUB:
  4850. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4851. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4852. begin
  4853. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4854. RemoveInstruction(hp1);
  4855. end;
  4856. A_ADD:
  4857. begin
  4858. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4859. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4860. begin
  4861. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4862. RemoveInstruction(hp1);
  4863. if (taicpu(p).oper[0]^.val = 0) then
  4864. begin
  4865. hp1 := tai(p.next);
  4866. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4867. if not GetLastInstruction(hp1, p) then
  4868. p := hp1;
  4869. DoSubAddOpt := True;
  4870. end
  4871. end;
  4872. end;
  4873. else
  4874. ;
  4875. end;
  4876. end;
  4877. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4878. begin
  4879. Result := False;
  4880. if UpdateTmpUsedRegs then
  4881. TransferUsedRegs(TmpUsedRegs);
  4882. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4883. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4884. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4885. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4886. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4887. (
  4888. (
  4889. (taicpu(hp1).opcode = A_TEST)
  4890. ) or (
  4891. (taicpu(hp1).opcode = A_CMP) and
  4892. { A sanity check more than anything }
  4893. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4894. )
  4895. ) then
  4896. begin
  4897. { change
  4898. mov mem, %reg
  4899. cmp/test x, %reg / test %reg,%reg
  4900. (reg deallocated)
  4901. to
  4902. cmp/test x, mem / cmp 0, mem
  4903. }
  4904. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4905. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4906. begin
  4907. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4908. if (taicpu(hp1).opcode = A_TEST) and
  4909. (
  4910. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4911. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4912. ) then
  4913. begin
  4914. taicpu(hp1).opcode := A_CMP;
  4915. taicpu(hp1).loadconst(0, 0);
  4916. end;
  4917. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4918. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4919. RemoveCurrentP(p, hp1);
  4920. Result := True;
  4921. Exit;
  4922. end;
  4923. end;
  4924. end;
  4925. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4926. var
  4927. hp1, hp2: tai;
  4928. ActiveReg: TRegister;
  4929. OldOffset: asizeint;
  4930. ThisConst: TCGInt;
  4931. function RegDeallocated: Boolean;
  4932. begin
  4933. TransferUsedRegs(TmpUsedRegs);
  4934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4935. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4936. end;
  4937. begin
  4938. Result:=false;
  4939. hp1 := nil;
  4940. { replace
  4941. subX const,%reg1
  4942. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4943. dealloc %reg1
  4944. by
  4945. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4946. }
  4947. if MatchOpType(taicpu(p),top_const,top_reg) then
  4948. begin
  4949. ActiveReg := taicpu(p).oper[1]^.reg;
  4950. { Ensures the entire register was updated }
  4951. if (taicpu(p).opsize >= S_L) and
  4952. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4953. MatchInstruction(hp1,A_LEA,[]) and
  4954. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4955. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4956. (
  4957. { Cover the case where the register in the reference is also the destination register }
  4958. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4959. (
  4960. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4961. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4962. RegDeallocated
  4963. )
  4964. ) then
  4965. begin
  4966. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4967. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4968. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4969. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4970. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4971. {$ifdef x86_64}
  4972. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4973. begin
  4974. { Overflow; abort }
  4975. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4976. end
  4977. else
  4978. {$endif x86_64}
  4979. begin
  4980. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4981. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4982. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4983. RemoveCurrentP(p, hp1)
  4984. else
  4985. RemoveCurrentP(p);
  4986. result:=true;
  4987. Exit;
  4988. end;
  4989. end;
  4990. if (
  4991. { Save calling GetNextInstructionUsingReg again }
  4992. Assigned(hp1) or
  4993. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4994. ) and
  4995. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4996. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4997. begin
  4998. if taicpu(hp1).oper[0]^.typ = top_const then
  4999. begin
  5000. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5001. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5002. Result := True;
  5003. { Handle any overflows }
  5004. case taicpu(p).opsize of
  5005. S_B:
  5006. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5007. S_W:
  5008. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5009. S_L:
  5010. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5011. {$ifdef x86_64}
  5012. S_Q:
  5013. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5014. { Overflow; abort }
  5015. Result := False
  5016. else
  5017. taicpu(p).oper[0]^.val := ThisConst;
  5018. {$endif x86_64}
  5019. else
  5020. InternalError(2021102610);
  5021. end;
  5022. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5023. if Result then
  5024. begin
  5025. if (taicpu(p).oper[0]^.val < 0) and
  5026. (
  5027. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5028. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5029. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5030. ) then
  5031. begin
  5032. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5033. taicpu(p).opcode := A_SUB;
  5034. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5035. end
  5036. else
  5037. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5038. RemoveInstruction(hp1);
  5039. end;
  5040. end
  5041. else
  5042. begin
  5043. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5044. TransferUsedRegs(TmpUsedRegs);
  5045. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5046. hp2 := p;
  5047. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5048. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5049. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5050. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5051. begin
  5052. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5053. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5054. Asml.Remove(p);
  5055. Asml.InsertAfter(p, hp1);
  5056. p := hp1;
  5057. Result := True;
  5058. Exit;
  5059. end;
  5060. end;
  5061. end;
  5062. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5063. { * change "sub/add const1, reg" or "dec reg" followed by
  5064. "sub const2, reg" to one "sub ..., reg" }
  5065. {$ifdef i386}
  5066. if (taicpu(p).oper[0]^.val = 2) and
  5067. (ActiveReg = NR_ESP) and
  5068. { Don't do the sub/push optimization if the sub }
  5069. { comes from setting up the stack frame (JM) }
  5070. (not(GetLastInstruction(p,hp1)) or
  5071. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5072. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5073. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5074. begin
  5075. hp1 := tai(p.next);
  5076. while Assigned(hp1) and
  5077. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5078. not RegReadByInstruction(NR_ESP,hp1) and
  5079. not RegModifiedByInstruction(NR_ESP,hp1) do
  5080. hp1 := tai(hp1.next);
  5081. if Assigned(hp1) and
  5082. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5083. begin
  5084. taicpu(hp1).changeopsize(S_L);
  5085. if taicpu(hp1).oper[0]^.typ=top_reg then
  5086. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5087. hp1 := tai(p.next);
  5088. RemoveCurrentp(p, hp1);
  5089. Result:=true;
  5090. exit;
  5091. end;
  5092. end;
  5093. {$endif i386}
  5094. if DoSubAddOpt(p) then
  5095. Result:=true;
  5096. end;
  5097. end;
  5098. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5099. var
  5100. TmpBool1,TmpBool2 : Boolean;
  5101. tmpref : treference;
  5102. hp1,hp2: tai;
  5103. mask: tcgint;
  5104. begin
  5105. Result:=false;
  5106. { All these optimisations work on "shl/sal const,%reg" }
  5107. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5108. Exit;
  5109. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5110. (taicpu(p).oper[0]^.val <= 3) then
  5111. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5112. begin
  5113. { should we check the next instruction? }
  5114. TmpBool1 := True;
  5115. { have we found an add/sub which could be
  5116. integrated in the lea? }
  5117. TmpBool2 := False;
  5118. reference_reset(tmpref,2,[]);
  5119. TmpRef.index := taicpu(p).oper[1]^.reg;
  5120. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5121. while TmpBool1 and
  5122. GetNextInstruction(p, hp1) and
  5123. (tai(hp1).typ = ait_instruction) and
  5124. ((((taicpu(hp1).opcode = A_ADD) or
  5125. (taicpu(hp1).opcode = A_SUB)) and
  5126. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5127. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5128. (((taicpu(hp1).opcode = A_INC) or
  5129. (taicpu(hp1).opcode = A_DEC)) and
  5130. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5131. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5132. ((taicpu(hp1).opcode = A_LEA) and
  5133. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5134. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5135. (not GetNextInstruction(hp1,hp2) or
  5136. not instrReadsFlags(hp2)) Do
  5137. begin
  5138. TmpBool1 := False;
  5139. if taicpu(hp1).opcode=A_LEA then
  5140. begin
  5141. if (TmpRef.base = NR_NO) and
  5142. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5143. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5144. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5145. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5146. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5147. begin
  5148. TmpBool1 := True;
  5149. TmpBool2 := True;
  5150. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5151. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5152. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5153. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5154. RemoveInstruction(hp1);
  5155. end
  5156. end
  5157. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5158. begin
  5159. TmpBool1 := True;
  5160. TmpBool2 := True;
  5161. case taicpu(hp1).opcode of
  5162. A_ADD:
  5163. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5164. A_SUB:
  5165. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5166. else
  5167. internalerror(2019050536);
  5168. end;
  5169. RemoveInstruction(hp1);
  5170. end
  5171. else
  5172. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5173. (((taicpu(hp1).opcode = A_ADD) and
  5174. (TmpRef.base = NR_NO)) or
  5175. (taicpu(hp1).opcode = A_INC) or
  5176. (taicpu(hp1).opcode = A_DEC)) then
  5177. begin
  5178. TmpBool1 := True;
  5179. TmpBool2 := True;
  5180. case taicpu(hp1).opcode of
  5181. A_ADD:
  5182. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5183. A_INC:
  5184. inc(TmpRef.offset);
  5185. A_DEC:
  5186. dec(TmpRef.offset);
  5187. else
  5188. internalerror(2019050535);
  5189. end;
  5190. RemoveInstruction(hp1);
  5191. end;
  5192. end;
  5193. if TmpBool2
  5194. {$ifndef x86_64}
  5195. or
  5196. ((current_settings.optimizecputype < cpu_Pentium2) and
  5197. (taicpu(p).oper[0]^.val <= 3) and
  5198. not(cs_opt_size in current_settings.optimizerswitches))
  5199. {$endif x86_64}
  5200. then
  5201. begin
  5202. if not(TmpBool2) and
  5203. (taicpu(p).oper[0]^.val=1) then
  5204. begin
  5205. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5206. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5207. end
  5208. else
  5209. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5210. taicpu(p).oper[1]^.reg);
  5211. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5212. InsertLLItem(p.previous, p.next, hp1);
  5213. p.free;
  5214. p := hp1;
  5215. end;
  5216. end
  5217. {$ifndef x86_64}
  5218. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5219. begin
  5220. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5221. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5222. (unlike shl, which is only Tairable in the U pipe) }
  5223. if taicpu(p).oper[0]^.val=1 then
  5224. begin
  5225. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5226. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5227. InsertLLItem(p.previous, p.next, hp1);
  5228. p.free;
  5229. p := hp1;
  5230. end
  5231. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5232. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5233. else if (taicpu(p).opsize = S_L) and
  5234. (taicpu(p).oper[0]^.val<= 3) then
  5235. begin
  5236. reference_reset(tmpref,2,[]);
  5237. TmpRef.index := taicpu(p).oper[1]^.reg;
  5238. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5239. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5240. InsertLLItem(p.previous, p.next, hp1);
  5241. p.free;
  5242. p := hp1;
  5243. end;
  5244. end
  5245. {$endif x86_64}
  5246. else if
  5247. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5248. (
  5249. (
  5250. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5251. SetAndTest(hp1, hp2)
  5252. {$ifdef x86_64}
  5253. ) or
  5254. (
  5255. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5256. GetNextInstruction(hp1, hp2) and
  5257. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5258. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5259. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5260. {$endif x86_64}
  5261. )
  5262. ) and
  5263. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5264. begin
  5265. { Change:
  5266. shl x, %reg1
  5267. mov -(1<<x), %reg2
  5268. and %reg2, %reg1
  5269. Or:
  5270. shl x, %reg1
  5271. and -(1<<x), %reg1
  5272. To just:
  5273. shl x, %reg1
  5274. Since the and operation only zeroes bits that are already zero from the shl operation
  5275. }
  5276. case taicpu(p).oper[0]^.val of
  5277. 8:
  5278. mask:=$FFFFFFFFFFFFFF00;
  5279. 16:
  5280. mask:=$FFFFFFFFFFFF0000;
  5281. 32:
  5282. mask:=$FFFFFFFF00000000;
  5283. 63:
  5284. { Constant pre-calculated to prevent overflow errors with Int64 }
  5285. mask:=$8000000000000000;
  5286. else
  5287. begin
  5288. if taicpu(p).oper[0]^.val >= 64 then
  5289. { Shouldn't happen realistically, since the register
  5290. is guaranteed to be set to zero at this point }
  5291. mask := 0
  5292. else
  5293. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5294. end;
  5295. end;
  5296. if taicpu(hp1).oper[0]^.val = mask then
  5297. begin
  5298. { Everything checks out, perform the optimisation, as long as
  5299. the FLAGS register isn't being used}
  5300. TransferUsedRegs(TmpUsedRegs);
  5301. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5302. {$ifdef x86_64}
  5303. if (hp1 <> hp2) then
  5304. begin
  5305. { "shl/mov/and" version }
  5306. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5307. { Don't do the optimisation if the FLAGS register is in use }
  5308. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5309. begin
  5310. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5311. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5312. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5313. begin
  5314. RemoveInstruction(hp1);
  5315. Result := True;
  5316. end;
  5317. { Only set Result to True if the 'mov' instruction was removed }
  5318. RemoveInstruction(hp2);
  5319. end;
  5320. end
  5321. else
  5322. {$endif x86_64}
  5323. begin
  5324. { "shl/and" version }
  5325. { Don't do the optimisation if the FLAGS register is in use }
  5326. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5327. begin
  5328. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5329. RemoveInstruction(hp1);
  5330. Result := True;
  5331. end;
  5332. end;
  5333. Exit;
  5334. end
  5335. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5336. begin
  5337. { Even if the mask doesn't allow for its removal, we might be
  5338. able to optimise the mask for the "shl/and" version, which
  5339. may permit other peephole optimisations }
  5340. {$ifdef DEBUG_AOPTCPU}
  5341. mask := taicpu(hp1).oper[0]^.val and mask;
  5342. if taicpu(hp1).oper[0]^.val <> mask then
  5343. begin
  5344. DebugMsg(
  5345. SPeepholeOptimization +
  5346. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5347. ' to $' + debug_tostr(mask) +
  5348. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5349. taicpu(hp1).oper[0]^.val := mask;
  5350. end;
  5351. {$else DEBUG_AOPTCPU}
  5352. { If debugging is off, just set the operand even if it's the same }
  5353. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5354. {$endif DEBUG_AOPTCPU}
  5355. end;
  5356. end;
  5357. {
  5358. change
  5359. shl/sal const,reg
  5360. <op> ...(...,reg,1),...
  5361. into
  5362. <op> ...(...,reg,1 shl const),...
  5363. if const in 1..3
  5364. }
  5365. if MatchOpType(taicpu(p), top_const, top_reg) and
  5366. (taicpu(p).oper[0]^.val in [1..3]) and
  5367. GetNextInstruction(p, hp1) and
  5368. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5369. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5370. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5371. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5372. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5373. begin
  5374. TransferUsedRegs(TmpUsedRegs);
  5375. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5376. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5377. begin
  5378. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5379. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5380. RemoveCurrentP(p);
  5381. Result:=true;
  5382. end;
  5383. end;
  5384. end;
  5385. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5386. var
  5387. CurrentRef: TReference;
  5388. FullReg: TRegister;
  5389. hp1, hp2: tai;
  5390. begin
  5391. Result := False;
  5392. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5393. Exit;
  5394. { We assume you've checked if the operand is actually a reference by
  5395. this point. If it isn't, you'll most likely get an access violation }
  5396. CurrentRef := first_mov.oper[1]^.ref^;
  5397. { Memory must be aligned }
  5398. if (CurrentRef.offset mod 4) <> 0 then
  5399. Exit;
  5400. Inc(CurrentRef.offset);
  5401. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5402. if MatchOperand(second_mov.oper[0]^, 0) and
  5403. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5404. GetNextInstruction(second_mov, hp1) and
  5405. (hp1.typ = ait_instruction) and
  5406. (taicpu(hp1).opcode = A_MOV) and
  5407. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5408. (taicpu(hp1).oper[0]^.val = 0) then
  5409. begin
  5410. Inc(CurrentRef.offset);
  5411. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5412. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5413. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5414. begin
  5415. case taicpu(hp1).opsize of
  5416. S_B:
  5417. if GetNextInstruction(hp1, hp2) and
  5418. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5419. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5420. (taicpu(hp2).oper[0]^.val = 0) then
  5421. begin
  5422. Inc(CurrentRef.offset);
  5423. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5424. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5425. (taicpu(hp2).opsize = S_B) then
  5426. begin
  5427. RemoveInstruction(hp1);
  5428. RemoveInstruction(hp2);
  5429. first_mov.opsize := S_L;
  5430. if first_mov.oper[0]^.typ = top_reg then
  5431. begin
  5432. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5433. { Reuse second_mov as a MOVZX instruction }
  5434. second_mov.opcode := A_MOVZX;
  5435. second_mov.opsize := S_BL;
  5436. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5437. second_mov.loadreg(1, FullReg);
  5438. first_mov.oper[0]^.reg := FullReg;
  5439. asml.Remove(second_mov);
  5440. asml.InsertBefore(second_mov, first_mov);
  5441. end
  5442. else
  5443. { It's a value }
  5444. begin
  5445. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5446. RemoveInstruction(second_mov);
  5447. end;
  5448. Result := True;
  5449. Exit;
  5450. end;
  5451. end;
  5452. S_W:
  5453. begin
  5454. RemoveInstruction(hp1);
  5455. first_mov.opsize := S_L;
  5456. if first_mov.oper[0]^.typ = top_reg then
  5457. begin
  5458. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5459. { Reuse second_mov as a MOVZX instruction }
  5460. second_mov.opcode := A_MOVZX;
  5461. second_mov.opsize := S_BL;
  5462. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5463. second_mov.loadreg(1, FullReg);
  5464. first_mov.oper[0]^.reg := FullReg;
  5465. asml.Remove(second_mov);
  5466. asml.InsertBefore(second_mov, first_mov);
  5467. end
  5468. else
  5469. { It's a value }
  5470. begin
  5471. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5472. RemoveInstruction(second_mov);
  5473. end;
  5474. Result := True;
  5475. Exit;
  5476. end;
  5477. else
  5478. ;
  5479. end;
  5480. end;
  5481. end;
  5482. end;
  5483. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5484. { returns true if a "continue" should be done after this optimization }
  5485. var
  5486. hp1, hp2: tai;
  5487. begin
  5488. Result := false;
  5489. if MatchOpType(taicpu(p),top_ref) and
  5490. GetNextInstruction(p, hp1) and
  5491. (hp1.typ = ait_instruction) and
  5492. (((taicpu(hp1).opcode = A_FLD) and
  5493. (taicpu(p).opcode = A_FSTP)) or
  5494. ((taicpu(p).opcode = A_FISTP) and
  5495. (taicpu(hp1).opcode = A_FILD))) and
  5496. MatchOpType(taicpu(hp1),top_ref) and
  5497. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5498. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5499. begin
  5500. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5501. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5502. GetNextInstruction(hp1, hp2) and
  5503. (hp2.typ = ait_instruction) and
  5504. IsExitCode(hp2) and
  5505. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5506. not(assigned(current_procinfo.procdef.funcretsym) and
  5507. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5508. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5509. begin
  5510. RemoveInstruction(hp1);
  5511. RemoveCurrentP(p, hp2);
  5512. RemoveLastDeallocForFuncRes(p);
  5513. Result := true;
  5514. end
  5515. else
  5516. { we can do this only in fast math mode as fstp is rounding ...
  5517. ... still disabled as it breaks the compiler and/or rtl }
  5518. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5519. { ... or if another fstp equal to the first one follows }
  5520. (GetNextInstruction(hp1,hp2) and
  5521. (hp2.typ = ait_instruction) and
  5522. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5523. (taicpu(p).opsize=taicpu(hp2).opsize))
  5524. ) and
  5525. { fst can't store an extended/comp value }
  5526. (taicpu(p).opsize <> S_FX) and
  5527. (taicpu(p).opsize <> S_IQ) then
  5528. begin
  5529. if (taicpu(p).opcode = A_FSTP) then
  5530. taicpu(p).opcode := A_FST
  5531. else
  5532. taicpu(p).opcode := A_FIST;
  5533. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5534. RemoveInstruction(hp1);
  5535. end;
  5536. end;
  5537. end;
  5538. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5539. var
  5540. hp1, hp2: tai;
  5541. begin
  5542. result:=false;
  5543. if MatchOpType(taicpu(p),top_reg) and
  5544. GetNextInstruction(p, hp1) and
  5545. (hp1.typ = Ait_Instruction) and
  5546. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5547. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5548. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5549. { change to
  5550. fld reg fxxx reg,st
  5551. fxxxp st, st1 (hp1)
  5552. Remark: non commutative operations must be reversed!
  5553. }
  5554. begin
  5555. case taicpu(hp1).opcode Of
  5556. A_FMULP,A_FADDP,
  5557. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5558. begin
  5559. case taicpu(hp1).opcode Of
  5560. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5561. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5562. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5563. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5564. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5565. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5566. else
  5567. internalerror(2019050534);
  5568. end;
  5569. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5570. taicpu(hp1).oper[1]^.reg := NR_ST;
  5571. RemoveCurrentP(p, hp1);
  5572. Result:=true;
  5573. exit;
  5574. end;
  5575. else
  5576. ;
  5577. end;
  5578. end
  5579. else
  5580. if MatchOpType(taicpu(p),top_ref) and
  5581. GetNextInstruction(p, hp2) and
  5582. (hp2.typ = Ait_Instruction) and
  5583. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5584. (taicpu(p).opsize in [S_FS, S_FL]) and
  5585. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5586. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5587. if GetLastInstruction(p, hp1) and
  5588. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5589. MatchOpType(taicpu(hp1),top_ref) and
  5590. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5591. if ((taicpu(hp2).opcode = A_FMULP) or
  5592. (taicpu(hp2).opcode = A_FADDP)) then
  5593. { change to
  5594. fld/fst mem1 (hp1) fld/fst mem1
  5595. fld mem1 (p) fadd/
  5596. faddp/ fmul st, st
  5597. fmulp st, st1 (hp2) }
  5598. begin
  5599. RemoveCurrentP(p, hp1);
  5600. if (taicpu(hp2).opcode = A_FADDP) then
  5601. taicpu(hp2).opcode := A_FADD
  5602. else
  5603. taicpu(hp2).opcode := A_FMUL;
  5604. taicpu(hp2).oper[1]^.reg := NR_ST;
  5605. end
  5606. else
  5607. { change to
  5608. fld/fst mem1 (hp1) fld/fst mem1
  5609. fld mem1 (p) fld st}
  5610. begin
  5611. taicpu(p).changeopsize(S_FL);
  5612. taicpu(p).loadreg(0,NR_ST);
  5613. end
  5614. else
  5615. begin
  5616. case taicpu(hp2).opcode Of
  5617. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5618. { change to
  5619. fld/fst mem1 (hp1) fld/fst mem1
  5620. fld mem2 (p) fxxx mem2
  5621. fxxxp st, st1 (hp2) }
  5622. begin
  5623. case taicpu(hp2).opcode Of
  5624. A_FADDP: taicpu(p).opcode := A_FADD;
  5625. A_FMULP: taicpu(p).opcode := A_FMUL;
  5626. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5627. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5628. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5629. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5630. else
  5631. internalerror(2019050533);
  5632. end;
  5633. RemoveInstruction(hp2);
  5634. end
  5635. else
  5636. ;
  5637. end
  5638. end
  5639. end;
  5640. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5641. begin
  5642. Result := condition_in(cond1, cond2) or
  5643. { Not strictly subsets due to the actual flags checked, but because we're
  5644. comparing integers, E is a subset of AE and GE and their aliases }
  5645. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5646. end;
  5647. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5648. var
  5649. v: TCGInt;
  5650. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5651. FirstMatch: Boolean;
  5652. NewReg: TRegister;
  5653. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5654. begin
  5655. Result:=false;
  5656. { All these optimisations need a next instruction }
  5657. if not GetNextInstruction(p, hp1) then
  5658. Exit;
  5659. { Search for:
  5660. cmp ###,###
  5661. j(c1) @lbl1
  5662. ...
  5663. @lbl:
  5664. cmp ###.### (same comparison as above)
  5665. j(c2) @lbl2
  5666. If c1 is a subset of c2, change to:
  5667. cmp ###,###
  5668. j(c2) @lbl2
  5669. (@lbl1 may become a dead label as a result)
  5670. }
  5671. { Also handle cases where there are multiple jumps in a row }
  5672. p_jump := hp1;
  5673. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5674. begin
  5675. if IsJumpToLabel(taicpu(p_jump)) then
  5676. begin
  5677. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5678. p_label := nil;
  5679. if Assigned(JumpLabel) then
  5680. p_label := getlabelwithsym(JumpLabel);
  5681. if Assigned(p_label) and
  5682. GetNextInstruction(p_label, p_dist) and
  5683. MatchInstruction(p_dist, A_CMP, []) and
  5684. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5685. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5686. GetNextInstruction(p_dist, hp1_dist) and
  5687. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5688. begin
  5689. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5690. if JumpLabel = JumpLabel_dist then
  5691. { This is an infinite loop }
  5692. Exit;
  5693. { Best optimisation when the first condition is a subset (or equal) of the second }
  5694. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5695. begin
  5696. { Any registers used here will already be allocated }
  5697. if Assigned(JumpLabel_dist) then
  5698. JumpLabel_dist.IncRefs;
  5699. if Assigned(JumpLabel) then
  5700. JumpLabel.DecRefs;
  5701. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5702. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5703. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5704. Result := True;
  5705. { Don't exit yet. Since p and p_jump haven't actually been
  5706. removed, we can check for more on this iteration }
  5707. end
  5708. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5709. GetNextInstruction(hp1_dist, hp1_label) and
  5710. SkipAligns(hp1_label, hp1_label) and
  5711. (hp1_label.typ = ait_label) then
  5712. begin
  5713. JumpLabel_far := tai_label(hp1_label).labsym;
  5714. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5715. { This is an infinite loop }
  5716. Exit;
  5717. if Assigned(JumpLabel_far) then
  5718. begin
  5719. { In this situation, if the first jump branches, the second one will never,
  5720. branch so change the destination label to after the second jump }
  5721. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5722. if Assigned(JumpLabel) then
  5723. JumpLabel.DecRefs;
  5724. JumpLabel_far.IncRefs;
  5725. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5726. Result := True;
  5727. { Don't exit yet. Since p and p_jump haven't actually been
  5728. removed, we can check for more on this iteration }
  5729. Continue;
  5730. end;
  5731. end;
  5732. end;
  5733. end;
  5734. { Search for:
  5735. cmp ###,###
  5736. j(c1) @lbl1
  5737. cmp ###,### (same as first)
  5738. Remove second cmp
  5739. }
  5740. if GetNextInstruction(p_jump, hp2) and
  5741. (
  5742. (
  5743. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5744. (
  5745. (
  5746. MatchOpType(taicpu(p), top_const, top_reg) and
  5747. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5748. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5749. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5750. ) or (
  5751. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5752. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5753. )
  5754. )
  5755. ) or (
  5756. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5757. MatchOperand(taicpu(p).oper[0]^, 0) and
  5758. (taicpu(p).oper[1]^.typ = top_reg) and
  5759. MatchInstruction(hp2, A_TEST, []) and
  5760. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5761. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5762. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5763. )
  5764. ) then
  5765. begin
  5766. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5767. RemoveInstruction(hp2);
  5768. Result := True;
  5769. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5770. end;
  5771. GetNextInstruction(p_jump, p_jump);
  5772. end;
  5773. {
  5774. Try to optimise the following:
  5775. cmp $x,### ($x and $y can be registers or constants)
  5776. je @lbl1 (only reference)
  5777. cmp $y,### (### are identical)
  5778. @Lbl:
  5779. sete %reg1
  5780. Change to:
  5781. cmp $x,###
  5782. sete %reg2 (allocate new %reg2)
  5783. cmp $y,###
  5784. sete %reg1
  5785. orb %reg2,%reg1
  5786. (dealloc %reg2)
  5787. This adds an instruction (so don't perform under -Os), but it removes
  5788. a conditional branch.
  5789. }
  5790. if not (cs_opt_size in current_settings.optimizerswitches) and
  5791. (
  5792. (hp1 = p_jump) or
  5793. GetNextInstruction(p, hp1)
  5794. ) and
  5795. MatchInstruction(hp1, A_Jcc, []) and
  5796. IsJumpToLabel(taicpu(hp1)) and
  5797. (taicpu(hp1).condition in [C_E, C_Z]) and
  5798. GetNextInstruction(hp1, hp2) and
  5799. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  5800. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  5801. { The first operand of CMP instructions can only be a register or
  5802. immediate anyway, so no need to check }
  5803. GetNextInstruction(hp2, p_label) and
  5804. (p_label.typ = ait_label) and
  5805. (tai_label(p_label).labsym.getrefs = 1) and
  5806. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  5807. GetNextInstruction(p_label, p_dist) and
  5808. MatchInstruction(p_dist, A_SETcc, []) and
  5809. (taicpu(p_dist).condition in [C_E, C_Z]) and
  5810. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  5811. begin
  5812. TransferUsedRegs(TmpUsedRegs);
  5813. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5814. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5815. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  5816. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5817. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  5818. { Get the instruction after the SETcc instruction so we can
  5819. allocate a new register over the entire range }
  5820. GetNextInstruction(p_dist, hp1_dist) then
  5821. begin
  5822. { Register can appear in p if it's not used afterwards, so only
  5823. allocate between hp1 and hp1_dist }
  5824. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  5825. if NewReg <> NR_NO then
  5826. begin
  5827. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  5828. { Change the jump instruction into a SETcc instruction }
  5829. taicpu(hp1).opcode := A_SETcc;
  5830. taicpu(hp1).opsize := S_B;
  5831. taicpu(hp1).loadreg(0, NewReg);
  5832. { This is now a dead label }
  5833. tai_label(p_label).labsym.decrefs;
  5834. { Prefer adding before the next instruction so the FLAGS
  5835. register is deallicated first }
  5836. AsmL.InsertBefore(
  5837. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  5838. hp1_dist
  5839. );
  5840. Result := True;
  5841. { Don't exit yet, as p wasn't changed and hp1, while
  5842. modified, is still intact and might be optimised by the
  5843. SETcc optimisation below }
  5844. end;
  5845. end;
  5846. end;
  5847. if taicpu(p).oper[0]^.typ = top_const then
  5848. begin
  5849. if (taicpu(p).oper[0]^.val = 0) and
  5850. (taicpu(p).oper[1]^.typ = top_reg) and
  5851. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5852. begin
  5853. hp2 := p;
  5854. FirstMatch := True;
  5855. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5856. anything meaningful once it's converted to "test %reg,%reg";
  5857. additionally, some jumps will always (or never) branch, so
  5858. evaluate every jump immediately following the
  5859. comparison, optimising the conditions if possible.
  5860. Similarly with SETcc... those that are always set to 0 or 1
  5861. are changed to MOV instructions }
  5862. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5863. (
  5864. GetNextInstruction(hp2, hp1) and
  5865. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5866. ) do
  5867. begin
  5868. FirstMatch := False;
  5869. case taicpu(hp1).condition of
  5870. C_B, C_C, C_NAE, C_O:
  5871. { For B/NAE:
  5872. Will never branch since an unsigned integer can never be below zero
  5873. For C/O:
  5874. Result cannot overflow because 0 is being subtracted
  5875. }
  5876. begin
  5877. if taicpu(hp1).opcode = A_Jcc then
  5878. begin
  5879. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5880. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5881. RemoveInstruction(hp1);
  5882. { Since hp1 was deleted, hp2 must not be updated }
  5883. Continue;
  5884. end
  5885. else
  5886. begin
  5887. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5888. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5889. taicpu(hp1).opcode := A_MOV;
  5890. taicpu(hp1).ops := 2;
  5891. taicpu(hp1).condition := C_None;
  5892. taicpu(hp1).opsize := S_B;
  5893. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5894. taicpu(hp1).loadconst(0, 0);
  5895. end;
  5896. end;
  5897. C_BE, C_NA:
  5898. begin
  5899. { Will only branch if equal to zero }
  5900. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5901. taicpu(hp1).condition := C_E;
  5902. end;
  5903. C_A, C_NBE:
  5904. begin
  5905. { Will only branch if not equal to zero }
  5906. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5907. taicpu(hp1).condition := C_NE;
  5908. end;
  5909. C_AE, C_NB, C_NC, C_NO:
  5910. begin
  5911. { Will always branch }
  5912. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5913. if taicpu(hp1).opcode = A_Jcc then
  5914. begin
  5915. MakeUnconditional(taicpu(hp1));
  5916. { Any jumps/set that follow will now be dead code }
  5917. RemoveDeadCodeAfterJump(taicpu(hp1));
  5918. Break;
  5919. end
  5920. else
  5921. begin
  5922. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5923. taicpu(hp1).opcode := A_MOV;
  5924. taicpu(hp1).ops := 2;
  5925. taicpu(hp1).condition := C_None;
  5926. taicpu(hp1).opsize := S_B;
  5927. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5928. taicpu(hp1).loadconst(0, 1);
  5929. end;
  5930. end;
  5931. C_None:
  5932. InternalError(2020012201);
  5933. C_P, C_PE, C_NP, C_PO:
  5934. { We can't handle parity checks and they should never be generated
  5935. after a general-purpose CMP (it's used in some floating-point
  5936. comparisons that don't use CMP) }
  5937. InternalError(2020012202);
  5938. else
  5939. { Zero/Equality, Sign, their complements and all of the
  5940. signed comparisons do not need to be converted };
  5941. end;
  5942. hp2 := hp1;
  5943. end;
  5944. { Convert the instruction to a TEST }
  5945. taicpu(p).opcode := A_TEST;
  5946. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5947. Result := True;
  5948. Exit;
  5949. end
  5950. else if (taicpu(p).oper[0]^.val = 1) and
  5951. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5952. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5953. begin
  5954. { Convert; To:
  5955. cmp $1,r/m cmp $0,r/m
  5956. jl @lbl jle @lbl
  5957. }
  5958. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5959. taicpu(p).oper[0]^.val := 0;
  5960. taicpu(hp1).condition := C_LE;
  5961. { If the instruction is now "cmp $0,%reg", convert it to a
  5962. TEST (and effectively do the work of the "cmp $0,%reg" in
  5963. the block above)
  5964. If it's a reference, we can get away with not setting
  5965. Result to True because he haven't evaluated the jump
  5966. in this pass yet.
  5967. }
  5968. if (taicpu(p).oper[1]^.typ = top_reg) then
  5969. begin
  5970. taicpu(p).opcode := A_TEST;
  5971. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5972. Result := True;
  5973. end;
  5974. Exit;
  5975. end
  5976. else if (taicpu(p).oper[1]^.typ = top_reg)
  5977. {$ifdef x86_64}
  5978. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5979. {$endif x86_64}
  5980. then
  5981. begin
  5982. { cmp register,$8000 neg register
  5983. je target --> jo target
  5984. .... only if register is deallocated before jump.}
  5985. case Taicpu(p).opsize of
  5986. S_B: v:=$80;
  5987. S_W: v:=$8000;
  5988. S_L: v:=qword($80000000);
  5989. else
  5990. internalerror(2013112905);
  5991. end;
  5992. if (taicpu(p).oper[0]^.val=v) and
  5993. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5994. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5995. begin
  5996. TransferUsedRegs(TmpUsedRegs);
  5997. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5998. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5999. begin
  6000. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6001. Taicpu(p).opcode:=A_NEG;
  6002. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6003. Taicpu(p).clearop(1);
  6004. Taicpu(p).ops:=1;
  6005. if Taicpu(hp1).condition=C_E then
  6006. Taicpu(hp1).condition:=C_O
  6007. else
  6008. Taicpu(hp1).condition:=C_NO;
  6009. Result:=true;
  6010. exit;
  6011. end;
  6012. end;
  6013. end;
  6014. end;
  6015. if TrySwapMovCmp(p, hp1) then
  6016. begin
  6017. Result := True;
  6018. Exit;
  6019. end;
  6020. end;
  6021. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6022. var
  6023. hp1: tai;
  6024. begin
  6025. {
  6026. remove the second (v)pxor from
  6027. pxor reg,reg
  6028. ...
  6029. pxor reg,reg
  6030. }
  6031. Result:=false;
  6032. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6033. MatchOpType(taicpu(p),top_reg,top_reg) and
  6034. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6035. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6036. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6037. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6038. begin
  6039. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6040. RemoveInstruction(hp1);
  6041. Result:=true;
  6042. Exit;
  6043. end
  6044. {
  6045. replace
  6046. pxor reg1,reg1
  6047. movapd/s reg1,reg2
  6048. dealloc reg1
  6049. by
  6050. pxor reg2,reg2
  6051. }
  6052. else if GetNextInstruction(p,hp1) and
  6053. { we mix single and double opperations here because we assume that the compiler
  6054. generates vmovapd only after double operations and vmovaps only after single operations }
  6055. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6056. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6057. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6058. (taicpu(p).oper[0]^.typ=top_reg) then
  6059. begin
  6060. TransferUsedRegs(TmpUsedRegs);
  6061. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6062. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6063. begin
  6064. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6065. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6066. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6067. RemoveInstruction(hp1);
  6068. result:=true;
  6069. end;
  6070. end;
  6071. end;
  6072. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6073. var
  6074. hp1: tai;
  6075. begin
  6076. {
  6077. remove the second (v)pxor from
  6078. (v)pxor reg,reg
  6079. ...
  6080. (v)pxor reg,reg
  6081. }
  6082. Result:=false;
  6083. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6084. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6085. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6086. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6087. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6088. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6089. begin
  6090. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6091. RemoveInstruction(hp1);
  6092. Result:=true;
  6093. Exit;
  6094. end
  6095. else
  6096. Result:=OptPass1VOP(p);
  6097. end;
  6098. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6099. var
  6100. hp1 : tai;
  6101. begin
  6102. result:=false;
  6103. { replace
  6104. IMul const,%mreg1,%mreg2
  6105. Mov %reg2,%mreg3
  6106. dealloc %mreg3
  6107. by
  6108. Imul const,%mreg1,%mreg23
  6109. }
  6110. if (taicpu(p).ops=3) and
  6111. GetNextInstruction(p,hp1) and
  6112. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6113. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6114. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6115. begin
  6116. TransferUsedRegs(TmpUsedRegs);
  6117. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6118. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6119. begin
  6120. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6121. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6122. RemoveInstruction(hp1);
  6123. result:=true;
  6124. end;
  6125. end;
  6126. end;
  6127. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6128. var
  6129. hp1 : tai;
  6130. begin
  6131. result:=false;
  6132. { replace
  6133. IMul %reg0,%reg1,%reg2
  6134. Mov %reg2,%reg3
  6135. dealloc %reg2
  6136. by
  6137. Imul %reg0,%reg1,%reg3
  6138. }
  6139. if GetNextInstruction(p,hp1) and
  6140. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6141. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6142. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6143. begin
  6144. TransferUsedRegs(TmpUsedRegs);
  6145. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6146. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6147. begin
  6148. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6149. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6150. RemoveInstruction(hp1);
  6151. result:=true;
  6152. end;
  6153. end;
  6154. end;
  6155. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6156. var
  6157. hp1: tai;
  6158. begin
  6159. Result:=false;
  6160. { get rid of
  6161. (v)cvtss2sd reg0,<reg1,>reg2
  6162. (v)cvtss2sd reg2,<reg2,>reg0
  6163. }
  6164. if GetNextInstruction(p,hp1) and
  6165. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6166. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6167. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6168. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6169. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6170. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6171. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6172. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6173. )
  6174. ) then
  6175. begin
  6176. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6177. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6178. begin
  6179. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6180. RemoveCurrentP(p);
  6181. RemoveInstruction(hp1);
  6182. end
  6183. else
  6184. begin
  6185. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6186. if taicpu(hp1).opcode=A_CVTSD2SS then
  6187. begin
  6188. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6189. taicpu(p).opcode:=A_MOVAPS;
  6190. end
  6191. else
  6192. begin
  6193. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6194. taicpu(p).opcode:=A_VMOVAPS;
  6195. end;
  6196. taicpu(p).ops:=2;
  6197. RemoveInstruction(hp1);
  6198. end;
  6199. Result:=true;
  6200. Exit;
  6201. end;
  6202. end;
  6203. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6204. var
  6205. hp1, hp2, hp3, hp4, hp5: tai;
  6206. ThisReg: TRegister;
  6207. begin
  6208. Result := False;
  6209. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  6210. Exit;
  6211. {
  6212. convert
  6213. j<c> .L1
  6214. mov 1,reg
  6215. jmp .L2
  6216. .L1
  6217. mov 0,reg
  6218. .L2
  6219. into
  6220. mov 0,reg
  6221. set<not(c)> reg
  6222. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6223. would destroy the flag contents
  6224. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6225. executed at the same time as a previous comparison.
  6226. set<not(c)> reg
  6227. movzx reg, reg
  6228. }
  6229. if MatchInstruction(hp1,A_MOV,[]) and
  6230. (taicpu(hp1).oper[0]^.typ = top_const) and
  6231. (
  6232. (
  6233. (taicpu(hp1).oper[1]^.typ = top_reg)
  6234. {$ifdef i386}
  6235. { Under i386, ESI, EDI, EBP and ESP
  6236. don't have an 8-bit representation }
  6237. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6238. {$endif i386}
  6239. ) or (
  6240. {$ifdef i386}
  6241. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6242. {$endif i386}
  6243. (taicpu(hp1).opsize = S_B)
  6244. )
  6245. ) and
  6246. GetNextInstruction(hp1,hp2) and
  6247. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6248. GetNextInstruction(hp2,hp3) and
  6249. SkipAligns(hp3, hp3) and
  6250. (hp3.typ=ait_label) and
  6251. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6252. GetNextInstruction(hp3,hp4) and
  6253. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6254. (taicpu(hp4).oper[0]^.typ = top_const) and
  6255. (
  6256. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6257. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6258. ) and
  6259. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6260. GetNextInstruction(hp4,hp5) and
  6261. SkipAligns(hp5, hp5) and
  6262. (hp5.typ=ait_label) and
  6263. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6264. begin
  6265. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6266. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6267. tai_label(hp3).labsym.DecRefs;
  6268. { If this isn't the only reference to the middle label, we can
  6269. still make a saving - only that the first jump and everything
  6270. that follows will remain. }
  6271. if (tai_label(hp3).labsym.getrefs = 0) then
  6272. begin
  6273. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6274. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6275. else
  6276. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6277. { remove jump, first label and second MOV (also catching any aligns) }
  6278. repeat
  6279. if not GetNextInstruction(hp2, hp3) then
  6280. InternalError(2021040810);
  6281. RemoveInstruction(hp2);
  6282. hp2 := hp3;
  6283. until hp2 = hp5;
  6284. { Don't decrement reference count before the removal loop
  6285. above, otherwise GetNextInstruction won't stop on the
  6286. the label }
  6287. tai_label(hp5).labsym.DecRefs;
  6288. end
  6289. else
  6290. begin
  6291. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6292. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6293. else
  6294. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6295. end;
  6296. taicpu(p).opcode:=A_SETcc;
  6297. taicpu(p).opsize:=S_B;
  6298. taicpu(p).is_jmp:=False;
  6299. if taicpu(hp1).opsize=S_B then
  6300. begin
  6301. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6302. if taicpu(hp1).oper[1]^.typ = top_reg then
  6303. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6304. RemoveInstruction(hp1);
  6305. end
  6306. else
  6307. begin
  6308. { Will be a register because the size can't be S_B otherwise }
  6309. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6310. taicpu(p).loadreg(0, ThisReg);
  6311. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6312. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6313. begin
  6314. case taicpu(hp1).opsize of
  6315. S_W:
  6316. taicpu(hp1).opsize := S_BW;
  6317. S_L:
  6318. taicpu(hp1).opsize := S_BL;
  6319. {$ifdef x86_64}
  6320. S_Q:
  6321. begin
  6322. taicpu(hp1).opsize := S_BL;
  6323. { Change the destination register to 32-bit }
  6324. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6325. end;
  6326. {$endif x86_64}
  6327. else
  6328. InternalError(2021040820);
  6329. end;
  6330. taicpu(hp1).opcode := A_MOVZX;
  6331. taicpu(hp1).loadreg(0, ThisReg);
  6332. end
  6333. else
  6334. begin
  6335. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6336. { hp1 is already a MOV instruction with the correct register }
  6337. taicpu(hp1).loadconst(0, 0);
  6338. { Inserting it right before p will guarantee that the flags are also tracked }
  6339. asml.Remove(hp1);
  6340. asml.InsertBefore(hp1, p);
  6341. end;
  6342. end;
  6343. Result:=true;
  6344. exit;
  6345. end
  6346. end;
  6347. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6348. var
  6349. hp1, hp2, hp3: tai;
  6350. SourceRef, TargetRef: TReference;
  6351. CurrentReg: TRegister;
  6352. begin
  6353. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6354. if not UseAVX then
  6355. InternalError(2021100501);
  6356. Result := False;
  6357. { Look for the following to simplify:
  6358. vmovdqa/u x(mem1), %xmmreg
  6359. vmovdqa/u %xmmreg, y(mem2)
  6360. vmovdqa/u x+16(mem1), %xmmreg
  6361. vmovdqa/u %xmmreg, y+16(mem2)
  6362. Change to:
  6363. vmovdqa/u x(mem1), %ymmreg
  6364. vmovdqa/u %ymmreg, y(mem2)
  6365. vpxor %ymmreg, %ymmreg, %ymmreg
  6366. ( The VPXOR instruction is to zero the upper half, thus removing the
  6367. need to call the potentially expensive VZEROUPPER instruction. Other
  6368. peephole optimisations can remove VPXOR if it's unnecessary )
  6369. }
  6370. TransferUsedRegs(TmpUsedRegs);
  6371. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6372. { NOTE: In the optimisations below, if the references dictate that an
  6373. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6374. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6375. if (taicpu(p).opsize = S_XMM) and
  6376. MatchOpType(taicpu(p), top_ref, top_reg) and
  6377. GetNextInstruction(p, hp1) and
  6378. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6379. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6380. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6381. begin
  6382. SourceRef := taicpu(p).oper[0]^.ref^;
  6383. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6384. if GetNextInstruction(hp1, hp2) and
  6385. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6386. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6387. begin
  6388. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6389. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6390. Inc(SourceRef.offset, 16);
  6391. { Reuse the register in the first block move }
  6392. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6393. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6394. begin
  6395. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6396. Inc(TargetRef.offset, 16);
  6397. if GetNextInstruction(hp2, hp3) and
  6398. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6399. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6400. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6401. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6402. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6403. begin
  6404. { Update the register tracking to the new size }
  6405. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6406. { Remember that the offsets are 16 ahead }
  6407. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6408. if not (
  6409. ((SourceRef.offset mod 32) = 16) and
  6410. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6411. ) then
  6412. taicpu(p).opcode := A_VMOVDQU;
  6413. taicpu(p).opsize := S_YMM;
  6414. taicpu(p).oper[1]^.reg := CurrentReg;
  6415. if not (
  6416. ((TargetRef.offset mod 32) = 16) and
  6417. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6418. ) then
  6419. taicpu(hp1).opcode := A_VMOVDQU;
  6420. taicpu(hp1).opsize := S_YMM;
  6421. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6422. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6423. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6424. if (pi_uses_ymm in current_procinfo.flags) then
  6425. RemoveInstruction(hp2)
  6426. else
  6427. begin
  6428. taicpu(hp2).opcode := A_VPXOR;
  6429. taicpu(hp2).opsize := S_YMM;
  6430. taicpu(hp2).loadreg(0, CurrentReg);
  6431. taicpu(hp2).loadreg(1, CurrentReg);
  6432. taicpu(hp2).loadreg(2, CurrentReg);
  6433. taicpu(hp2).ops := 3;
  6434. end;
  6435. RemoveInstruction(hp3);
  6436. Result := True;
  6437. Exit;
  6438. end;
  6439. end
  6440. else
  6441. begin
  6442. { See if the next references are 16 less rather than 16 greater }
  6443. Dec(SourceRef.offset, 32); { -16 the other way }
  6444. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6445. begin
  6446. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6447. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6448. if GetNextInstruction(hp2, hp3) and
  6449. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6450. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6451. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6452. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6453. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6454. begin
  6455. { Update the register tracking to the new size }
  6456. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6457. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6458. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6459. if not(
  6460. ((SourceRef.offset mod 32) = 0) and
  6461. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6462. ) then
  6463. taicpu(hp2).opcode := A_VMOVDQU;
  6464. taicpu(hp2).opsize := S_YMM;
  6465. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6466. if not (
  6467. ((TargetRef.offset mod 32) = 0) and
  6468. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6469. ) then
  6470. taicpu(hp3).opcode := A_VMOVDQU;
  6471. taicpu(hp3).opsize := S_YMM;
  6472. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6473. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6474. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6475. if (pi_uses_ymm in current_procinfo.flags) then
  6476. RemoveInstruction(hp1)
  6477. else
  6478. begin
  6479. taicpu(hp1).opcode := A_VPXOR;
  6480. taicpu(hp1).opsize := S_YMM;
  6481. taicpu(hp1).loadreg(0, CurrentReg);
  6482. taicpu(hp1).loadreg(1, CurrentReg);
  6483. taicpu(hp1).loadreg(2, CurrentReg);
  6484. taicpu(hp1).ops := 3;
  6485. Asml.Remove(hp1);
  6486. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6487. end;
  6488. RemoveCurrentP(p, hp2);
  6489. Result := True;
  6490. Exit;
  6491. end;
  6492. end;
  6493. end;
  6494. end;
  6495. end;
  6496. end;
  6497. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6498. var
  6499. hp2, hp3, first_assignment: tai;
  6500. IncCount, OperIdx: Integer;
  6501. OrigLabel: TAsmLabel;
  6502. begin
  6503. Count := 0;
  6504. Result := False;
  6505. first_assignment := nil;
  6506. if (LoopCount >= 20) then
  6507. begin
  6508. { Guard against infinite loops }
  6509. Exit;
  6510. end;
  6511. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6512. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6513. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6514. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6515. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6516. Exit;
  6517. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6518. {
  6519. change
  6520. jmp .L1
  6521. ...
  6522. .L1:
  6523. mov ##, ## ( multiple movs possible )
  6524. jmp/ret
  6525. into
  6526. mov ##, ##
  6527. jmp/ret
  6528. }
  6529. if not Assigned(hp1) then
  6530. begin
  6531. hp1 := GetLabelWithSym(OrigLabel);
  6532. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6533. Exit;
  6534. end;
  6535. hp2 := hp1;
  6536. while Assigned(hp2) do
  6537. begin
  6538. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6539. SkipLabels(hp2,hp2);
  6540. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6541. Break;
  6542. case taicpu(hp2).opcode of
  6543. A_MOVSS:
  6544. begin
  6545. if taicpu(hp2).ops = 0 then
  6546. { Wrong MOVSS }
  6547. Break;
  6548. Inc(Count);
  6549. if Count >= 5 then
  6550. { Too many to be worthwhile }
  6551. Break;
  6552. GetNextInstruction(hp2, hp2);
  6553. Continue;
  6554. end;
  6555. A_MOV,
  6556. A_MOVD,
  6557. A_MOVQ,
  6558. A_MOVSX,
  6559. {$ifdef x86_64}
  6560. A_MOVSXD,
  6561. {$endif x86_64}
  6562. A_MOVZX,
  6563. A_MOVAPS,
  6564. A_MOVUPS,
  6565. A_MOVSD,
  6566. A_MOVAPD,
  6567. A_MOVUPD,
  6568. A_MOVDQA,
  6569. A_MOVDQU,
  6570. A_VMOVSS,
  6571. A_VMOVAPS,
  6572. A_VMOVUPS,
  6573. A_VMOVSD,
  6574. A_VMOVAPD,
  6575. A_VMOVUPD,
  6576. A_VMOVDQA,
  6577. A_VMOVDQU:
  6578. begin
  6579. Inc(Count);
  6580. if Count >= 5 then
  6581. { Too many to be worthwhile }
  6582. Break;
  6583. GetNextInstruction(hp2, hp2);
  6584. Continue;
  6585. end;
  6586. A_JMP:
  6587. begin
  6588. { Guard against infinite loops }
  6589. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6590. Exit;
  6591. { Analyse this jump first in case it also duplicates assignments }
  6592. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6593. begin
  6594. { Something did change! }
  6595. Result := True;
  6596. Inc(Count, IncCount);
  6597. if Count >= 5 then
  6598. begin
  6599. { Too many to be worthwhile }
  6600. Exit;
  6601. end;
  6602. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6603. Break;
  6604. end;
  6605. Result := True;
  6606. Break;
  6607. end;
  6608. A_RET:
  6609. begin
  6610. Result := True;
  6611. Break;
  6612. end;
  6613. else
  6614. Break;
  6615. end;
  6616. end;
  6617. if Result then
  6618. begin
  6619. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6620. if Count = 0 then
  6621. begin
  6622. Result := False;
  6623. Exit;
  6624. end;
  6625. hp3 := p;
  6626. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6627. while True do
  6628. begin
  6629. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6630. SkipLabels(hp1,hp1);
  6631. if (hp1.typ <> ait_instruction) then
  6632. InternalError(2021040720);
  6633. case taicpu(hp1).opcode of
  6634. A_JMP:
  6635. begin
  6636. { Change the original jump to the new destination }
  6637. OrigLabel.decrefs;
  6638. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6639. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6640. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6641. if not Assigned(first_assignment) then
  6642. InternalError(2021040810)
  6643. else
  6644. p := first_assignment;
  6645. Exit;
  6646. end;
  6647. A_RET:
  6648. begin
  6649. { Now change the jump into a RET instruction }
  6650. ConvertJumpToRET(p, hp1);
  6651. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6652. if not Assigned(first_assignment) then
  6653. InternalError(2021040811)
  6654. else
  6655. p := first_assignment;
  6656. Exit;
  6657. end;
  6658. else
  6659. begin
  6660. { Duplicate the MOV instruction }
  6661. hp3:=tai(hp1.getcopy);
  6662. if first_assignment = nil then
  6663. first_assignment := hp3;
  6664. asml.InsertBefore(hp3, p);
  6665. { Make sure the compiler knows about any final registers written here }
  6666. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6667. with taicpu(hp3).oper[OperIdx]^ do
  6668. begin
  6669. case typ of
  6670. top_ref:
  6671. begin
  6672. if (ref^.base <> NR_NO) and
  6673. (getsupreg(ref^.base) <> RS_ESP) and
  6674. (getsupreg(ref^.base) <> RS_EBP)
  6675. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6676. then
  6677. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6678. if (ref^.index <> NR_NO) and
  6679. (getsupreg(ref^.index) <> RS_ESP) and
  6680. (getsupreg(ref^.index) <> RS_EBP)
  6681. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6682. (ref^.index <> ref^.base) then
  6683. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6684. end;
  6685. top_reg:
  6686. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6687. else
  6688. ;
  6689. end;
  6690. end;
  6691. end;
  6692. end;
  6693. if not GetNextInstruction(hp1, hp1) then
  6694. { Should have dropped out earlier }
  6695. InternalError(2021040710);
  6696. end;
  6697. end;
  6698. end;
  6699. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6700. var
  6701. hp2: tai;
  6702. X: Integer;
  6703. const
  6704. WriteOp: array[0..3] of set of TInsChange = (
  6705. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6706. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6707. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6708. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6709. RegWriteFlags: array[0..7] of set of TInsChange = (
  6710. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6711. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6712. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6713. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6714. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6715. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6716. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6717. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6718. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6719. begin
  6720. { If we have something like:
  6721. cmp ###,%reg1
  6722. mov 0,%reg2
  6723. And no modified registers are shared, move the instruction to before
  6724. the comparison as this means it can be optimised without worrying
  6725. about the FLAGS register. (CMP/MOV is generated by
  6726. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6727. As long as the second instruction doesn't use the flags or one of the
  6728. registers used by CMP or TEST (also check any references that use the
  6729. registers), then it can be moved prior to the comparison.
  6730. }
  6731. Result := False;
  6732. if (hp1.typ <> ait_instruction) or
  6733. taicpu(hp1).is_jmp or
  6734. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6735. Exit;
  6736. { NOP is a pipeline fence, likely marking the beginning of the function
  6737. epilogue, so drop out. Similarly, drop out if POP or RET are
  6738. encountered }
  6739. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6740. Exit;
  6741. if (taicpu(hp1).opcode = A_MOVSS) and
  6742. (taicpu(hp1).ops = 0) then
  6743. { Wrong MOVSS }
  6744. Exit;
  6745. { Check for writes to specific registers first }
  6746. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6747. for X := 0 to 7 do
  6748. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6749. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6750. Exit;
  6751. for X := 0 to taicpu(hp1).ops - 1 do
  6752. begin
  6753. { Check to see if this operand writes to something }
  6754. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6755. { And matches something in the CMP/TEST instruction }
  6756. (
  6757. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6758. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6759. (
  6760. { If it's a register, make sure the register written to doesn't
  6761. appear in the cmp instruction as part of a reference }
  6762. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6763. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6764. )
  6765. ) then
  6766. Exit;
  6767. end;
  6768. { The instruction can be safely moved }
  6769. asml.Remove(hp1);
  6770. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6771. if not GetLastInstruction(p, hp2) then
  6772. asml.InsertBefore(hp1, p)
  6773. else
  6774. asml.InsertAfter(hp1, hp2);
  6775. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6776. for X := 0 to taicpu(hp1).ops - 1 do
  6777. case taicpu(hp1).oper[X]^.typ of
  6778. top_reg:
  6779. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6780. top_ref:
  6781. begin
  6782. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6783. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6784. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6785. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6786. end;
  6787. else
  6788. ;
  6789. end;
  6790. if taicpu(hp1).opcode = A_LEA then
  6791. { The flags will be overwritten by the CMP/TEST instruction }
  6792. ConvertLEA(taicpu(hp1));
  6793. Result := True;
  6794. end;
  6795. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6796. function IsXCHGAcceptable: Boolean; inline;
  6797. begin
  6798. { Always accept if optimising for size }
  6799. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6800. (
  6801. {$ifdef x86_64}
  6802. { XCHG takes 3 cycles on AMD Athlon64 }
  6803. (current_settings.optimizecputype >= cpu_core_i)
  6804. {$else x86_64}
  6805. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6806. than 3, so it becomes a saving compared to three MOVs with two of
  6807. them able to execute simultaneously. [Kit] }
  6808. (current_settings.optimizecputype >= cpu_PentiumM)
  6809. {$endif x86_64}
  6810. );
  6811. end;
  6812. var
  6813. NewRef: TReference;
  6814. hp1, hp2, hp3, hp4: Tai;
  6815. {$ifndef x86_64}
  6816. OperIdx: Integer;
  6817. {$endif x86_64}
  6818. NewInstr : Taicpu;
  6819. NewAligh : Tai_align;
  6820. DestLabel: TAsmLabel;
  6821. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6822. var
  6823. NextInstr: tai;
  6824. begin
  6825. Result := False;
  6826. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6827. if not GetNextInstruction(InputInstr, NextInstr) or
  6828. (
  6829. { The FLAGS register isn't always tracked properly, so do not
  6830. perform this optimisation if a conditional statement follows }
  6831. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6832. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6833. ) then
  6834. begin
  6835. reference_reset(NewRef, 1, []);
  6836. NewRef.base := taicpu(p).oper[0]^.reg;
  6837. NewRef.scalefactor := 1;
  6838. if taicpu(InputInstr).opcode = A_ADD then
  6839. begin
  6840. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6841. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6842. end
  6843. else
  6844. begin
  6845. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6846. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6847. end;
  6848. taicpu(p).opcode := A_LEA;
  6849. taicpu(p).loadref(0, NewRef);
  6850. RemoveInstruction(InputInstr);
  6851. Result := True;
  6852. end;
  6853. end;
  6854. begin
  6855. Result:=false;
  6856. { This optimisation adds an instruction, so only do it for speed }
  6857. if not (cs_opt_size in current_settings.optimizerswitches) and
  6858. MatchOpType(taicpu(p), top_const, top_reg) and
  6859. (taicpu(p).oper[0]^.val = 0) then
  6860. begin
  6861. { To avoid compiler warning }
  6862. DestLabel := nil;
  6863. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6864. InternalError(2021040750);
  6865. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6866. Exit;
  6867. case hp1.typ of
  6868. ait_label:
  6869. begin
  6870. { Change:
  6871. mov $0,%reg mov $0,%reg
  6872. @Lbl1: @Lbl1:
  6873. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6874. je @Lbl2 jne @Lbl2
  6875. To: To:
  6876. mov $0,%reg mov $0,%reg
  6877. jmp @Lbl2 jmp @Lbl3
  6878. (align) (align)
  6879. @Lbl1: @Lbl1:
  6880. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6881. je @Lbl2 je @Lbl2
  6882. @Lbl3: <-- Only if label exists
  6883. (Not if it's optimised for size)
  6884. }
  6885. if not GetNextInstruction(hp1, hp2) then
  6886. Exit;
  6887. if not (cs_opt_size in current_settings.optimizerswitches) and
  6888. (hp2.typ = ait_instruction) and
  6889. (
  6890. { Register sizes must exactly match }
  6891. (
  6892. (taicpu(hp2).opcode = A_CMP) and
  6893. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6894. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6895. ) or (
  6896. (taicpu(hp2).opcode = A_TEST) and
  6897. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6898. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6899. )
  6900. ) and GetNextInstruction(hp2, hp3) and
  6901. (hp3.typ = ait_instruction) and
  6902. (taicpu(hp3).opcode = A_JCC) and
  6903. (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
  6904. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6905. begin
  6906. { Check condition of jump }
  6907. { Always true? }
  6908. if condition_in(C_E, taicpu(hp3).condition) then
  6909. begin
  6910. { Copy label symbol and obtain matching label entry for the
  6911. conditional jump, as this will be our destination}
  6912. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6913. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6914. Result := True;
  6915. end
  6916. { Always false? }
  6917. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6918. begin
  6919. { This is only worth it if there's a jump to take }
  6920. case hp2.typ of
  6921. ait_instruction:
  6922. begin
  6923. if taicpu(hp2).opcode = A_JMP then
  6924. begin
  6925. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6926. { An unconditional jump follows the conditional jump which will always be false,
  6927. so use this jump's destination for the new jump }
  6928. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6929. Result := True;
  6930. end
  6931. else if taicpu(hp2).opcode = A_JCC then
  6932. begin
  6933. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6934. if condition_in(C_E, taicpu(hp2).condition) then
  6935. begin
  6936. { A second conditional jump follows the conditional jump which will always be false,
  6937. while the second jump is always True, so use this jump's destination for the new jump }
  6938. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6939. Result := True;
  6940. end;
  6941. { Don't risk it if the jump isn't always true (Result remains False) }
  6942. end;
  6943. end;
  6944. else
  6945. { If anything else don't optimise };
  6946. end;
  6947. end;
  6948. if Result then
  6949. begin
  6950. { Just so we have something to insert as a paremeter}
  6951. reference_reset(NewRef, 1, []);
  6952. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6953. { Now actually load the correct parameter }
  6954. NewInstr.loadsymbol(0, DestLabel, 0);
  6955. { Get instruction before original label (may not be p under -O3) }
  6956. if not GetLastInstruction(hp1, hp2) then
  6957. { Shouldn't fail here }
  6958. InternalError(2021040701);
  6959. DestLabel.increfs;
  6960. AsmL.InsertAfter(NewInstr, hp2);
  6961. { Add new alignment field }
  6962. (* AsmL.InsertAfter(
  6963. cai_align.create_max(
  6964. current_settings.alignment.jumpalign,
  6965. current_settings.alignment.jumpalignskipmax
  6966. ),
  6967. NewInstr
  6968. ); *)
  6969. end;
  6970. Exit;
  6971. end;
  6972. end;
  6973. else
  6974. ;
  6975. end;
  6976. end;
  6977. if not GetNextInstruction(p, hp1) then
  6978. Exit;
  6979. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  6980. and DoMovCmpMemOpt(p, hp1, True) then
  6981. begin
  6982. Result := True;
  6983. Exit;
  6984. end
  6985. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6986. begin
  6987. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6988. further, but we can't just put this jump optimisation in pass 1
  6989. because it tends to perform worse when conditional jumps are
  6990. nearby (e.g. when converting CMOV instructions). [Kit] }
  6991. if OptPass2JMP(hp1) then
  6992. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6993. Result := OptPass1MOV(p)
  6994. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6995. returned True and the instruction is still a MOV, thus checking
  6996. the optimisations below }
  6997. { If OptPass2JMP returned False, no optimisations were done to
  6998. the jump and there are no further optimisations that can be done
  6999. to the MOV instruction on this pass }
  7000. end
  7001. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7002. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7003. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7004. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7005. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7006. begin
  7007. { Change:
  7008. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7009. addl/q $x,%reg2 subl/q $x,%reg2
  7010. To:
  7011. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7012. }
  7013. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7014. { be lazy, checking separately for sub would be slightly better }
  7015. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7016. begin
  7017. TransferUsedRegs(TmpUsedRegs);
  7018. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7019. if TryMovArith2Lea(hp1) then
  7020. begin
  7021. Result := True;
  7022. Exit;
  7023. end
  7024. end
  7025. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7026. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7027. { Same as above, but also adds or subtracts to %reg2 in between.
  7028. It's still valid as long as the flags aren't in use }
  7029. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7030. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7031. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7032. { be lazy, checking separately for sub would be slightly better }
  7033. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7034. begin
  7035. TransferUsedRegs(TmpUsedRegs);
  7036. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7037. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7038. if TryMovArith2Lea(hp2) then
  7039. begin
  7040. Result := True;
  7041. Exit;
  7042. end;
  7043. end;
  7044. end
  7045. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7046. {$ifdef x86_64}
  7047. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7048. {$else x86_64}
  7049. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7050. {$endif x86_64}
  7051. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7052. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7053. { mov reg1, reg2 mov reg1, reg2
  7054. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7055. begin
  7056. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7057. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7058. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7059. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7060. TransferUsedRegs(TmpUsedRegs);
  7061. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7062. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7063. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7064. then
  7065. begin
  7066. RemoveCurrentP(p, hp1);
  7067. Result:=true;
  7068. end;
  7069. exit;
  7070. end
  7071. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7072. IsXCHGAcceptable and
  7073. { XCHG doesn't support 8-byte registers }
  7074. (taicpu(p).opsize <> S_B) and
  7075. MatchInstruction(hp1, A_MOV, []) and
  7076. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7077. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7078. GetNextInstruction(hp1, hp2) and
  7079. MatchInstruction(hp2, A_MOV, []) and
  7080. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7081. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7082. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7083. begin
  7084. { mov %reg1,%reg2
  7085. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7086. mov %reg2,%reg3
  7087. (%reg2 not used afterwards)
  7088. Note that xchg takes 3 cycles to execute, and generally mov's take
  7089. only one cycle apiece, but the first two mov's can be executed in
  7090. parallel, only taking 2 cycles overall. Older processors should
  7091. therefore only optimise for size. [Kit]
  7092. }
  7093. TransferUsedRegs(TmpUsedRegs);
  7094. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7096. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7097. begin
  7098. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7099. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7100. taicpu(hp1).opcode := A_XCHG;
  7101. RemoveCurrentP(p, hp1);
  7102. RemoveInstruction(hp2);
  7103. Result := True;
  7104. Exit;
  7105. end;
  7106. end
  7107. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7108. MatchInstruction(hp1, A_SAR, []) then
  7109. begin
  7110. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7111. begin
  7112. { the use of %edx also covers the opsize being S_L }
  7113. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7114. begin
  7115. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7116. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7117. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7118. begin
  7119. { Change:
  7120. movl %eax,%edx
  7121. sarl $31,%edx
  7122. To:
  7123. cltd
  7124. }
  7125. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7126. RemoveInstruction(hp1);
  7127. taicpu(p).opcode := A_CDQ;
  7128. taicpu(p).opsize := S_NO;
  7129. taicpu(p).clearop(1);
  7130. taicpu(p).clearop(0);
  7131. taicpu(p).ops:=0;
  7132. Result := True;
  7133. end
  7134. else if (cs_opt_size in current_settings.optimizerswitches) and
  7135. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7136. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7137. begin
  7138. { Change:
  7139. movl %edx,%eax
  7140. sarl $31,%edx
  7141. To:
  7142. movl %edx,%eax
  7143. cltd
  7144. Note that this creates a dependency between the two instructions,
  7145. so only perform if optimising for size.
  7146. }
  7147. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7148. taicpu(hp1).opcode := A_CDQ;
  7149. taicpu(hp1).opsize := S_NO;
  7150. taicpu(hp1).clearop(1);
  7151. taicpu(hp1).clearop(0);
  7152. taicpu(hp1).ops:=0;
  7153. end;
  7154. {$ifndef x86_64}
  7155. end
  7156. { Don't bother if CMOV is supported, because a more optimal
  7157. sequence would have been generated for the Abs() intrinsic }
  7158. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7159. { the use of %eax also covers the opsize being S_L }
  7160. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7161. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7162. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7163. GetNextInstruction(hp1, hp2) and
  7164. MatchInstruction(hp2, A_XOR, [S_L]) and
  7165. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7166. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7167. GetNextInstruction(hp2, hp3) and
  7168. MatchInstruction(hp3, A_SUB, [S_L]) and
  7169. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7170. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7171. begin
  7172. { Change:
  7173. movl %eax,%edx
  7174. sarl $31,%eax
  7175. xorl %eax,%edx
  7176. subl %eax,%edx
  7177. (Instruction that uses %edx)
  7178. (%eax deallocated)
  7179. (%edx deallocated)
  7180. To:
  7181. cltd
  7182. xorl %edx,%eax <-- Note the registers have swapped
  7183. subl %edx,%eax
  7184. (Instruction that uses %eax) <-- %eax rather than %edx
  7185. }
  7186. TransferUsedRegs(TmpUsedRegs);
  7187. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7188. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7189. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7190. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7191. begin
  7192. if GetNextInstruction(hp3, hp4) and
  7193. not RegModifiedByInstruction(NR_EDX, hp4) and
  7194. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7195. begin
  7196. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7197. taicpu(p).opcode := A_CDQ;
  7198. taicpu(p).clearop(1);
  7199. taicpu(p).clearop(0);
  7200. taicpu(p).ops:=0;
  7201. RemoveInstruction(hp1);
  7202. taicpu(hp2).loadreg(0, NR_EDX);
  7203. taicpu(hp2).loadreg(1, NR_EAX);
  7204. taicpu(hp3).loadreg(0, NR_EDX);
  7205. taicpu(hp3).loadreg(1, NR_EAX);
  7206. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7207. { Convert references in the following instruction (hp4) from %edx to %eax }
  7208. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7209. with taicpu(hp4).oper[OperIdx]^ do
  7210. case typ of
  7211. top_reg:
  7212. if getsupreg(reg) = RS_EDX then
  7213. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7214. top_ref:
  7215. begin
  7216. if getsupreg(reg) = RS_EDX then
  7217. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7218. if getsupreg(reg) = RS_EDX then
  7219. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7220. end;
  7221. else
  7222. ;
  7223. end;
  7224. end;
  7225. end;
  7226. {$else x86_64}
  7227. end;
  7228. end
  7229. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7230. { the use of %rdx also covers the opsize being S_Q }
  7231. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7232. begin
  7233. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7234. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7235. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7236. begin
  7237. { Change:
  7238. movq %rax,%rdx
  7239. sarq $63,%rdx
  7240. To:
  7241. cqto
  7242. }
  7243. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7244. RemoveInstruction(hp1);
  7245. taicpu(p).opcode := A_CQO;
  7246. taicpu(p).opsize := S_NO;
  7247. taicpu(p).clearop(1);
  7248. taicpu(p).clearop(0);
  7249. taicpu(p).ops:=0;
  7250. Result := True;
  7251. end
  7252. else if (cs_opt_size in current_settings.optimizerswitches) and
  7253. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7254. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7255. begin
  7256. { Change:
  7257. movq %rdx,%rax
  7258. sarq $63,%rdx
  7259. To:
  7260. movq %rdx,%rax
  7261. cqto
  7262. Note that this creates a dependency between the two instructions,
  7263. so only perform if optimising for size.
  7264. }
  7265. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7266. taicpu(hp1).opcode := A_CQO;
  7267. taicpu(hp1).opsize := S_NO;
  7268. taicpu(hp1).clearop(1);
  7269. taicpu(hp1).clearop(0);
  7270. taicpu(hp1).ops:=0;
  7271. {$endif x86_64}
  7272. end;
  7273. end;
  7274. end
  7275. else if MatchInstruction(hp1, A_MOV, []) and
  7276. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7277. { Though "GetNextInstruction" could be factored out, along with
  7278. the instructions that depend on hp2, it is an expensive call that
  7279. should be delayed for as long as possible, hence we do cheaper
  7280. checks first that are likely to be False. [Kit] }
  7281. begin
  7282. if (
  7283. (
  7284. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7285. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7286. (
  7287. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7288. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7289. )
  7290. ) or
  7291. (
  7292. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7293. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7294. (
  7295. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7296. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7297. )
  7298. )
  7299. ) and
  7300. GetNextInstruction(hp1, hp2) and
  7301. MatchInstruction(hp2, A_SAR, []) and
  7302. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7303. begin
  7304. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7305. begin
  7306. { Change:
  7307. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7308. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7309. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7310. To:
  7311. movl r/m,%eax <- Note the change in register
  7312. cltd
  7313. }
  7314. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7315. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7316. taicpu(p).loadreg(1, NR_EAX);
  7317. taicpu(hp1).opcode := A_CDQ;
  7318. taicpu(hp1).clearop(1);
  7319. taicpu(hp1).clearop(0);
  7320. taicpu(hp1).ops:=0;
  7321. RemoveInstruction(hp2);
  7322. (*
  7323. {$ifdef x86_64}
  7324. end
  7325. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7326. { This code sequence does not get generated - however it might become useful
  7327. if and when 128-bit signed integer types make an appearance, so the code
  7328. is kept here for when it is eventually needed. [Kit] }
  7329. (
  7330. (
  7331. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7332. (
  7333. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7334. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7335. )
  7336. ) or
  7337. (
  7338. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7339. (
  7340. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7341. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7342. )
  7343. )
  7344. ) and
  7345. GetNextInstruction(hp1, hp2) and
  7346. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7347. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7348. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7349. begin
  7350. { Change:
  7351. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7352. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7353. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7354. To:
  7355. movq r/m,%rax <- Note the change in register
  7356. cqto
  7357. }
  7358. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7359. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7360. taicpu(p).loadreg(1, NR_RAX);
  7361. taicpu(hp1).opcode := A_CQO;
  7362. taicpu(hp1).clearop(1);
  7363. taicpu(hp1).clearop(0);
  7364. taicpu(hp1).ops:=0;
  7365. RemoveInstruction(hp2);
  7366. {$endif x86_64}
  7367. *)
  7368. end;
  7369. end;
  7370. {$ifdef x86_64}
  7371. end
  7372. else if (taicpu(p).opsize = S_L) and
  7373. (taicpu(p).oper[1]^.typ = top_reg) and
  7374. (
  7375. MatchInstruction(hp1, A_MOV,[]) and
  7376. (taicpu(hp1).opsize = S_L) and
  7377. (taicpu(hp1).oper[1]^.typ = top_reg)
  7378. ) and (
  7379. GetNextInstruction(hp1, hp2) and
  7380. (tai(hp2).typ=ait_instruction) and
  7381. (taicpu(hp2).opsize = S_Q) and
  7382. (
  7383. (
  7384. MatchInstruction(hp2, A_ADD,[]) and
  7385. (taicpu(hp2).opsize = S_Q) and
  7386. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7387. (
  7388. (
  7389. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7390. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7391. ) or (
  7392. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7393. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7394. )
  7395. )
  7396. ) or (
  7397. MatchInstruction(hp2, A_LEA,[]) and
  7398. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7399. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7400. (
  7401. (
  7402. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7403. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7404. ) or (
  7405. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7406. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7407. )
  7408. ) and (
  7409. (
  7410. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7411. ) or (
  7412. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7413. )
  7414. )
  7415. )
  7416. )
  7417. ) and (
  7418. GetNextInstruction(hp2, hp3) and
  7419. MatchInstruction(hp3, A_SHR,[]) and
  7420. (taicpu(hp3).opsize = S_Q) and
  7421. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7422. (taicpu(hp3).oper[0]^.val = 1) and
  7423. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7424. ) then
  7425. begin
  7426. { Change movl x, reg1d movl x, reg1d
  7427. movl y, reg2d movl y, reg2d
  7428. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7429. shrq $1, reg1q shrq $1, reg1q
  7430. ( reg1d and reg2d can be switched around in the first two instructions )
  7431. To movl x, reg1d
  7432. addl y, reg1d
  7433. rcrl $1, reg1d
  7434. This corresponds to the common expression (x + y) shr 1, where
  7435. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7436. smaller code, but won't account for x + y causing an overflow). [Kit]
  7437. }
  7438. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7439. { Change first MOV command to have the same register as the final output }
  7440. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7441. else
  7442. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7443. { Change second MOV command to an ADD command. This is easier than
  7444. converting the existing command because it means we don't have to
  7445. touch 'y', which might be a complicated reference, and also the
  7446. fact that the third command might either be ADD or LEA. [Kit] }
  7447. taicpu(hp1).opcode := A_ADD;
  7448. { Delete old ADD/LEA instruction }
  7449. RemoveInstruction(hp2);
  7450. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7451. taicpu(hp3).opcode := A_RCR;
  7452. taicpu(hp3).changeopsize(S_L);
  7453. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7454. {$endif x86_64}
  7455. end;
  7456. end;
  7457. {$push}
  7458. {$q-}{$r-}
  7459. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7460. var
  7461. ThisReg: TRegister;
  7462. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7463. TargetSubReg: TSubRegister;
  7464. hp1, hp2: tai;
  7465. RegInUse, RegChanged, p_removed: Boolean;
  7466. { Store list of found instructions so we don't have to call
  7467. GetNextInstructionUsingReg multiple times }
  7468. InstrList: array of taicpu;
  7469. InstrMax, Index: Integer;
  7470. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7471. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7472. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7473. WorkingValue: TCgInt;
  7474. PreMessage: string;
  7475. { Data flow analysis }
  7476. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7477. BitwiseOnly, OrXorUsed,
  7478. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7479. function CheckOverflowConditions: Boolean;
  7480. begin
  7481. Result := True;
  7482. if (TestValSignedMax > SignedUpperLimit) then
  7483. UpperSignedOverflow := True;
  7484. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7485. LowerSignedOverflow := True;
  7486. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7487. LowerUnsignedOverflow := True;
  7488. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7489. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7490. begin
  7491. { Absolute overflow }
  7492. Result := False;
  7493. Exit;
  7494. end;
  7495. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7496. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7497. ShiftDownOverflow := True;
  7498. if (TestValMin < 0) or (TestValMax < 0) then
  7499. begin
  7500. LowerUnsignedOverflow := True;
  7501. UpperUnsignedOverflow := True;
  7502. end;
  7503. end;
  7504. procedure AdjustFinalLoad;
  7505. begin
  7506. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7507. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7508. begin
  7509. { Convert the output MOVZX to a MOV }
  7510. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7511. begin
  7512. { Or remove it completely! }
  7513. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7514. { Be careful; if p = hp1 and p was also removed, p
  7515. will become a dangling pointer }
  7516. if p = hp1 then
  7517. begin
  7518. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7519. p_removed := True;
  7520. end
  7521. else
  7522. RemoveInstruction(hp1);
  7523. end
  7524. else
  7525. begin
  7526. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7527. taicpu(hp1).opcode := A_MOV;
  7528. taicpu(hp1).oper[0]^.reg := ThisReg;
  7529. taicpu(hp1).opsize := TargetSize;
  7530. end;
  7531. end
  7532. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7533. begin
  7534. { Need to change the size of the output }
  7535. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7536. taicpu(hp1).oper[0]^.reg := ThisReg;
  7537. taicpu(hp1).opsize := S_BL;
  7538. end;
  7539. end;
  7540. function CompressInstructions: Boolean;
  7541. var
  7542. LocalIndex: Integer;
  7543. begin
  7544. Result := False;
  7545. { The objective here is to try to find a combination that
  7546. removes one of the MOV/Z instructions. }
  7547. if (
  7548. (taicpu(p).oper[0]^.typ <> top_reg) or
  7549. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7550. ) and
  7551. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7552. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7553. begin
  7554. { Make a preference to remove the second MOVZX instruction }
  7555. case taicpu(hp1).opsize of
  7556. S_BL, S_WL:
  7557. begin
  7558. TargetSize := S_L;
  7559. TargetSubReg := R_SUBD;
  7560. end;
  7561. S_BW:
  7562. begin
  7563. TargetSize := S_W;
  7564. TargetSubReg := R_SUBW;
  7565. end;
  7566. else
  7567. InternalError(2020112302);
  7568. end;
  7569. end
  7570. else
  7571. begin
  7572. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7573. begin
  7574. { Exceeded lower bound but not upper bound }
  7575. TargetSize := MaxSize;
  7576. end
  7577. else if not LowerUnsignedOverflow then
  7578. begin
  7579. { Size didn't exceed lower bound }
  7580. TargetSize := MinSize;
  7581. end
  7582. else
  7583. Exit;
  7584. end;
  7585. case TargetSize of
  7586. S_B:
  7587. TargetSubReg := R_SUBL;
  7588. S_W:
  7589. TargetSubReg := R_SUBW;
  7590. S_L:
  7591. TargetSubReg := R_SUBD;
  7592. else
  7593. InternalError(2020112350);
  7594. end;
  7595. { Update the register to its new size }
  7596. setsubreg(ThisReg, TargetSubReg);
  7597. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7598. begin
  7599. { Check to see if the active register is used afterwards;
  7600. if not, we can change it and make a saving. }
  7601. RegInUse := False;
  7602. TransferUsedRegs(TmpUsedRegs);
  7603. { The target register may be marked as in use to cross
  7604. a jump to a distant label, so exclude it }
  7605. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7606. hp2 := p;
  7607. repeat
  7608. { Explicitly check for the excluded register (don't include the first
  7609. instruction as it may be reading from here }
  7610. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7611. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7612. begin
  7613. RegInUse := True;
  7614. Break;
  7615. end;
  7616. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7617. if not GetNextInstruction(hp2, hp2) then
  7618. InternalError(2020112340);
  7619. until (hp2 = hp1);
  7620. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7621. { We might still be able to get away with this }
  7622. RegInUse := not
  7623. (
  7624. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7625. (hp2.typ = ait_instruction) and
  7626. (
  7627. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7628. instruction that doesn't actually contain ThisReg }
  7629. (cs_opt_level3 in current_settings.optimizerswitches) or
  7630. RegInInstruction(ThisReg, hp2)
  7631. ) and
  7632. RegLoadedWithNewValue(ThisReg, hp2)
  7633. );
  7634. if not RegInUse then
  7635. begin
  7636. { Force the register size to the same as this instruction so it can be removed}
  7637. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7638. begin
  7639. TargetSize := S_L;
  7640. TargetSubReg := R_SUBD;
  7641. end
  7642. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7643. begin
  7644. TargetSize := S_W;
  7645. TargetSubReg := R_SUBW;
  7646. end;
  7647. ThisReg := taicpu(hp1).oper[1]^.reg;
  7648. setsubreg(ThisReg, TargetSubReg);
  7649. RegChanged := True;
  7650. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7651. TransferUsedRegs(TmpUsedRegs);
  7652. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7653. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7654. if p = hp1 then
  7655. begin
  7656. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7657. p_removed := True;
  7658. end
  7659. else
  7660. RemoveInstruction(hp1);
  7661. { Instruction will become "mov %reg,%reg" }
  7662. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7663. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7664. begin
  7665. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7666. RemoveCurrentP(p);
  7667. p_removed := True;
  7668. end
  7669. else
  7670. taicpu(p).oper[1]^.reg := ThisReg;
  7671. Result := True;
  7672. end
  7673. else
  7674. begin
  7675. if TargetSize <> MaxSize then
  7676. begin
  7677. { Since the register is in use, we have to force it to
  7678. MaxSize otherwise part of it may become undefined later on }
  7679. TargetSize := MaxSize;
  7680. case TargetSize of
  7681. S_B:
  7682. TargetSubReg := R_SUBL;
  7683. S_W:
  7684. TargetSubReg := R_SUBW;
  7685. S_L:
  7686. TargetSubReg := R_SUBD;
  7687. else
  7688. InternalError(2020112351);
  7689. end;
  7690. setsubreg(ThisReg, TargetSubReg);
  7691. end;
  7692. AdjustFinalLoad;
  7693. end;
  7694. end
  7695. else
  7696. AdjustFinalLoad;
  7697. if not p_removed then
  7698. begin
  7699. if TargetSize = MinSize then
  7700. begin
  7701. { Convert the input MOVZX to a MOV }
  7702. if (taicpu(p).oper[0]^.typ = top_reg) and
  7703. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7704. begin
  7705. { Or remove it completely! }
  7706. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7707. DebugMsg(SPeepholeOptimization + tostr(InstrMax), p);
  7708. RemoveCurrentP(p);
  7709. p_removed := True;
  7710. end
  7711. else
  7712. begin
  7713. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7714. taicpu(p).opcode := A_MOV;
  7715. taicpu(p).oper[1]^.reg := ThisReg;
  7716. taicpu(p).opsize := TargetSize;
  7717. end;
  7718. Result := True;
  7719. end
  7720. else if TargetSize <> MaxSize then
  7721. begin
  7722. case MaxSize of
  7723. S_L:
  7724. if TargetSize = S_W then
  7725. begin
  7726. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7727. taicpu(p).opsize := S_BW;
  7728. taicpu(p).oper[1]^.reg := ThisReg;
  7729. Result := True;
  7730. end
  7731. else
  7732. InternalError(2020112341);
  7733. S_W:
  7734. if TargetSize = S_L then
  7735. begin
  7736. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7737. taicpu(p).opsize := S_BL;
  7738. taicpu(p).oper[1]^.reg := ThisReg;
  7739. Result := True;
  7740. end
  7741. else
  7742. InternalError(2020112342);
  7743. else
  7744. ;
  7745. end;
  7746. end;
  7747. end;
  7748. { Now go through every instruction we found and change the
  7749. size. If TargetSize = MaxSize, then almost no changes are
  7750. needed and Result can remain False if it hasn't been set
  7751. yet.
  7752. If RegChanged is True, then the register requires changing
  7753. and so the point about TargetSize = MaxSize doesn't apply. }
  7754. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7755. begin
  7756. for LocalIndex := 0 to InstrMax do
  7757. begin
  7758. { If p_removed is true, then the original MOV/Z was removed
  7759. and removing the AND instruction may not be safe if it
  7760. appears first }
  7761. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7762. InternalError(2020112310);
  7763. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7764. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7765. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7766. InstrList[LocalIndex].opsize := TargetSize;
  7767. end;
  7768. Result := True;
  7769. end;
  7770. end;
  7771. begin
  7772. Result := False;
  7773. p_removed := False;
  7774. ThisReg := taicpu(p).oper[1]^.reg;
  7775. { Check for:
  7776. movs/z ###,%ecx (or %cx or %rcx)
  7777. ...
  7778. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7779. (dealloc %ecx)
  7780. Change to:
  7781. mov ###,%cl (if ### = %cl, then remove completely)
  7782. ...
  7783. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7784. }
  7785. if (getsupreg(ThisReg) = RS_ECX) and
  7786. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  7787. (hp1.typ = ait_instruction) and
  7788. (
  7789. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7790. instruction that doesn't actually contain ECX }
  7791. (cs_opt_level3 in current_settings.optimizerswitches) or
  7792. RegInInstruction(NR_ECX, hp1) or
  7793. (
  7794. { It's common for the shift/rotate's read/write register to be
  7795. initialised in between, so under -O2 and under, search ahead
  7796. one more instruction
  7797. }
  7798. GetNextInstruction(hp1, hp1) and
  7799. (hp1.typ = ait_instruction) and
  7800. RegInInstruction(NR_ECX, hp1)
  7801. )
  7802. ) and
  7803. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  7804. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  7805. begin
  7806. TransferUsedRegs(TmpUsedRegs);
  7807. hp2 := p;
  7808. repeat
  7809. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7810. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7811. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  7812. begin
  7813. case taicpu(p).opsize of
  7814. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7815. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  7816. begin
  7817. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  7818. RemoveCurrentP(p);
  7819. end
  7820. else
  7821. begin
  7822. taicpu(p).opcode := A_MOV;
  7823. taicpu(p).opsize := S_B;
  7824. taicpu(p).oper[1]^.reg := NR_CL;
  7825. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  7826. end;
  7827. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7828. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  7829. begin
  7830. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  7831. RemoveCurrentP(p);
  7832. end
  7833. else
  7834. begin
  7835. taicpu(p).opcode := A_MOV;
  7836. taicpu(p).opsize := S_W;
  7837. taicpu(p).oper[1]^.reg := NR_CX;
  7838. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  7839. end;
  7840. {$ifdef x86_64}
  7841. S_LQ:
  7842. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  7843. begin
  7844. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  7845. RemoveCurrentP(p);
  7846. end
  7847. else
  7848. begin
  7849. taicpu(p).opcode := A_MOV;
  7850. taicpu(p).opsize := S_L;
  7851. taicpu(p).oper[1]^.reg := NR_ECX;
  7852. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  7853. end;
  7854. {$endif x86_64}
  7855. else
  7856. InternalError(2021120401);
  7857. end;
  7858. Result := True;
  7859. Exit;
  7860. end;
  7861. end;
  7862. { This is anything but quick! }
  7863. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  7864. Exit;
  7865. SetLength(InstrList, 0);
  7866. InstrMax := -1;
  7867. case taicpu(p).opsize of
  7868. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7869. begin
  7870. {$if defined(i386) or defined(i8086)}
  7871. { If the target size is 8-bit, make sure we can actually encode it }
  7872. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  7873. Exit;
  7874. {$endif i386 or i8086}
  7875. LowerLimit := $FF;
  7876. SignedLowerLimit := $7F;
  7877. SignedLowerLimitBottom := -128;
  7878. MinSize := S_B;
  7879. if taicpu(p).opsize = S_BW then
  7880. begin
  7881. MaxSize := S_W;
  7882. UpperLimit := $FFFF;
  7883. SignedUpperLimit := $7FFF;
  7884. SignedUpperLimitBottom := -32768;
  7885. end
  7886. else
  7887. begin
  7888. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  7889. MaxSize := S_L;
  7890. UpperLimit := $FFFFFFFF;
  7891. SignedUpperLimit := $7FFFFFFF;
  7892. SignedUpperLimitBottom := -2147483648;
  7893. end;
  7894. end;
  7895. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7896. begin
  7897. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  7898. LowerLimit := $FFFF;
  7899. SignedLowerLimit := $7FFF;
  7900. SignedLowerLimitBottom := -32768;
  7901. UpperLimit := $FFFFFFFF;
  7902. SignedUpperLimit := $7FFFFFFF;
  7903. SignedUpperLimitBottom := -2147483648;
  7904. MinSize := S_W;
  7905. MaxSize := S_L;
  7906. end;
  7907. {$ifdef x86_64}
  7908. S_LQ:
  7909. begin
  7910. { Both the lower and upper limits are set to 32-bit. If a limit
  7911. is breached, then optimisation is impossible }
  7912. LowerLimit := $FFFFFFFF;
  7913. SignedLowerLimit := $7FFFFFFF;
  7914. SignedLowerLimitBottom := -2147483648;
  7915. UpperLimit := $FFFFFFFF;
  7916. SignedUpperLimit := $7FFFFFFF;
  7917. SignedUpperLimitBottom := -2147483648;
  7918. MinSize := S_L;
  7919. MaxSize := S_L;
  7920. end;
  7921. {$endif x86_64}
  7922. else
  7923. InternalError(2020112301);
  7924. end;
  7925. TestValMin := 0;
  7926. TestValMax := LowerLimit;
  7927. TestValSignedMax := SignedLowerLimit;
  7928. TryShiftDownLimit := LowerLimit;
  7929. TryShiftDown := S_NO;
  7930. ShiftDownOverflow := False;
  7931. RegChanged := False;
  7932. BitwiseOnly := True;
  7933. OrXorUsed := False;
  7934. UpperSignedOverflow := False;
  7935. LowerSignedOverflow := False;
  7936. UpperUnsignedOverflow := False;
  7937. LowerUnsignedOverflow := False;
  7938. hp1 := p;
  7939. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  7940. (hp1.typ = ait_instruction) and
  7941. (
  7942. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7943. instruction that doesn't actually contain ThisReg }
  7944. (cs_opt_level3 in current_settings.optimizerswitches) or
  7945. { This allows this Movx optimisation to work through the SETcc instructions
  7946. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  7947. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  7948. skip over these SETcc instructions). }
  7949. (taicpu(hp1).opcode = A_SETcc) or
  7950. RegInInstruction(ThisReg, hp1)
  7951. ) do
  7952. begin
  7953. case taicpu(hp1).opcode of
  7954. A_INC,A_DEC:
  7955. begin
  7956. { Has to be an exact match on the register }
  7957. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7958. Break;
  7959. if taicpu(hp1).opcode = A_INC then
  7960. begin
  7961. Inc(TestValMin);
  7962. Inc(TestValMax);
  7963. Inc(TestValSignedMax);
  7964. end
  7965. else
  7966. begin
  7967. Dec(TestValMin);
  7968. Dec(TestValMax);
  7969. Dec(TestValSignedMax);
  7970. end;
  7971. end;
  7972. A_TEST, A_CMP:
  7973. begin
  7974. if (
  7975. { Too high a risk of non-linear behaviour that breaks DFA
  7976. here, unless it's cmp $0,%reg, which is equivalent to
  7977. test %reg,%reg }
  7978. OrXorUsed and
  7979. (taicpu(hp1).opcode = A_CMP) and
  7980. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  7981. ) or
  7982. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7983. { Has to be an exact match on the register }
  7984. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7985. (
  7986. { Permit "test %reg,%reg" }
  7987. (taicpu(hp1).opcode = A_TEST) and
  7988. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7989. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  7990. ) or
  7991. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7992. { Make sure the comparison value is not smaller than the
  7993. smallest allowed signed value for the minimum size (e.g.
  7994. -128 for 8-bit) }
  7995. not (
  7996. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  7997. { Is it in the negative range? }
  7998. (
  7999. (taicpu(hp1).oper[0]^.val < 0) and
  8000. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8001. )
  8002. ) then
  8003. Break;
  8004. { Check to see if the active register is used afterwards }
  8005. TransferUsedRegs(TmpUsedRegs);
  8006. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8007. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8008. begin
  8009. { Make sure the comparison or any previous instructions
  8010. hasn't pushed the test values outside of the range of
  8011. MinSize }
  8012. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8013. begin
  8014. { Exceeded lower bound but not upper bound }
  8015. TargetSize := MaxSize;
  8016. end
  8017. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8018. begin
  8019. { Size didn't exceed lower bound }
  8020. TargetSize := MinSize;
  8021. end
  8022. else
  8023. Break;
  8024. case TargetSize of
  8025. S_B:
  8026. TargetSubReg := R_SUBL;
  8027. S_W:
  8028. TargetSubReg := R_SUBW;
  8029. S_L:
  8030. TargetSubReg := R_SUBD;
  8031. else
  8032. InternalError(2021051002);
  8033. end;
  8034. { Update the register to its new size }
  8035. setsubreg(ThisReg, TargetSubReg);
  8036. taicpu(hp1).oper[1]^.reg := ThisReg;
  8037. taicpu(hp1).opsize := MinSize;
  8038. { Convert the input MOVZX to a MOV }
  8039. if (taicpu(p).oper[0]^.typ = top_reg) and
  8040. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8041. begin
  8042. { Or remove it completely! }
  8043. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8044. RemoveCurrentP(p);
  8045. p_removed := True;
  8046. end
  8047. else
  8048. begin
  8049. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8050. taicpu(p).opcode := A_MOV;
  8051. taicpu(p).oper[1]^.reg := ThisReg;
  8052. taicpu(p).opsize := MinSize;
  8053. end;
  8054. if (InstrMax >= 0) then
  8055. begin
  8056. for Index := 0 to InstrMax do
  8057. begin
  8058. { If p_removed is true, then the original MOV/Z was removed
  8059. and removing the AND instruction may not be safe if it
  8060. appears first }
  8061. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8062. InternalError(2020112311);
  8063. if InstrList[Index].oper[0]^.typ = top_reg then
  8064. InstrList[Index].oper[0]^.reg := ThisReg;
  8065. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8066. InstrList[Index].opsize := MinSize;
  8067. end;
  8068. end;
  8069. Result := True;
  8070. Exit;
  8071. end;
  8072. end;
  8073. A_SETcc:
  8074. begin
  8075. { This allows this Movx optimisation to work through the SETcc instructions
  8076. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8077. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8078. skip over these SETcc instructions). }
  8079. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8080. { Of course, break out if the current register is used }
  8081. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8082. Break
  8083. else
  8084. { We must use Continue so the instruction doesn't get added
  8085. to InstrList }
  8086. Continue;
  8087. end;
  8088. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8089. begin
  8090. if
  8091. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8092. { Has to be an exact match on the register }
  8093. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8094. (
  8095. (
  8096. (taicpu(hp1).oper[0]^.typ = top_const) and
  8097. (
  8098. (
  8099. (taicpu(hp1).opcode = A_SHL) and
  8100. (
  8101. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8102. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8103. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8104. )
  8105. ) or (
  8106. (taicpu(hp1).opcode <> A_SHL) and
  8107. (
  8108. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8109. { Is it in the negative range? }
  8110. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8111. )
  8112. )
  8113. )
  8114. ) or (
  8115. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8116. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8117. )
  8118. ) then
  8119. Break;
  8120. { Only process OR and XOR if there are only bitwise operations,
  8121. since otherwise they can too easily fool the data flow
  8122. analysis (they can cause non-linear behaviour) }
  8123. case taicpu(hp1).opcode of
  8124. A_ADD:
  8125. begin
  8126. if OrXorUsed then
  8127. { Too high a risk of non-linear behaviour that breaks DFA here }
  8128. Break
  8129. else
  8130. BitwiseOnly := False;
  8131. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8132. begin
  8133. TestValMin := TestValMin * 2;
  8134. TestValMax := TestValMax * 2;
  8135. TestValSignedMax := TestValSignedMax * 2;
  8136. end
  8137. else
  8138. begin
  8139. WorkingValue := taicpu(hp1).oper[0]^.val;
  8140. TestValMin := TestValMin + WorkingValue;
  8141. TestValMax := TestValMax + WorkingValue;
  8142. TestValSignedMax := TestValSignedMax + WorkingValue;
  8143. end;
  8144. end;
  8145. A_SUB:
  8146. begin
  8147. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8148. begin
  8149. TestValMin := 0;
  8150. TestValMax := 0;
  8151. TestValSignedMax := 0;
  8152. end
  8153. else
  8154. begin
  8155. if OrXorUsed then
  8156. { Too high a risk of non-linear behaviour that breaks DFA here }
  8157. Break
  8158. else
  8159. BitwiseOnly := False;
  8160. WorkingValue := taicpu(hp1).oper[0]^.val;
  8161. TestValMin := TestValMin - WorkingValue;
  8162. TestValMax := TestValMax - WorkingValue;
  8163. TestValSignedMax := TestValSignedMax - WorkingValue;
  8164. end;
  8165. end;
  8166. A_AND:
  8167. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8168. begin
  8169. { we might be able to go smaller if AND appears first }
  8170. if InstrMax = -1 then
  8171. case MinSize of
  8172. S_B:
  8173. ;
  8174. S_W:
  8175. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8176. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8177. begin
  8178. TryShiftDown := S_B;
  8179. TryShiftDownLimit := $FF;
  8180. end;
  8181. S_L:
  8182. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8183. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8184. begin
  8185. TryShiftDown := S_B;
  8186. TryShiftDownLimit := $FF;
  8187. end
  8188. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8189. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8190. begin
  8191. TryShiftDown := S_W;
  8192. TryShiftDownLimit := $FFFF;
  8193. end;
  8194. else
  8195. InternalError(2020112320);
  8196. end;
  8197. WorkingValue := taicpu(hp1).oper[0]^.val;
  8198. TestValMin := TestValMin and WorkingValue;
  8199. TestValMax := TestValMax and WorkingValue;
  8200. TestValSignedMax := TestValSignedMax and WorkingValue;
  8201. end;
  8202. A_OR:
  8203. begin
  8204. if not BitwiseOnly then
  8205. Break;
  8206. OrXorUsed := True;
  8207. WorkingValue := taicpu(hp1).oper[0]^.val;
  8208. TestValMin := TestValMin or WorkingValue;
  8209. TestValMax := TestValMax or WorkingValue;
  8210. TestValSignedMax := TestValSignedMax or WorkingValue;
  8211. end;
  8212. A_XOR:
  8213. begin
  8214. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8215. begin
  8216. TestValMin := 0;
  8217. TestValMax := 0;
  8218. TestValSignedMax := 0;
  8219. end
  8220. else
  8221. begin
  8222. if not BitwiseOnly then
  8223. Break;
  8224. OrXorUsed := True;
  8225. WorkingValue := taicpu(hp1).oper[0]^.val;
  8226. TestValMin := TestValMin xor WorkingValue;
  8227. TestValMax := TestValMax xor WorkingValue;
  8228. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8229. end;
  8230. end;
  8231. A_SHL:
  8232. begin
  8233. BitwiseOnly := False;
  8234. WorkingValue := taicpu(hp1).oper[0]^.val;
  8235. TestValMin := TestValMin shl WorkingValue;
  8236. TestValMax := TestValMax shl WorkingValue;
  8237. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8238. end;
  8239. A_SHR,
  8240. { The first instruction was MOVZX, so the value won't be negative }
  8241. A_SAR:
  8242. begin
  8243. if InstrMax <> -1 then
  8244. BitwiseOnly := False
  8245. else
  8246. { we might be able to go smaller if SHR appears first }
  8247. case MinSize of
  8248. S_B:
  8249. ;
  8250. S_W:
  8251. if (taicpu(hp1).oper[0]^.val >= 8) then
  8252. begin
  8253. TryShiftDown := S_B;
  8254. TryShiftDownLimit := $FF;
  8255. TryShiftDownSignedLimit := $7F;
  8256. TryShiftDownSignedLimitLower := -128;
  8257. end;
  8258. S_L:
  8259. if (taicpu(hp1).oper[0]^.val >= 24) then
  8260. begin
  8261. TryShiftDown := S_B;
  8262. TryShiftDownLimit := $FF;
  8263. TryShiftDownSignedLimit := $7F;
  8264. TryShiftDownSignedLimitLower := -128;
  8265. end
  8266. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8267. begin
  8268. TryShiftDown := S_W;
  8269. TryShiftDownLimit := $FFFF;
  8270. TryShiftDownSignedLimit := $7FFF;
  8271. TryShiftDownSignedLimitLower := -32768;
  8272. end;
  8273. else
  8274. InternalError(2020112321);
  8275. end;
  8276. WorkingValue := taicpu(hp1).oper[0]^.val;
  8277. if taicpu(hp1).opcode = A_SAR then
  8278. begin
  8279. TestValMin := SarInt64(TestValMin, WorkingValue);
  8280. TestValMax := SarInt64(TestValMax, WorkingValue);
  8281. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8282. end
  8283. else
  8284. begin
  8285. TestValMin := TestValMin shr WorkingValue;
  8286. TestValMax := TestValMax shr WorkingValue;
  8287. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8288. end;
  8289. end;
  8290. else
  8291. InternalError(2020112303);
  8292. end;
  8293. end;
  8294. (*
  8295. A_IMUL:
  8296. case taicpu(hp1).ops of
  8297. 2:
  8298. begin
  8299. if not MatchOpType(hp1, top_reg, top_reg) or
  8300. { Has to be an exact match on the register }
  8301. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8302. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8303. Break;
  8304. TestValMin := TestValMin * TestValMin;
  8305. TestValMax := TestValMax * TestValMax;
  8306. TestValSignedMax := TestValSignedMax * TestValMax;
  8307. end;
  8308. 3:
  8309. begin
  8310. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8311. { Has to be an exact match on the register }
  8312. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8313. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8314. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8315. { Is it in the negative range? }
  8316. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8317. Break;
  8318. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8319. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8320. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8321. end;
  8322. else
  8323. Break;
  8324. end;
  8325. A_IDIV:
  8326. case taicpu(hp1).ops of
  8327. 3:
  8328. begin
  8329. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8330. { Has to be an exact match on the register }
  8331. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8332. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8333. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8334. { Is it in the negative range? }
  8335. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8336. Break;
  8337. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8338. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8339. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8340. end;
  8341. else
  8342. Break;
  8343. end;
  8344. *)
  8345. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8346. begin
  8347. { If there are no instructions in between, then we might be able to make a saving }
  8348. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8349. Break;
  8350. { We have something like:
  8351. movzbw %dl,%dx
  8352. ...
  8353. movswl %dx,%edx
  8354. Change the latter to a zero-extension then enter the
  8355. A_MOVZX case branch.
  8356. }
  8357. {$ifdef x86_64}
  8358. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8359. begin
  8360. { this becomes a zero extension from 32-bit to 64-bit, but
  8361. the upper 32 bits are already zero, so just delete the
  8362. instruction }
  8363. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8364. RemoveInstruction(hp1);
  8365. Result := True;
  8366. Exit;
  8367. end
  8368. else
  8369. {$endif x86_64}
  8370. begin
  8371. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8372. taicpu(hp1).opcode := A_MOVZX;
  8373. {$ifdef x86_64}
  8374. case taicpu(hp1).opsize of
  8375. S_BQ:
  8376. begin
  8377. taicpu(hp1).opsize := S_BL;
  8378. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8379. end;
  8380. S_WQ:
  8381. begin
  8382. taicpu(hp1).opsize := S_WL;
  8383. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8384. end;
  8385. S_LQ:
  8386. begin
  8387. taicpu(hp1).opcode := A_MOV;
  8388. taicpu(hp1).opsize := S_L;
  8389. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8390. { In this instance, we need to break out because the
  8391. instruction is no longer MOVZX or MOVSXD }
  8392. Result := True;
  8393. Exit;
  8394. end;
  8395. else
  8396. ;
  8397. end;
  8398. {$endif x86_64}
  8399. Result := CompressInstructions;
  8400. Exit;
  8401. end;
  8402. end;
  8403. A_MOVZX:
  8404. begin
  8405. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8406. Break;
  8407. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8408. begin
  8409. if (InstrMax = -1) and
  8410. { Will return false if the second parameter isn't ThisReg
  8411. (can happen on -O2 and under) }
  8412. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8413. begin
  8414. { The two MOVZX instructions are adjacent, so remove the first one }
  8415. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8416. RemoveCurrentP(p);
  8417. Result := True;
  8418. Exit;
  8419. end;
  8420. Break;
  8421. end;
  8422. Result := CompressInstructions;
  8423. Exit;
  8424. end;
  8425. else
  8426. { This includes ADC, SBB and IDIV }
  8427. Break;
  8428. end;
  8429. if not CheckOverflowConditions then
  8430. Break;
  8431. { Contains highest index (so instruction count - 1) }
  8432. Inc(InstrMax);
  8433. if InstrMax > High(InstrList) then
  8434. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8435. InstrList[InstrMax] := taicpu(hp1);
  8436. end;
  8437. end;
  8438. {$pop}
  8439. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8440. var
  8441. hp1 : tai;
  8442. begin
  8443. Result:=false;
  8444. if (taicpu(p).ops >= 2) and
  8445. ((taicpu(p).oper[0]^.typ = top_const) or
  8446. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8447. (taicpu(p).oper[1]^.typ = top_reg) and
  8448. ((taicpu(p).ops = 2) or
  8449. ((taicpu(p).oper[2]^.typ = top_reg) and
  8450. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8451. GetLastInstruction(p,hp1) and
  8452. MatchInstruction(hp1,A_MOV,[]) and
  8453. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8454. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8455. begin
  8456. TransferUsedRegs(TmpUsedRegs);
  8457. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8458. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8459. { change
  8460. mov reg1,reg2
  8461. imul y,reg2 to imul y,reg1,reg2 }
  8462. begin
  8463. taicpu(p).ops := 3;
  8464. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8465. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8466. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8467. RemoveInstruction(hp1);
  8468. result:=true;
  8469. end;
  8470. end;
  8471. end;
  8472. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8473. var
  8474. ThisLabel: TAsmLabel;
  8475. begin
  8476. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8477. ThisLabel.decrefs;
  8478. taicpu(p).opcode := A_RET;
  8479. taicpu(p).is_jmp := false;
  8480. taicpu(p).ops := taicpu(ret_p).ops;
  8481. case taicpu(ret_p).ops of
  8482. 0:
  8483. taicpu(p).clearop(0);
  8484. 1:
  8485. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8486. else
  8487. internalerror(2016041301);
  8488. end;
  8489. { If the original label is now dead, it might turn out that the label
  8490. immediately follows p. As a result, everything beyond it, which will
  8491. be just some final register configuration and a RET instruction, is
  8492. now dead code. [Kit] }
  8493. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8494. running RemoveDeadCodeAfterJump for each RET instruction, because
  8495. this optimisation rarely happens and most RETs appear at the end of
  8496. routines where there is nothing that can be stripped. [Kit] }
  8497. if not ThisLabel.is_used then
  8498. RemoveDeadCodeAfterJump(p);
  8499. end;
  8500. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8501. var
  8502. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8503. Unconditional, PotentialModified: Boolean;
  8504. OperPtr: POper;
  8505. NewRef: TReference;
  8506. InstrList: array of taicpu;
  8507. InstrMax, Index: Integer;
  8508. const
  8509. {$ifdef DEBUG_AOPTCPU}
  8510. SNoFlags: shortstring = ' so the flags aren''t modified';
  8511. {$else DEBUG_AOPTCPU}
  8512. SNoFlags = '';
  8513. {$endif DEBUG_AOPTCPU}
  8514. begin
  8515. Result:=false;
  8516. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8517. begin
  8518. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8519. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8520. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8521. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8522. GetNextInstruction(hp1, hp2) and
  8523. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8524. { Change from: To:
  8525. set(C) %reg j(~C) label
  8526. test %reg,%reg/cmp $0,%reg
  8527. je label
  8528. set(C) %reg j(C) label
  8529. test %reg,%reg/cmp $0,%reg
  8530. jne label
  8531. (Also do something similar with sete/setne instead of je/jne)
  8532. }
  8533. begin
  8534. { Before we do anything else, we need to check the instructions
  8535. in between SETcc and TEST to make sure they don't modify the
  8536. FLAGS register - if -O2 or under, there won't be any
  8537. instructions between SET and TEST }
  8538. TransferUsedRegs(TmpUsedRegs);
  8539. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8540. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8541. begin
  8542. next := p;
  8543. SetLength(InstrList, 0);
  8544. InstrMax := -1;
  8545. PotentialModified := False;
  8546. { Make a note of every instruction that modifies the FLAGS
  8547. register }
  8548. while GetNextInstruction(next, next) and (next <> hp1) do
  8549. begin
  8550. if next.typ <> ait_instruction then
  8551. { GetNextInstructionUsingReg should have returned False }
  8552. InternalError(2021051701);
  8553. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8554. begin
  8555. case taicpu(next).opcode of
  8556. A_SETcc,
  8557. A_CMOVcc,
  8558. A_Jcc:
  8559. begin
  8560. if PotentialModified then
  8561. { Not safe because the flags were modified earlier }
  8562. Exit
  8563. else
  8564. { Condition is the same as the initial SETcc, so this is safe
  8565. (don't add to instruction list though) }
  8566. Continue;
  8567. end;
  8568. A_ADD:
  8569. begin
  8570. if (taicpu(next).opsize = S_B) or
  8571. { LEA doesn't support 8-bit operands }
  8572. (taicpu(next).oper[1]^.typ <> top_reg) or
  8573. { Must write to a register }
  8574. (taicpu(next).oper[0]^.typ = top_ref) then
  8575. { Require a constant or a register }
  8576. Exit;
  8577. PotentialModified := True;
  8578. end;
  8579. A_SUB:
  8580. begin
  8581. if (taicpu(next).opsize = S_B) or
  8582. { LEA doesn't support 8-bit operands }
  8583. (taicpu(next).oper[1]^.typ <> top_reg) or
  8584. { Must write to a register }
  8585. (taicpu(next).oper[0]^.typ <> top_const) or
  8586. (taicpu(next).oper[0]^.val = $80000000) then
  8587. { Can't subtract a register with LEA - also
  8588. check that the value isn't -2^31, as this
  8589. can't be negated }
  8590. Exit;
  8591. PotentialModified := True;
  8592. end;
  8593. A_SAL,
  8594. A_SHL:
  8595. begin
  8596. if (taicpu(next).opsize = S_B) or
  8597. { LEA doesn't support 8-bit operands }
  8598. (taicpu(next).oper[1]^.typ <> top_reg) or
  8599. { Must write to a register }
  8600. (taicpu(next).oper[0]^.typ <> top_const) or
  8601. (taicpu(next).oper[0]^.val < 0) or
  8602. (taicpu(next).oper[0]^.val > 3) then
  8603. Exit;
  8604. PotentialModified := True;
  8605. end;
  8606. A_IMUL:
  8607. begin
  8608. if (taicpu(next).ops <> 3) or
  8609. (taicpu(next).oper[1]^.typ <> top_reg) or
  8610. { Must write to a register }
  8611. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8612. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8613. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8614. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8615. Exit
  8616. else
  8617. PotentialModified := True;
  8618. end;
  8619. else
  8620. { Don't know how to change this, so abort }
  8621. Exit;
  8622. end;
  8623. { Contains highest index (so instruction count - 1) }
  8624. Inc(InstrMax);
  8625. if InstrMax > High(InstrList) then
  8626. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8627. InstrList[InstrMax] := taicpu(next);
  8628. end;
  8629. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8630. end;
  8631. if not Assigned(next) or (next <> hp1) then
  8632. { It should be equal to hp1 }
  8633. InternalError(2021051702);
  8634. { Cycle through each instruction and check to see if we can
  8635. change them to versions that don't modify the flags }
  8636. if (InstrMax >= 0) then
  8637. begin
  8638. for Index := 0 to InstrMax do
  8639. case InstrList[Index].opcode of
  8640. A_ADD:
  8641. begin
  8642. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8643. InstrList[Index].opcode := A_LEA;
  8644. reference_reset(NewRef, 1, []);
  8645. NewRef.base := InstrList[Index].oper[1]^.reg;
  8646. if InstrList[Index].oper[0]^.typ = top_reg then
  8647. begin
  8648. NewRef.index := InstrList[Index].oper[0]^.reg;
  8649. NewRef.scalefactor := 1;
  8650. end
  8651. else
  8652. NewRef.offset := InstrList[Index].oper[0]^.val;
  8653. InstrList[Index].loadref(0, NewRef);
  8654. end;
  8655. A_SUB:
  8656. begin
  8657. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8658. InstrList[Index].opcode := A_LEA;
  8659. reference_reset(NewRef, 1, []);
  8660. NewRef.base := InstrList[Index].oper[1]^.reg;
  8661. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8662. InstrList[Index].loadref(0, NewRef);
  8663. end;
  8664. A_SHL,
  8665. A_SAL:
  8666. begin
  8667. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8668. InstrList[Index].opcode := A_LEA;
  8669. reference_reset(NewRef, 1, []);
  8670. NewRef.index := InstrList[Index].oper[1]^.reg;
  8671. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8672. InstrList[Index].loadref(0, NewRef);
  8673. end;
  8674. A_IMUL:
  8675. begin
  8676. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8677. InstrList[Index].opcode := A_LEA;
  8678. reference_reset(NewRef, 1, []);
  8679. NewRef.index := InstrList[Index].oper[1]^.reg;
  8680. case InstrList[Index].oper[0]^.val of
  8681. 2, 4, 8:
  8682. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8683. else {3, 5 and 9}
  8684. begin
  8685. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8686. NewRef.base := InstrList[Index].oper[1]^.reg;
  8687. end;
  8688. end;
  8689. InstrList[Index].loadref(0, NewRef);
  8690. end;
  8691. else
  8692. InternalError(2021051710);
  8693. end;
  8694. end;
  8695. { Mark the FLAGS register as used across this whole block }
  8696. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8697. end;
  8698. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8699. JumpC := taicpu(hp2).condition;
  8700. Unconditional := False;
  8701. if conditions_equal(JumpC, C_E) then
  8702. SetC := inverse_cond(taicpu(p).condition)
  8703. else if conditions_equal(JumpC, C_NE) then
  8704. SetC := taicpu(p).condition
  8705. else
  8706. { We've got something weird here (and inefficent) }
  8707. begin
  8708. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8709. SetC := C_NONE;
  8710. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8711. if condition_in(C_AE, JumpC) then
  8712. Unconditional := True
  8713. else
  8714. { Not sure what to do with this jump - drop out }
  8715. Exit;
  8716. end;
  8717. RemoveInstruction(hp1);
  8718. if Unconditional then
  8719. MakeUnconditional(taicpu(hp2))
  8720. else
  8721. begin
  8722. if SetC = C_NONE then
  8723. InternalError(2018061402);
  8724. taicpu(hp2).SetCondition(SetC);
  8725. end;
  8726. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8727. TmpUsedRegs }
  8728. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8729. begin
  8730. RemoveCurrentp(p, hp2);
  8731. if taicpu(hp2).opcode = A_SETcc then
  8732. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8733. else
  8734. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8735. end
  8736. else
  8737. if taicpu(hp2).opcode = A_SETcc then
  8738. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8739. else
  8740. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8741. Result := True;
  8742. end
  8743. else if
  8744. { Make sure the instructions are adjacent }
  8745. (
  8746. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8747. GetNextInstruction(p, hp1)
  8748. ) and
  8749. MatchInstruction(hp1, A_MOV, [S_B]) and
  8750. { Writing to memory is allowed }
  8751. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8752. begin
  8753. {
  8754. Watch out for sequences such as:
  8755. set(c)b %regb
  8756. movb %regb,(ref)
  8757. movb $0,1(ref)
  8758. movb $0,2(ref)
  8759. movb $0,3(ref)
  8760. Much more efficient to turn it into:
  8761. movl $0,%regl
  8762. set(c)b %regb
  8763. movl %regl,(ref)
  8764. Or:
  8765. set(c)b %regb
  8766. movzbl %regb,%regl
  8767. movl %regl,(ref)
  8768. }
  8769. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8770. GetNextInstruction(hp1, hp2) and
  8771. MatchInstruction(hp2, A_MOV, [S_B]) and
  8772. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8773. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8774. begin
  8775. { Don't do anything else except set Result to True }
  8776. end
  8777. else
  8778. begin
  8779. if taicpu(p).oper[0]^.typ = top_reg then
  8780. begin
  8781. TransferUsedRegs(TmpUsedRegs);
  8782. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8783. end;
  8784. { If it's not a register, it's a memory address }
  8785. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  8786. begin
  8787. { Even if the register is still in use, we can minimise the
  8788. pipeline stall by changing the MOV into another SETcc. }
  8789. taicpu(hp1).opcode := A_SETcc;
  8790. taicpu(hp1).condition := taicpu(p).condition;
  8791. if taicpu(hp1).oper[1]^.typ = top_ref then
  8792. begin
  8793. { Swapping the operand pointers like this is probably a
  8794. bit naughty, but it is far faster than using loadoper
  8795. to transfer the reference from oper[1] to oper[0] if
  8796. you take into account the extra procedure calls and
  8797. the memory allocation and deallocation required }
  8798. OperPtr := taicpu(hp1).oper[1];
  8799. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  8800. taicpu(hp1).oper[0] := OperPtr;
  8801. end
  8802. else
  8803. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  8804. taicpu(hp1).clearop(1);
  8805. taicpu(hp1).ops := 1;
  8806. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  8807. end
  8808. else
  8809. begin
  8810. if taicpu(hp1).oper[1]^.typ = top_reg then
  8811. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  8812. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8813. RemoveInstruction(hp1);
  8814. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  8815. end
  8816. end;
  8817. Result := True;
  8818. end;
  8819. end;
  8820. end;
  8821. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  8822. var
  8823. hp1: tai;
  8824. Count: Integer;
  8825. OrigLabel: TAsmLabel;
  8826. begin
  8827. result := False;
  8828. { Sometimes, the optimisations below can permit this }
  8829. RemoveDeadCodeAfterJump(p);
  8830. 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
  8831. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  8832. begin
  8833. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8834. { Also a side-effect of optimisations }
  8835. if CollapseZeroDistJump(p, OrigLabel) then
  8836. begin
  8837. Result := True;
  8838. Exit;
  8839. end;
  8840. hp1 := GetLabelWithSym(OrigLabel);
  8841. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  8842. begin
  8843. case taicpu(hp1).opcode of
  8844. A_RET:
  8845. {
  8846. change
  8847. jmp .L1
  8848. ...
  8849. .L1:
  8850. ret
  8851. into
  8852. ret
  8853. }
  8854. begin
  8855. ConvertJumpToRET(p, hp1);
  8856. result:=true;
  8857. end;
  8858. { Check any kind of direct assignment instruction }
  8859. A_MOV,
  8860. A_MOVD,
  8861. A_MOVQ,
  8862. A_MOVSX,
  8863. {$ifdef x86_64}
  8864. A_MOVSXD,
  8865. {$endif x86_64}
  8866. A_MOVZX,
  8867. A_MOVAPS,
  8868. A_MOVUPS,
  8869. A_MOVSD,
  8870. A_MOVAPD,
  8871. A_MOVUPD,
  8872. A_MOVDQA,
  8873. A_MOVDQU,
  8874. A_VMOVSS,
  8875. A_VMOVAPS,
  8876. A_VMOVUPS,
  8877. A_VMOVSD,
  8878. A_VMOVAPD,
  8879. A_VMOVUPD,
  8880. A_VMOVDQA,
  8881. A_VMOVDQU:
  8882. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  8883. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  8884. begin
  8885. Result := True;
  8886. Exit;
  8887. end;
  8888. else
  8889. ;
  8890. end;
  8891. end;
  8892. end;
  8893. end;
  8894. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  8895. begin
  8896. CanBeCMOV:=assigned(p) and
  8897. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  8898. { we can't use cmov ref,reg because
  8899. ref could be nil and cmov still throws an exception
  8900. if ref=nil but the mov isn't done (FK)
  8901. or ((taicpu(p).oper[0]^.typ = top_ref) and
  8902. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  8903. }
  8904. (taicpu(p).oper[1]^.typ = top_reg) and
  8905. (
  8906. (taicpu(p).oper[0]^.typ = top_reg) or
  8907. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  8908. it is not expected that this can cause a seg. violation }
  8909. (
  8910. (taicpu(p).oper[0]^.typ = top_ref) and
  8911. IsRefSafe(taicpu(p).oper[0]^.ref)
  8912. )
  8913. );
  8914. end;
  8915. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  8916. var
  8917. hp1,hp2: tai;
  8918. {$ifndef i8086}
  8919. hp3,hp4,hpmov2, hp5: tai;
  8920. l : Longint;
  8921. condition : TAsmCond;
  8922. {$endif i8086}
  8923. carryadd_opcode : TAsmOp;
  8924. symbol: TAsmSymbol;
  8925. increg, tmpreg: TRegister;
  8926. begin
  8927. result:=false;
  8928. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  8929. begin
  8930. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8931. if (
  8932. (
  8933. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8934. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8935. (Taicpu(hp1).oper[0]^.val=1)
  8936. ) or
  8937. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8938. ) and
  8939. GetNextInstruction(hp1,hp2) and
  8940. SkipAligns(hp2, hp2) and
  8941. (hp2.typ = ait_label) and
  8942. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8943. { jb @@1 cmc
  8944. inc/dec operand --> adc/sbb operand,0
  8945. @@1:
  8946. ... and ...
  8947. jnb @@1
  8948. inc/dec operand --> adc/sbb operand,0
  8949. @@1: }
  8950. begin
  8951. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8952. begin
  8953. case taicpu(hp1).opcode of
  8954. A_INC,
  8955. A_ADD:
  8956. carryadd_opcode:=A_ADC;
  8957. A_DEC,
  8958. A_SUB:
  8959. carryadd_opcode:=A_SBB;
  8960. else
  8961. InternalError(2021011001);
  8962. end;
  8963. Taicpu(p).clearop(0);
  8964. Taicpu(p).ops:=0;
  8965. Taicpu(p).is_jmp:=false;
  8966. Taicpu(p).opcode:=A_CMC;
  8967. Taicpu(p).condition:=C_NONE;
  8968. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8969. Taicpu(hp1).ops:=2;
  8970. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8971. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8972. else
  8973. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8974. Taicpu(hp1).loadconst(0,0);
  8975. Taicpu(hp1).opcode:=carryadd_opcode;
  8976. result:=true;
  8977. exit;
  8978. end
  8979. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8980. begin
  8981. case taicpu(hp1).opcode of
  8982. A_INC,
  8983. A_ADD:
  8984. carryadd_opcode:=A_ADC;
  8985. A_DEC,
  8986. A_SUB:
  8987. carryadd_opcode:=A_SBB;
  8988. else
  8989. InternalError(2021011002);
  8990. end;
  8991. Taicpu(hp1).ops:=2;
  8992. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8993. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8994. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8995. else
  8996. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8997. Taicpu(hp1).loadconst(0,0);
  8998. Taicpu(hp1).opcode:=carryadd_opcode;
  8999. RemoveCurrentP(p, hp1);
  9000. result:=true;
  9001. exit;
  9002. end
  9003. {
  9004. jcc @@1 setcc tmpreg
  9005. inc/dec/add/sub operand -> (movzx tmpreg)
  9006. @@1: add/sub tmpreg,operand
  9007. While this increases code size slightly, it makes the code much faster if the
  9008. jump is unpredictable
  9009. }
  9010. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9011. begin
  9012. { search for an available register which is volatile }
  9013. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9014. if increg <> NR_NO then
  9015. begin
  9016. { We don't need to check if tmpreg is in hp1 or not, because
  9017. it will be marked as in use at p (if not, this is
  9018. indictive of a compiler bug). }
  9019. TAsmLabel(symbol).decrefs;
  9020. Taicpu(p).clearop(0);
  9021. Taicpu(p).ops:=1;
  9022. Taicpu(p).is_jmp:=false;
  9023. Taicpu(p).opcode:=A_SETcc;
  9024. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9025. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9026. Taicpu(p).loadreg(0,increg);
  9027. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9028. begin
  9029. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9030. R_SUBW:
  9031. begin
  9032. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9033. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9034. end;
  9035. R_SUBD:
  9036. begin
  9037. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9038. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9039. end;
  9040. {$ifdef x86_64}
  9041. R_SUBQ:
  9042. begin
  9043. { MOVZX doesn't have a 64-bit variant, because
  9044. the 32-bit version implicitly zeroes the
  9045. upper 32-bits of the destination register }
  9046. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9047. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9048. setsubreg(tmpreg, R_SUBQ);
  9049. end;
  9050. {$endif x86_64}
  9051. else
  9052. Internalerror(2020030601);
  9053. end;
  9054. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9055. asml.InsertAfter(hp2,p);
  9056. end
  9057. else
  9058. tmpreg := increg;
  9059. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9060. begin
  9061. Taicpu(hp1).ops:=2;
  9062. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9063. end;
  9064. Taicpu(hp1).loadreg(0,tmpreg);
  9065. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9066. Result := True;
  9067. { p is no longer a Jcc instruction, so exit }
  9068. Exit;
  9069. end;
  9070. end;
  9071. end;
  9072. { Detect the following:
  9073. jmp<cond> @Lbl1
  9074. jmp @Lbl2
  9075. ...
  9076. @Lbl1:
  9077. ret
  9078. Change to:
  9079. jmp<inv_cond> @Lbl2
  9080. ret
  9081. }
  9082. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9083. begin
  9084. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9085. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9086. MatchInstruction(hp2,A_RET,[S_NO]) then
  9087. begin
  9088. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9089. { Change label address to that of the unconditional jump }
  9090. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9091. TAsmLabel(symbol).DecRefs;
  9092. taicpu(hp1).opcode := A_RET;
  9093. taicpu(hp1).is_jmp := false;
  9094. taicpu(hp1).ops := taicpu(hp2).ops;
  9095. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9096. case taicpu(hp2).ops of
  9097. 0:
  9098. taicpu(hp1).clearop(0);
  9099. 1:
  9100. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9101. else
  9102. internalerror(2016041302);
  9103. end;
  9104. end;
  9105. {$ifndef i8086}
  9106. end
  9107. {
  9108. convert
  9109. j<c> .L1
  9110. mov 1,reg
  9111. jmp .L2
  9112. .L1
  9113. mov 0,reg
  9114. .L2
  9115. into
  9116. mov 0,reg
  9117. set<not(c)> reg
  9118. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9119. would destroy the flag contents
  9120. }
  9121. else if MatchInstruction(hp1,A_MOV,[]) and
  9122. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9123. {$ifdef i386}
  9124. (
  9125. { Under i386, ESI, EDI, EBP and ESP
  9126. don't have an 8-bit representation }
  9127. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9128. ) and
  9129. {$endif i386}
  9130. (taicpu(hp1).oper[0]^.val=1) and
  9131. GetNextInstruction(hp1,hp2) and
  9132. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9133. GetNextInstruction(hp2,hp3) and
  9134. { skip align }
  9135. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9136. (hp3.typ=ait_label) and
  9137. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9138. (tai_label(hp3).labsym.getrefs=1) and
  9139. GetNextInstruction(hp3,hp4) and
  9140. MatchInstruction(hp4,A_MOV,[]) and
  9141. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9142. (taicpu(hp4).oper[0]^.val=0) and
  9143. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9144. GetNextInstruction(hp4,hp5) and
  9145. (hp5.typ=ait_label) and
  9146. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9147. (tai_label(hp5).labsym.getrefs=1) then
  9148. begin
  9149. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9150. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9151. { remove last label }
  9152. RemoveInstruction(hp5);
  9153. { remove second label }
  9154. RemoveInstruction(hp3);
  9155. { if align is present remove it }
  9156. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9157. RemoveInstruction(hp3);
  9158. { remove jmp }
  9159. RemoveInstruction(hp2);
  9160. if taicpu(hp1).opsize=S_B then
  9161. RemoveInstruction(hp1)
  9162. else
  9163. taicpu(hp1).loadconst(0,0);
  9164. taicpu(hp4).opcode:=A_SETcc;
  9165. taicpu(hp4).opsize:=S_B;
  9166. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9167. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9168. taicpu(hp4).opercnt:=1;
  9169. taicpu(hp4).ops:=1;
  9170. taicpu(hp4).freeop(1);
  9171. RemoveCurrentP(p);
  9172. Result:=true;
  9173. exit;
  9174. end
  9175. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9176. begin
  9177. { check for
  9178. jCC xxx
  9179. <several movs>
  9180. xxx:
  9181. }
  9182. l:=0;
  9183. while assigned(hp1) and
  9184. CanBeCMOV(hp1) and
  9185. { stop on labels }
  9186. not(hp1.typ=ait_label) do
  9187. begin
  9188. inc(l);
  9189. GetNextInstruction(hp1,hp1);
  9190. end;
  9191. if assigned(hp1) then
  9192. begin
  9193. if FindLabel(tasmlabel(symbol),hp1) then
  9194. begin
  9195. if (l<=4) and (l>0) then
  9196. begin
  9197. condition:=inverse_cond(taicpu(p).condition);
  9198. UpdateUsedRegs(tai(p.next));
  9199. GetNextInstruction(p,hp1);
  9200. repeat
  9201. if not Assigned(hp1) then
  9202. InternalError(2018062900);
  9203. taicpu(hp1).opcode:=A_CMOVcc;
  9204. taicpu(hp1).condition:=condition;
  9205. UpdateUsedRegs(tai(hp1.next));
  9206. GetNextInstruction(hp1,hp1);
  9207. until not(CanBeCMOV(hp1));
  9208. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9209. hp2 := hp1;
  9210. repeat
  9211. if not Assigned(hp2) then
  9212. InternalError(2018062910);
  9213. case hp2.typ of
  9214. ait_label:
  9215. { What we expected - break out of the loop (it won't be a dead label at the top of
  9216. a cluster because that was optimised at an earlier stage) }
  9217. Break;
  9218. ait_align:
  9219. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9220. begin
  9221. hp2 := tai(hp2.Next);
  9222. Continue;
  9223. end;
  9224. else
  9225. begin
  9226. { Might be a comment or temporary allocation entry }
  9227. if not (hp2.typ in SkipInstr) then
  9228. InternalError(2018062911);
  9229. hp2 := tai(hp2.Next);
  9230. Continue;
  9231. end;
  9232. end;
  9233. until False;
  9234. { Now we can safely decrement the reference count }
  9235. tasmlabel(symbol).decrefs;
  9236. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9237. { Remove the original jump }
  9238. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9239. UpdateUsedRegs(tai(hp2.next));
  9240. GetNextInstruction(hp2, p); { Instruction after the label }
  9241. { Remove the label if this is its final reference }
  9242. if (tasmlabel(symbol).getrefs=0) then
  9243. StripLabelFast(hp1);
  9244. if Assigned(p) then
  9245. result:=true;
  9246. exit;
  9247. end;
  9248. end
  9249. else
  9250. begin
  9251. { check further for
  9252. jCC xxx
  9253. <several movs 1>
  9254. jmp yyy
  9255. xxx:
  9256. <several movs 2>
  9257. yyy:
  9258. }
  9259. { hp2 points to jmp yyy }
  9260. hp2:=hp1;
  9261. { skip hp1 to xxx (or an align right before it) }
  9262. GetNextInstruction(hp1, hp1);
  9263. if assigned(hp2) and
  9264. assigned(hp1) and
  9265. (l<=3) and
  9266. (hp2.typ=ait_instruction) and
  9267. (taicpu(hp2).is_jmp) and
  9268. (taicpu(hp2).condition=C_None) and
  9269. { real label and jump, no further references to the
  9270. label are allowed }
  9271. (tasmlabel(symbol).getrefs=1) and
  9272. FindLabel(tasmlabel(symbol),hp1) then
  9273. begin
  9274. l:=0;
  9275. { skip hp1 to <several moves 2> }
  9276. if (hp1.typ = ait_align) then
  9277. GetNextInstruction(hp1, hp1);
  9278. GetNextInstruction(hp1, hpmov2);
  9279. hp1 := hpmov2;
  9280. while assigned(hp1) and
  9281. CanBeCMOV(hp1) do
  9282. begin
  9283. inc(l);
  9284. GetNextInstruction(hp1, hp1);
  9285. end;
  9286. { hp1 points to yyy (or an align right before it) }
  9287. hp3 := hp1;
  9288. if assigned(hp1) and
  9289. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9290. begin
  9291. condition:=inverse_cond(taicpu(p).condition);
  9292. UpdateUsedRegs(tai(p.next));
  9293. GetNextInstruction(p,hp1);
  9294. repeat
  9295. taicpu(hp1).opcode:=A_CMOVcc;
  9296. taicpu(hp1).condition:=condition;
  9297. UpdateUsedRegs(tai(hp1.next));
  9298. GetNextInstruction(hp1,hp1);
  9299. until not(assigned(hp1)) or
  9300. not(CanBeCMOV(hp1));
  9301. condition:=inverse_cond(condition);
  9302. if GetLastInstruction(hpmov2,hp1) then
  9303. UpdateUsedRegs(tai(hp1.next));
  9304. hp1 := hpmov2;
  9305. { hp1 is now at <several movs 2> }
  9306. while Assigned(hp1) and CanBeCMOV(hp1) do
  9307. begin
  9308. taicpu(hp1).opcode:=A_CMOVcc;
  9309. taicpu(hp1).condition:=condition;
  9310. UpdateUsedRegs(tai(hp1.next));
  9311. GetNextInstruction(hp1,hp1);
  9312. end;
  9313. hp1 := p;
  9314. { Get first instruction after label }
  9315. UpdateUsedRegs(tai(hp3.next));
  9316. GetNextInstruction(hp3, p);
  9317. if assigned(p) and (hp3.typ = ait_align) then
  9318. GetNextInstruction(p, p);
  9319. { Don't dereference yet, as doing so will cause
  9320. GetNextInstruction to skip the label and
  9321. optional align marker. [Kit] }
  9322. GetNextInstruction(hp2, hp4);
  9323. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9324. { remove jCC }
  9325. RemoveInstruction(hp1);
  9326. { Now we can safely decrement it }
  9327. tasmlabel(symbol).decrefs;
  9328. { Remove label xxx (it will have a ref of zero due to the initial check }
  9329. StripLabelFast(hp4);
  9330. { remove jmp }
  9331. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9332. RemoveInstruction(hp2);
  9333. { As before, now we can safely decrement it }
  9334. tasmlabel(symbol).decrefs;
  9335. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9336. if tasmlabel(symbol).getrefs = 0 then
  9337. StripLabelFast(hp3);
  9338. if Assigned(p) then
  9339. result:=true;
  9340. exit;
  9341. end;
  9342. end;
  9343. end;
  9344. end;
  9345. {$endif i8086}
  9346. end;
  9347. end;
  9348. end;
  9349. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9350. var
  9351. hp1,hp2,hp3: tai;
  9352. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9353. NewSize: TOpSize;
  9354. NewRegSize: TSubRegister;
  9355. Limit: TCgInt;
  9356. SwapOper: POper;
  9357. begin
  9358. result:=false;
  9359. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9360. GetNextInstruction(p,hp1) and
  9361. (hp1.typ = ait_instruction);
  9362. if reg_and_hp1_is_instr and
  9363. (
  9364. (taicpu(hp1).opcode <> A_LEA) or
  9365. { If the LEA instruction can be converted into an arithmetic instruction,
  9366. it may be possible to then fold it. }
  9367. (
  9368. { If the flags register is in use, don't change the instruction
  9369. to an ADD otherwise this will scramble the flags. [Kit] }
  9370. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9371. ConvertLEA(taicpu(hp1))
  9372. )
  9373. ) and
  9374. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9375. GetNextInstruction(hp1,hp2) and
  9376. MatchInstruction(hp2,A_MOV,[]) and
  9377. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9378. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9379. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9380. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9381. {$ifdef i386}
  9382. { not all registers have byte size sub registers on i386 }
  9383. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9384. {$endif i386}
  9385. (((taicpu(hp1).ops=2) and
  9386. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9387. ((taicpu(hp1).ops=1) and
  9388. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9389. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9390. begin
  9391. { change movsX/movzX reg/ref, reg2
  9392. add/sub/or/... reg3/$const, reg2
  9393. mov reg2 reg/ref
  9394. to add/sub/or/... reg3/$const, reg/ref }
  9395. { by example:
  9396. movswl %si,%eax movswl %si,%eax p
  9397. decl %eax addl %edx,%eax hp1
  9398. movw %ax,%si movw %ax,%si hp2
  9399. ->
  9400. movswl %si,%eax movswl %si,%eax p
  9401. decw %eax addw %edx,%eax hp1
  9402. movw %ax,%si movw %ax,%si hp2
  9403. }
  9404. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9405. {
  9406. ->
  9407. movswl %si,%eax movswl %si,%eax p
  9408. decw %si addw %dx,%si hp1
  9409. movw %ax,%si movw %ax,%si hp2
  9410. }
  9411. case taicpu(hp1).ops of
  9412. 1:
  9413. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9414. 2:
  9415. begin
  9416. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9417. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9418. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9419. end;
  9420. else
  9421. internalerror(2008042702);
  9422. end;
  9423. {
  9424. ->
  9425. decw %si addw %dx,%si p
  9426. }
  9427. DebugMsg(SPeepholeOptimization + 'var3',p);
  9428. RemoveCurrentP(p, hp1);
  9429. RemoveInstruction(hp2);
  9430. Result := True;
  9431. Exit;
  9432. end;
  9433. if reg_and_hp1_is_instr and
  9434. (taicpu(hp1).opcode = A_MOV) and
  9435. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9436. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9437. {$ifdef x86_64}
  9438. { check for implicit extension to 64 bit }
  9439. or
  9440. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9441. (taicpu(hp1).opsize=S_Q) and
  9442. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9443. )
  9444. {$endif x86_64}
  9445. )
  9446. then
  9447. begin
  9448. { change
  9449. movx %reg1,%reg2
  9450. mov %reg2,%reg3
  9451. dealloc %reg2
  9452. into
  9453. movx %reg,%reg3
  9454. }
  9455. TransferUsedRegs(TmpUsedRegs);
  9456. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9457. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9458. begin
  9459. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9460. {$ifdef x86_64}
  9461. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9462. (taicpu(hp1).opsize=S_Q) then
  9463. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9464. else
  9465. {$endif x86_64}
  9466. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9467. RemoveInstruction(hp1);
  9468. Result := True;
  9469. Exit;
  9470. end;
  9471. end;
  9472. if reg_and_hp1_is_instr and
  9473. ((taicpu(hp1).opcode=A_MOV) or
  9474. (taicpu(hp1).opcode=A_ADD) or
  9475. (taicpu(hp1).opcode=A_SUB) or
  9476. (taicpu(hp1).opcode=A_CMP) or
  9477. (taicpu(hp1).opcode=A_OR) or
  9478. (taicpu(hp1).opcode=A_XOR) or
  9479. (taicpu(hp1).opcode=A_AND)
  9480. ) and
  9481. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9482. begin
  9483. AndTest := (taicpu(hp1).opcode=A_AND) and
  9484. GetNextInstruction(hp1, hp2) and
  9485. (hp2.typ = ait_instruction) and
  9486. (
  9487. (
  9488. (taicpu(hp2).opcode=A_TEST) and
  9489. (
  9490. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9491. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9492. (
  9493. { If the AND and TEST instructions share a constant, this is also valid }
  9494. (taicpu(hp1).oper[0]^.typ = top_const) and
  9495. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9496. )
  9497. ) and
  9498. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9499. ) or
  9500. (
  9501. (taicpu(hp2).opcode=A_CMP) and
  9502. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9503. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9504. )
  9505. );
  9506. { change
  9507. movx (oper),%reg2
  9508. and $x,%reg2
  9509. test %reg2,%reg2
  9510. dealloc %reg2
  9511. into
  9512. op %reg1,%reg3
  9513. if the second op accesses only the bits stored in reg1
  9514. }
  9515. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9516. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9517. (taicpu(hp1).oper[0]^.typ = top_const) and
  9518. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9519. AndTest then
  9520. begin
  9521. { Check if the AND constant is in range }
  9522. case taicpu(p).opsize of
  9523. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9524. begin
  9525. NewSize := S_B;
  9526. Limit := $FF;
  9527. end;
  9528. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9529. begin
  9530. NewSize := S_W;
  9531. Limit := $FFFF;
  9532. end;
  9533. {$ifdef x86_64}
  9534. S_LQ:
  9535. begin
  9536. NewSize := S_L;
  9537. Limit := $FFFFFFFF;
  9538. end;
  9539. {$endif x86_64}
  9540. else
  9541. InternalError(2021120303);
  9542. end;
  9543. if (
  9544. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9545. { Check for negative operands }
  9546. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9547. ) and
  9548. GetNextInstruction(hp2,hp3) and
  9549. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9550. (taicpu(hp3).condition in [C_E,C_NE]) then
  9551. begin
  9552. TransferUsedRegs(TmpUsedRegs);
  9553. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9554. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9555. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9556. begin
  9557. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9558. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9559. taicpu(hp1).opcode := A_TEST;
  9560. taicpu(hp1).opsize := NewSize;
  9561. RemoveInstruction(hp2);
  9562. RemoveCurrentP(p, hp1);
  9563. Result:=true;
  9564. exit;
  9565. end;
  9566. end;
  9567. end;
  9568. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9569. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9570. (taicpu(hp1).opsize=S_B)) or
  9571. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9572. (taicpu(hp1).opsize=S_W))
  9573. {$ifdef x86_64}
  9574. or ((taicpu(p).opsize=S_LQ) and
  9575. (taicpu(hp1).opsize=S_L))
  9576. {$endif x86_64}
  9577. ) and
  9578. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9579. begin
  9580. { change
  9581. movx %reg1,%reg2
  9582. op %reg2,%reg3
  9583. dealloc %reg2
  9584. into
  9585. op %reg1,%reg3
  9586. if the second op accesses only the bits stored in reg1
  9587. }
  9588. TransferUsedRegs(TmpUsedRegs);
  9589. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9590. if AndTest then
  9591. begin
  9592. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9593. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9594. end
  9595. else
  9596. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9597. if not RegUsed then
  9598. begin
  9599. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9600. if taicpu(p).oper[0]^.typ=top_reg then
  9601. begin
  9602. case taicpu(hp1).opsize of
  9603. S_B:
  9604. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9605. S_W:
  9606. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9607. S_L:
  9608. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9609. else
  9610. Internalerror(2020102301);
  9611. end;
  9612. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9613. end
  9614. else
  9615. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9616. RemoveCurrentP(p);
  9617. if AndTest then
  9618. RemoveInstruction(hp2);
  9619. result:=true;
  9620. exit;
  9621. end;
  9622. end
  9623. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9624. (
  9625. { Bitwise operations only }
  9626. (taicpu(hp1).opcode=A_AND) or
  9627. (taicpu(hp1).opcode=A_TEST) or
  9628. (
  9629. (taicpu(hp1).oper[0]^.typ = top_const) and
  9630. (
  9631. (taicpu(hp1).opcode=A_OR) or
  9632. (taicpu(hp1).opcode=A_XOR)
  9633. )
  9634. )
  9635. ) and
  9636. (
  9637. (taicpu(hp1).oper[0]^.typ = top_const) or
  9638. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9639. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9640. ) then
  9641. begin
  9642. { change
  9643. movx %reg2,%reg2
  9644. op const,%reg2
  9645. into
  9646. op const,%reg2 (smaller version)
  9647. movx %reg2,%reg2
  9648. also change
  9649. movx %reg1,%reg2
  9650. and/test (oper),%reg2
  9651. dealloc %reg2
  9652. into
  9653. and/test (oper),%reg1
  9654. }
  9655. case taicpu(p).opsize of
  9656. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9657. begin
  9658. NewSize := S_B;
  9659. NewRegSize := R_SUBL;
  9660. Limit := $FF;
  9661. end;
  9662. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9663. begin
  9664. NewSize := S_W;
  9665. NewRegSize := R_SUBW;
  9666. Limit := $FFFF;
  9667. end;
  9668. {$ifdef x86_64}
  9669. S_LQ:
  9670. begin
  9671. NewSize := S_L;
  9672. NewRegSize := R_SUBD;
  9673. Limit := $FFFFFFFF;
  9674. end;
  9675. {$endif x86_64}
  9676. else
  9677. Internalerror(2021120302);
  9678. end;
  9679. TransferUsedRegs(TmpUsedRegs);
  9680. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9681. if AndTest then
  9682. begin
  9683. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9684. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9685. end
  9686. else
  9687. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9688. if
  9689. (
  9690. (taicpu(p).opcode = A_MOVZX) and
  9691. (
  9692. (taicpu(hp1).opcode=A_AND) or
  9693. (taicpu(hp1).opcode=A_TEST)
  9694. ) and
  9695. not (
  9696. { If both are references, then the final instruction will have
  9697. both operands as references, which is not allowed }
  9698. (taicpu(p).oper[0]^.typ = top_ref) and
  9699. (taicpu(hp1).oper[0]^.typ = top_ref)
  9700. ) and
  9701. not RegUsed
  9702. ) or
  9703. (
  9704. (
  9705. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9706. not RegUsed
  9707. ) and
  9708. (taicpu(p).oper[0]^.typ = top_reg) and
  9709. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9710. (taicpu(hp1).oper[0]^.typ = top_const) and
  9711. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9712. ) then
  9713. begin
  9714. {$if defined(i386) or defined(i8086)}
  9715. { If the target size is 8-bit, make sure we can actually encode it }
  9716. 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
  9717. Exit;
  9718. {$endif i386 or i8086}
  9719. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9720. taicpu(hp1).opsize := NewSize;
  9721. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9722. if AndTest then
  9723. begin
  9724. RemoveInstruction(hp2);
  9725. if not RegUsed then
  9726. begin
  9727. taicpu(hp1).opcode := A_TEST;
  9728. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  9729. begin
  9730. { Make sure the reference is the second operand }
  9731. SwapOper := taicpu(hp1).oper[0];
  9732. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9733. taicpu(hp1).oper[1] := SwapOper;
  9734. end;
  9735. end;
  9736. end;
  9737. case taicpu(hp1).oper[0]^.typ of
  9738. top_reg:
  9739. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9740. top_const:
  9741. { For the AND/TEST case }
  9742. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9743. else
  9744. ;
  9745. end;
  9746. if RegUsed then
  9747. begin
  9748. AsmL.Remove(p);
  9749. AsmL.InsertAfter(p, hp1);
  9750. p := hp1;
  9751. end
  9752. else
  9753. RemoveCurrentP(p, hp1);
  9754. result:=true;
  9755. exit;
  9756. end;
  9757. end;
  9758. end;
  9759. if reg_and_hp1_is_instr and
  9760. (taicpu(p).oper[0]^.typ = top_reg) and
  9761. (
  9762. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9763. ) and
  9764. (taicpu(hp1).oper[0]^.typ = top_const) and
  9765. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9766. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9767. { Minimum shift value allowed is the bit difference between the sizes }
  9768. (taicpu(hp1).oper[0]^.val >=
  9769. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9770. 8 * (
  9771. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  9772. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9773. )
  9774. ) then
  9775. begin
  9776. { For:
  9777. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  9778. shl/sal ##, %reg1
  9779. Remove the movsx/movzx instruction if the shift overwrites the
  9780. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  9781. }
  9782. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  9783. RemoveCurrentP(p, hp1);
  9784. Result := True;
  9785. Exit;
  9786. end
  9787. else if reg_and_hp1_is_instr and
  9788. (taicpu(p).oper[0]^.typ = top_reg) and
  9789. (
  9790. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  9791. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  9792. ) and
  9793. (taicpu(hp1).oper[0]^.typ = top_const) and
  9794. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9795. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9796. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  9797. (taicpu(hp1).oper[0]^.val <
  9798. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9799. 8 * (
  9800. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9801. )
  9802. ) then
  9803. begin
  9804. { For:
  9805. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  9806. sar ##, %reg1 shr ##, %reg1
  9807. Move the shift to before the movx instruction if the shift value
  9808. is not too large.
  9809. }
  9810. asml.Remove(hp1);
  9811. asml.InsertBefore(hp1, p);
  9812. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9813. case taicpu(p).opsize of
  9814. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  9815. taicpu(hp1).opsize := S_B;
  9816. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  9817. taicpu(hp1).opsize := S_W;
  9818. {$ifdef x86_64}
  9819. S_LQ:
  9820. taicpu(hp1).opsize := S_L;
  9821. {$endif}
  9822. else
  9823. InternalError(2020112401);
  9824. end;
  9825. if (taicpu(hp1).opcode = A_SHR) then
  9826. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  9827. else
  9828. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  9829. Result := True;
  9830. end;
  9831. if reg_and_hp1_is_instr and
  9832. (taicpu(p).oper[0]^.typ = top_reg) and
  9833. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9834. (
  9835. (taicpu(hp1).opcode = taicpu(p).opcode)
  9836. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  9837. {$ifdef x86_64}
  9838. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  9839. {$endif x86_64}
  9840. ) then
  9841. begin
  9842. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  9843. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  9844. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9845. begin
  9846. {
  9847. For example:
  9848. movzbw %al,%ax
  9849. movzwl %ax,%eax
  9850. Compress into:
  9851. movzbl %al,%eax
  9852. }
  9853. RegUsed := False;
  9854. case taicpu(p).opsize of
  9855. S_BW:
  9856. case taicpu(hp1).opsize of
  9857. S_WL:
  9858. begin
  9859. taicpu(p).opsize := S_BL;
  9860. RegUsed := True;
  9861. end;
  9862. {$ifdef x86_64}
  9863. S_WQ:
  9864. begin
  9865. if taicpu(p).opcode = A_MOVZX then
  9866. begin
  9867. taicpu(p).opsize := S_BL;
  9868. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9869. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9870. end
  9871. else
  9872. taicpu(p).opsize := S_BQ;
  9873. RegUsed := True;
  9874. end;
  9875. {$endif x86_64}
  9876. else
  9877. ;
  9878. end;
  9879. {$ifdef x86_64}
  9880. S_BL:
  9881. case taicpu(hp1).opsize of
  9882. S_LQ:
  9883. begin
  9884. if taicpu(p).opcode = A_MOVZX then
  9885. begin
  9886. taicpu(p).opsize := S_BL;
  9887. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9888. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9889. end
  9890. else
  9891. taicpu(p).opsize := S_BQ;
  9892. RegUsed := True;
  9893. end;
  9894. else
  9895. ;
  9896. end;
  9897. S_WL:
  9898. case taicpu(hp1).opsize of
  9899. S_LQ:
  9900. begin
  9901. if taicpu(p).opcode = A_MOVZX then
  9902. begin
  9903. taicpu(p).opsize := S_WL;
  9904. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9905. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9906. end
  9907. else
  9908. taicpu(p).opsize := S_WQ;
  9909. RegUsed := True;
  9910. end;
  9911. else
  9912. ;
  9913. end;
  9914. {$endif x86_64}
  9915. else
  9916. ;
  9917. end;
  9918. if RegUsed then
  9919. begin
  9920. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  9921. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9922. RemoveInstruction(hp1);
  9923. Result := True;
  9924. Exit;
  9925. end;
  9926. end;
  9927. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  9928. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  9929. GetNextInstruction(hp1, hp2) and
  9930. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  9931. (
  9932. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  9933. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  9934. {$ifdef x86_64}
  9935. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  9936. {$endif x86_64}
  9937. ) and
  9938. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  9939. (
  9940. (
  9941. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9942. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9943. ) or
  9944. (
  9945. { Only allow the operands in reverse order for TEST instructions }
  9946. (taicpu(hp2).opcode = A_TEST) and
  9947. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9948. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  9949. )
  9950. ) then
  9951. begin
  9952. {
  9953. For example:
  9954. movzbl %al,%eax
  9955. movzbl (ref),%edx
  9956. andl %edx,%eax
  9957. (%edx deallocated)
  9958. Change to:
  9959. andb (ref),%al
  9960. movzbl %al,%eax
  9961. Rules are:
  9962. - First two instructions have the same opcode and opsize
  9963. - First instruction's operands are the same super-register
  9964. - Second instruction operates on a different register
  9965. - Third instruction is AND, OR, XOR or TEST
  9966. - Third instruction's operands are the destination registers of the first two instructions
  9967. - Third instruction writes to the destination register of the first instruction (except with TEST)
  9968. - Second instruction's destination register is deallocated afterwards
  9969. }
  9970. TransferUsedRegs(TmpUsedRegs);
  9971. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9972. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9973. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  9974. begin
  9975. case taicpu(p).opsize of
  9976. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9977. NewSize := S_B;
  9978. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9979. NewSize := S_W;
  9980. {$ifdef x86_64}
  9981. S_LQ:
  9982. NewSize := S_L;
  9983. {$endif x86_64}
  9984. else
  9985. InternalError(2021120301);
  9986. end;
  9987. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  9988. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  9989. taicpu(hp2).opsize := NewSize;
  9990. RemoveInstruction(hp1);
  9991. { With TEST, it's best to keep the MOVX instruction at the top }
  9992. if (taicpu(hp2).opcode <> A_TEST) then
  9993. begin
  9994. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  9995. asml.Remove(p);
  9996. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  9997. asml.InsertAfter(p, hp2);
  9998. p := hp2;
  9999. end
  10000. else
  10001. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10002. Result := True;
  10003. Exit;
  10004. end;
  10005. end;
  10006. end;
  10007. if taicpu(p).opcode=A_MOVZX then
  10008. begin
  10009. { removes superfluous And's after movzx's }
  10010. if reg_and_hp1_is_instr and
  10011. (taicpu(hp1).opcode = A_AND) and
  10012. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10013. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10014. {$ifdef x86_64}
  10015. { check for implicit extension to 64 bit }
  10016. or
  10017. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10018. (taicpu(hp1).opsize=S_Q) and
  10019. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10020. )
  10021. {$endif x86_64}
  10022. )
  10023. then
  10024. begin
  10025. case taicpu(p).opsize Of
  10026. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10027. if (taicpu(hp1).oper[0]^.val = $ff) then
  10028. begin
  10029. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10030. RemoveInstruction(hp1);
  10031. Result:=true;
  10032. exit;
  10033. end;
  10034. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10035. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10036. begin
  10037. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10038. RemoveInstruction(hp1);
  10039. Result:=true;
  10040. exit;
  10041. end;
  10042. {$ifdef x86_64}
  10043. S_LQ:
  10044. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10045. begin
  10046. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10047. RemoveInstruction(hp1);
  10048. Result:=true;
  10049. exit;
  10050. end;
  10051. {$endif x86_64}
  10052. else
  10053. ;
  10054. end;
  10055. { we cannot get rid of the and, but can we get rid of the movz ?}
  10056. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10057. begin
  10058. case taicpu(p).opsize Of
  10059. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10060. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10061. begin
  10062. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10063. RemoveCurrentP(p,hp1);
  10064. Result:=true;
  10065. exit;
  10066. end;
  10067. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10068. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10069. begin
  10070. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10071. RemoveCurrentP(p,hp1);
  10072. Result:=true;
  10073. exit;
  10074. end;
  10075. {$ifdef x86_64}
  10076. S_LQ:
  10077. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10078. begin
  10079. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10080. RemoveCurrentP(p,hp1);
  10081. Result:=true;
  10082. exit;
  10083. end;
  10084. {$endif x86_64}
  10085. else
  10086. ;
  10087. end;
  10088. end;
  10089. end;
  10090. { changes some movzx constructs to faster synonyms (all examples
  10091. are given with eax/ax, but are also valid for other registers)}
  10092. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10093. begin
  10094. case taicpu(p).opsize of
  10095. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10096. (the machine code is equivalent to movzbl %al,%eax), but the
  10097. code generator still generates that assembler instruction and
  10098. it is silently converted. This should probably be checked.
  10099. [Kit] }
  10100. S_BW:
  10101. begin
  10102. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10103. (
  10104. not IsMOVZXAcceptable
  10105. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10106. or (
  10107. (cs_opt_size in current_settings.optimizerswitches) and
  10108. (taicpu(p).oper[1]^.reg = NR_AX)
  10109. )
  10110. ) then
  10111. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10112. begin
  10113. DebugMsg(SPeepholeOptimization + 'var7',p);
  10114. taicpu(p).opcode := A_AND;
  10115. taicpu(p).changeopsize(S_W);
  10116. taicpu(p).loadConst(0,$ff);
  10117. Result := True;
  10118. end
  10119. else if not IsMOVZXAcceptable and
  10120. GetNextInstruction(p, hp1) and
  10121. (tai(hp1).typ = ait_instruction) and
  10122. (taicpu(hp1).opcode = A_AND) and
  10123. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10124. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10125. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10126. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10127. begin
  10128. DebugMsg(SPeepholeOptimization + 'var8',p);
  10129. taicpu(p).opcode := A_MOV;
  10130. taicpu(p).changeopsize(S_W);
  10131. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10132. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10133. Result := True;
  10134. end;
  10135. end;
  10136. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10137. S_BL:
  10138. begin
  10139. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10140. (
  10141. not IsMOVZXAcceptable
  10142. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10143. or (
  10144. (cs_opt_size in current_settings.optimizerswitches) and
  10145. (taicpu(p).oper[1]^.reg = NR_EAX)
  10146. )
  10147. ) then
  10148. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10149. begin
  10150. DebugMsg(SPeepholeOptimization + 'var9',p);
  10151. taicpu(p).opcode := A_AND;
  10152. taicpu(p).changeopsize(S_L);
  10153. taicpu(p).loadConst(0,$ff);
  10154. Result := True;
  10155. end
  10156. else if not IsMOVZXAcceptable and
  10157. GetNextInstruction(p, hp1) and
  10158. (tai(hp1).typ = ait_instruction) and
  10159. (taicpu(hp1).opcode = A_AND) and
  10160. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10161. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10162. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10163. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10164. begin
  10165. DebugMsg(SPeepholeOptimization + 'var10',p);
  10166. taicpu(p).opcode := A_MOV;
  10167. taicpu(p).changeopsize(S_L);
  10168. { do not use R_SUBWHOLE
  10169. as movl %rdx,%eax
  10170. is invalid in assembler PM }
  10171. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10172. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10173. Result := True;
  10174. end;
  10175. end;
  10176. {$endif i8086}
  10177. S_WL:
  10178. if not IsMOVZXAcceptable then
  10179. begin
  10180. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10181. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10182. begin
  10183. DebugMsg(SPeepholeOptimization + 'var11',p);
  10184. taicpu(p).opcode := A_AND;
  10185. taicpu(p).changeopsize(S_L);
  10186. taicpu(p).loadConst(0,$ffff);
  10187. Result := True;
  10188. end
  10189. else if GetNextInstruction(p, hp1) and
  10190. (tai(hp1).typ = ait_instruction) and
  10191. (taicpu(hp1).opcode = A_AND) and
  10192. (taicpu(hp1).oper[0]^.typ = top_const) and
  10193. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10194. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10195. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10196. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10197. begin
  10198. DebugMsg(SPeepholeOptimization + 'var12',p);
  10199. taicpu(p).opcode := A_MOV;
  10200. taicpu(p).changeopsize(S_L);
  10201. { do not use R_SUBWHOLE
  10202. as movl %rdx,%eax
  10203. is invalid in assembler PM }
  10204. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10205. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10206. Result := True;
  10207. end;
  10208. end;
  10209. else
  10210. InternalError(2017050705);
  10211. end;
  10212. end
  10213. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10214. begin
  10215. if GetNextInstruction(p, hp1) and
  10216. (tai(hp1).typ = ait_instruction) and
  10217. (taicpu(hp1).opcode = A_AND) and
  10218. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10219. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10220. begin
  10221. //taicpu(p).opcode := A_MOV;
  10222. case taicpu(p).opsize Of
  10223. S_BL:
  10224. begin
  10225. DebugMsg(SPeepholeOptimization + 'var13',p);
  10226. taicpu(hp1).changeopsize(S_L);
  10227. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10228. end;
  10229. S_WL:
  10230. begin
  10231. DebugMsg(SPeepholeOptimization + 'var14',p);
  10232. taicpu(hp1).changeopsize(S_L);
  10233. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10234. end;
  10235. S_BW:
  10236. begin
  10237. DebugMsg(SPeepholeOptimization + 'var15',p);
  10238. taicpu(hp1).changeopsize(S_W);
  10239. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10240. end;
  10241. else
  10242. Internalerror(2017050704)
  10243. end;
  10244. Result := True;
  10245. end;
  10246. end;
  10247. end;
  10248. end;
  10249. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10250. var
  10251. hp1, hp2 : tai;
  10252. MaskLength : Cardinal;
  10253. MaskedBits : TCgInt;
  10254. ActiveReg : TRegister;
  10255. begin
  10256. Result:=false;
  10257. { There are no optimisations for reference targets }
  10258. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10259. Exit;
  10260. while GetNextInstruction(p, hp1) and
  10261. (hp1.typ = ait_instruction) do
  10262. begin
  10263. if (taicpu(p).oper[0]^.typ = top_const) then
  10264. begin
  10265. case taicpu(hp1).opcode of
  10266. A_AND:
  10267. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10268. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10269. { the second register must contain the first one, so compare their subreg types }
  10270. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10271. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10272. { change
  10273. and const1, reg
  10274. and const2, reg
  10275. to
  10276. and (const1 and const2), reg
  10277. }
  10278. begin
  10279. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10280. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10281. RemoveCurrentP(p, hp1);
  10282. Result:=true;
  10283. exit;
  10284. end;
  10285. A_CMP:
  10286. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10287. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10288. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10289. { Just check that the condition on the next instruction is compatible }
  10290. GetNextInstruction(hp1, hp2) and
  10291. (hp2.typ = ait_instruction) and
  10292. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10293. then
  10294. { change
  10295. and 2^n, reg
  10296. cmp 2^n, reg
  10297. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10298. to
  10299. and 2^n, reg
  10300. test reg, reg
  10301. j(~c) / set(~c) / cmov(~c)
  10302. }
  10303. begin
  10304. { Keep TEST instruction in, rather than remove it, because
  10305. it may trigger other optimisations such as MovAndTest2Test }
  10306. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10307. taicpu(hp1).opcode := A_TEST;
  10308. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10309. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10310. Result := True;
  10311. Exit;
  10312. end;
  10313. A_MOVZX:
  10314. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10315. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10316. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10317. (
  10318. (
  10319. (taicpu(p).opsize=S_W) and
  10320. (taicpu(hp1).opsize=S_BW)
  10321. ) or
  10322. (
  10323. (taicpu(p).opsize=S_L) and
  10324. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10325. )
  10326. {$ifdef x86_64}
  10327. or
  10328. (
  10329. (taicpu(p).opsize=S_Q) and
  10330. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10331. )
  10332. {$endif x86_64}
  10333. ) then
  10334. begin
  10335. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10336. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10337. ) or
  10338. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10339. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10340. then
  10341. begin
  10342. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10343. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10344. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10345. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10346. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10347. }
  10348. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10349. RemoveInstruction(hp1);
  10350. { See if there are other optimisations possible }
  10351. Continue;
  10352. end;
  10353. end;
  10354. A_SHL:
  10355. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10356. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10357. begin
  10358. {$ifopt R+}
  10359. {$define RANGE_WAS_ON}
  10360. {$R-}
  10361. {$endif}
  10362. { get length of potential and mask }
  10363. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10364. { really a mask? }
  10365. {$ifdef RANGE_WAS_ON}
  10366. {$R+}
  10367. {$endif}
  10368. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10369. { unmasked part shifted out? }
  10370. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10371. begin
  10372. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10373. RemoveCurrentP(p, hp1);
  10374. Result:=true;
  10375. exit;
  10376. end;
  10377. end;
  10378. A_SHR:
  10379. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10380. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10381. (taicpu(hp1).oper[0]^.val <= 63) then
  10382. begin
  10383. { Does SHR combined with the AND cover all the bits?
  10384. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10385. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10386. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10387. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10388. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10389. begin
  10390. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10391. RemoveCurrentP(p, hp1);
  10392. Result := True;
  10393. Exit;
  10394. end;
  10395. end;
  10396. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10397. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10398. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10399. begin
  10400. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10401. (
  10402. (
  10403. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10404. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10405. ) or (
  10406. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10407. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10408. {$ifdef x86_64}
  10409. ) or (
  10410. (taicpu(hp1).opsize = S_LQ) and
  10411. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10412. {$endif x86_64}
  10413. )
  10414. ) then
  10415. begin
  10416. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10417. begin
  10418. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10419. RemoveInstruction(hp1);
  10420. { See if there are other optimisations possible }
  10421. Continue;
  10422. end;
  10423. { The super-registers are the same though.
  10424. Note that this change by itself doesn't improve
  10425. code speed, but it opens up other optimisations. }
  10426. {$ifdef x86_64}
  10427. { Convert 64-bit register to 32-bit }
  10428. case taicpu(hp1).opsize of
  10429. S_BQ:
  10430. begin
  10431. taicpu(hp1).opsize := S_BL;
  10432. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10433. end;
  10434. S_WQ:
  10435. begin
  10436. taicpu(hp1).opsize := S_WL;
  10437. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10438. end
  10439. else
  10440. ;
  10441. end;
  10442. {$endif x86_64}
  10443. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10444. taicpu(hp1).opcode := A_MOVZX;
  10445. { See if there are other optimisations possible }
  10446. Continue;
  10447. end;
  10448. end;
  10449. else
  10450. ;
  10451. end;
  10452. end
  10453. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10454. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10455. begin
  10456. {$ifdef x86_64}
  10457. if (taicpu(p).opsize = S_Q) then
  10458. begin
  10459. { Never necessary }
  10460. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10461. RemoveCurrentP(p, hp1);
  10462. Result := True;
  10463. Exit;
  10464. end;
  10465. {$endif x86_64}
  10466. { Forward check to determine necessity of and %reg,%reg }
  10467. TransferUsedRegs(TmpUsedRegs);
  10468. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10469. { Saves on a bunch of dereferences }
  10470. ActiveReg := taicpu(p).oper[1]^.reg;
  10471. case taicpu(hp1).opcode of
  10472. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10473. if (
  10474. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10475. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10476. ) and
  10477. (
  10478. (taicpu(hp1).opcode <> A_MOV) or
  10479. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10480. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10481. ) and
  10482. not (
  10483. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10484. (taicpu(hp1).opcode = A_MOV) and
  10485. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10486. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10487. ) and
  10488. (
  10489. (
  10490. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10491. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10492. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10493. ) or
  10494. (
  10495. {$ifdef x86_64}
  10496. (
  10497. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10498. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10499. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10500. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10501. ) and
  10502. {$endif x86_64}
  10503. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10504. )
  10505. ) then
  10506. begin
  10507. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10508. RemoveCurrentP(p, hp1);
  10509. Result := True;
  10510. Exit;
  10511. end;
  10512. A_ADD,
  10513. A_AND,
  10514. A_BSF,
  10515. A_BSR,
  10516. A_BTC,
  10517. A_BTR,
  10518. A_BTS,
  10519. A_OR,
  10520. A_SUB,
  10521. A_XOR:
  10522. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10523. if (
  10524. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10525. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10526. ) and
  10527. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10528. begin
  10529. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10530. RemoveCurrentP(p, hp1);
  10531. Result := True;
  10532. Exit;
  10533. end;
  10534. A_CMP,
  10535. A_TEST:
  10536. if (
  10537. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10538. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10539. ) and
  10540. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10541. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10542. begin
  10543. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10544. RemoveCurrentP(p, hp1);
  10545. Result := True;
  10546. Exit;
  10547. end;
  10548. A_BSWAP,
  10549. A_NEG,
  10550. A_NOT:
  10551. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10552. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10553. begin
  10554. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10555. RemoveCurrentP(p, hp1);
  10556. Result := True;
  10557. Exit;
  10558. end;
  10559. else
  10560. ;
  10561. end;
  10562. end;
  10563. if (taicpu(hp1).is_jmp) and
  10564. (taicpu(hp1).opcode<>A_JMP) and
  10565. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10566. begin
  10567. { change
  10568. and x, reg
  10569. jxx
  10570. to
  10571. test x, reg
  10572. jxx
  10573. if reg is deallocated before the
  10574. jump, but only if it's a conditional jump (PFV)
  10575. }
  10576. taicpu(p).opcode := A_TEST;
  10577. Exit;
  10578. end;
  10579. Break;
  10580. end;
  10581. { Lone AND tests }
  10582. if (taicpu(p).oper[0]^.typ = top_const) then
  10583. begin
  10584. {
  10585. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10586. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10587. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10588. }
  10589. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10590. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10591. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10592. begin
  10593. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10594. if taicpu(p).opsize = S_L then
  10595. begin
  10596. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10597. Result := True;
  10598. end;
  10599. end;
  10600. end;
  10601. { Backward check to determine necessity of and %reg,%reg }
  10602. if (taicpu(p).oper[0]^.typ = top_reg) and
  10603. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10604. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10605. GetLastInstruction(p, hp2) and
  10606. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10607. { Check size of adjacent instruction to determine if the AND is
  10608. effectively a null operation }
  10609. (
  10610. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10611. { Note: Don't include S_Q }
  10612. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10613. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10614. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10615. ) then
  10616. begin
  10617. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10618. { If GetNextInstruction returned False, hp1 will be nil }
  10619. RemoveCurrentP(p, hp1);
  10620. Result := True;
  10621. Exit;
  10622. end;
  10623. end;
  10624. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10625. var
  10626. hp1: tai; NewRef: TReference;
  10627. { This entire nested function is used in an if-statement below, but we
  10628. want to avoid all the used reg transfers and GetNextInstruction calls
  10629. until we really have to check }
  10630. function MemRegisterNotUsedLater: Boolean; inline;
  10631. var
  10632. hp2: tai;
  10633. begin
  10634. TransferUsedRegs(TmpUsedRegs);
  10635. hp2 := p;
  10636. repeat
  10637. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10638. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10639. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10640. end;
  10641. begin
  10642. Result := False;
  10643. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10644. Exit;
  10645. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10646. begin
  10647. { Change:
  10648. add %reg2,%reg1
  10649. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10650. To:
  10651. mov/s/z #(%reg1,%reg2),%reg1
  10652. }
  10653. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10654. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10655. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10656. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10657. (
  10658. (
  10659. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10660. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10661. { r/esp cannot be an index }
  10662. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10663. ) or (
  10664. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10665. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10666. )
  10667. ) and (
  10668. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10669. (
  10670. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10671. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10672. MemRegisterNotUsedLater
  10673. )
  10674. ) then
  10675. begin
  10676. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10677. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10678. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10679. RemoveCurrentp(p, hp1);
  10680. Result := True;
  10681. Exit;
  10682. end;
  10683. { Change:
  10684. addl/q $x,%reg1
  10685. movl/q %reg1,%reg2
  10686. To:
  10687. leal/q $x(%reg1),%reg2
  10688. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10689. Breaks the dependency chain.
  10690. }
  10691. if MatchOpType(taicpu(p),top_const,top_reg) and
  10692. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10693. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10694. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10695. (
  10696. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10697. not (cs_opt_size in current_settings.optimizerswitches) or
  10698. (
  10699. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10700. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10701. )
  10702. ) then
  10703. begin
  10704. { Change the MOV instruction to a LEA instruction, and update the
  10705. first operand }
  10706. reference_reset(NewRef, 1, []);
  10707. NewRef.base := taicpu(p).oper[1]^.reg;
  10708. NewRef.scalefactor := 1;
  10709. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10710. taicpu(hp1).opcode := A_LEA;
  10711. taicpu(hp1).loadref(0, NewRef);
  10712. TransferUsedRegs(TmpUsedRegs);
  10713. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10714. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10715. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10716. begin
  10717. { Move what is now the LEA instruction to before the SUB instruction }
  10718. Asml.Remove(hp1);
  10719. Asml.InsertBefore(hp1, p);
  10720. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10721. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10722. p := hp1;
  10723. end
  10724. else
  10725. begin
  10726. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10727. RemoveCurrentP(p, hp1);
  10728. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10729. end;
  10730. Result := True;
  10731. end;
  10732. end;
  10733. end;
  10734. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10735. var
  10736. SubReg: TSubRegister;
  10737. begin
  10738. Result:=false;
  10739. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10740. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10741. with taicpu(p).oper[0]^.ref^ do
  10742. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10743. begin
  10744. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10745. begin
  10746. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10747. taicpu(p).opcode := A_ADD;
  10748. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10749. Result := True;
  10750. end
  10751. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10752. begin
  10753. if (base <> NR_NO) then
  10754. begin
  10755. if (scalefactor <= 1) then
  10756. begin
  10757. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10758. taicpu(p).opcode := A_ADD;
  10759. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10760. Result := True;
  10761. end;
  10762. end
  10763. else
  10764. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  10765. if (scalefactor in [2, 4, 8]) then
  10766. begin
  10767. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  10768. taicpu(p).loadconst(0, BsrByte(scalefactor));
  10769. taicpu(p).opcode := A_SHL;
  10770. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  10771. Result := True;
  10772. end;
  10773. end;
  10774. end;
  10775. end;
  10776. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  10777. var
  10778. hp1: tai; NewRef: TReference;
  10779. begin
  10780. { Change:
  10781. subl/q $x,%reg1
  10782. movl/q %reg1,%reg2
  10783. To:
  10784. leal/q $-x(%reg1),%reg2
  10785. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10786. Breaks the dependency chain and potentially permits the removal of
  10787. a CMP instruction if one follows.
  10788. }
  10789. Result := False;
  10790. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  10791. MatchOpType(taicpu(p),top_const,top_reg) and
  10792. GetNextInstruction(p, hp1) and
  10793. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10794. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10795. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10796. (
  10797. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  10798. not (cs_opt_size in current_settings.optimizerswitches) or
  10799. (
  10800. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10801. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10802. )
  10803. ) then
  10804. begin
  10805. { Change the MOV instruction to a LEA instruction, and update the
  10806. first operand }
  10807. reference_reset(NewRef, 1, []);
  10808. NewRef.base := taicpu(p).oper[1]^.reg;
  10809. NewRef.scalefactor := 1;
  10810. NewRef.offset := -taicpu(p).oper[0]^.val;
  10811. taicpu(hp1).opcode := A_LEA;
  10812. taicpu(hp1).loadref(0, NewRef);
  10813. TransferUsedRegs(TmpUsedRegs);
  10814. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10815. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10816. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10817. begin
  10818. { Move what is now the LEA instruction to before the SUB instruction }
  10819. Asml.Remove(hp1);
  10820. Asml.InsertBefore(hp1, p);
  10821. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10822. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  10823. p := hp1;
  10824. end
  10825. else
  10826. begin
  10827. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10828. RemoveCurrentP(p, hp1);
  10829. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  10830. end;
  10831. Result := True;
  10832. end;
  10833. end;
  10834. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  10835. begin
  10836. { we can skip all instructions not messing with the stack pointer }
  10837. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  10838. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  10839. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  10840. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  10841. ({(taicpu(hp1).ops=0) or }
  10842. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  10843. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  10844. ) and }
  10845. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  10846. )
  10847. ) do
  10848. GetNextInstruction(hp1,hp1);
  10849. Result:=assigned(hp1);
  10850. end;
  10851. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  10852. var
  10853. hp1, hp2, hp3, hp4, hp5: tai;
  10854. begin
  10855. Result:=false;
  10856. hp5:=nil;
  10857. { replace
  10858. leal(q) x(<stackpointer>),<stackpointer>
  10859. call procname
  10860. leal(q) -x(<stackpointer>),<stackpointer>
  10861. ret
  10862. by
  10863. jmp procname
  10864. but do it only on level 4 because it destroys stack back traces
  10865. }
  10866. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10867. MatchOpType(taicpu(p),top_ref,top_reg) and
  10868. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10869. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  10870. { the -8 or -24 are not required, but bail out early if possible,
  10871. higher values are unlikely }
  10872. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  10873. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  10874. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  10875. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  10876. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  10877. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10878. GetNextInstruction(p, hp1) and
  10879. { Take a copy of hp1 }
  10880. SetAndTest(hp1, hp4) and
  10881. { trick to skip label }
  10882. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10883. SkipSimpleInstructions(hp1) and
  10884. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10885. GetNextInstruction(hp1, hp2) and
  10886. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  10887. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  10888. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  10889. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10890. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  10891. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  10892. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  10893. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  10894. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10895. GetNextInstruction(hp2, hp3) and
  10896. { trick to skip label }
  10897. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10898. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10899. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10900. SetAndTest(hp3,hp5) and
  10901. GetNextInstruction(hp3,hp3) and
  10902. MatchInstruction(hp3,A_RET,[S_NO])
  10903. )
  10904. ) and
  10905. (taicpu(hp3).ops=0) then
  10906. begin
  10907. taicpu(hp1).opcode := A_JMP;
  10908. taicpu(hp1).is_jmp := true;
  10909. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  10910. RemoveCurrentP(p, hp4);
  10911. RemoveInstruction(hp2);
  10912. RemoveInstruction(hp3);
  10913. if Assigned(hp5) then
  10914. begin
  10915. AsmL.Remove(hp5);
  10916. ASmL.InsertBefore(hp5,hp1)
  10917. end;
  10918. Result:=true;
  10919. end;
  10920. end;
  10921. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  10922. {$ifdef x86_64}
  10923. var
  10924. hp1, hp2, hp3, hp4, hp5: tai;
  10925. {$endif x86_64}
  10926. begin
  10927. Result:=false;
  10928. {$ifdef x86_64}
  10929. hp5:=nil;
  10930. { replace
  10931. push %rax
  10932. call procname
  10933. pop %rcx
  10934. ret
  10935. by
  10936. jmp procname
  10937. but do it only on level 4 because it destroys stack back traces
  10938. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  10939. for all supported calling conventions
  10940. }
  10941. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10942. MatchOpType(taicpu(p),top_reg) and
  10943. (taicpu(p).oper[0]^.reg=NR_RAX) and
  10944. GetNextInstruction(p, hp1) and
  10945. { Take a copy of hp1 }
  10946. SetAndTest(hp1, hp4) and
  10947. { trick to skip label }
  10948. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10949. SkipSimpleInstructions(hp1) and
  10950. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10951. GetNextInstruction(hp1, hp2) and
  10952. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  10953. MatchOpType(taicpu(hp2),top_reg) and
  10954. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  10955. GetNextInstruction(hp2, hp3) and
  10956. { trick to skip label }
  10957. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10958. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10959. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10960. SetAndTest(hp3,hp5) and
  10961. GetNextInstruction(hp3,hp3) and
  10962. MatchInstruction(hp3,A_RET,[S_NO])
  10963. )
  10964. ) and
  10965. (taicpu(hp3).ops=0) then
  10966. begin
  10967. taicpu(hp1).opcode := A_JMP;
  10968. taicpu(hp1).is_jmp := true;
  10969. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  10970. RemoveCurrentP(p, hp4);
  10971. RemoveInstruction(hp2);
  10972. RemoveInstruction(hp3);
  10973. if Assigned(hp5) then
  10974. begin
  10975. AsmL.Remove(hp5);
  10976. ASmL.InsertBefore(hp5,hp1)
  10977. end;
  10978. Result:=true;
  10979. end;
  10980. {$endif x86_64}
  10981. end;
  10982. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  10983. var
  10984. Value, RegName: string;
  10985. begin
  10986. Result:=false;
  10987. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  10988. begin
  10989. case taicpu(p).oper[0]^.val of
  10990. 0:
  10991. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  10992. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10993. begin
  10994. { change "mov $0,%reg" into "xor %reg,%reg" }
  10995. taicpu(p).opcode := A_XOR;
  10996. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  10997. Result := True;
  10998. {$ifdef x86_64}
  10999. end
  11000. else if (taicpu(p).opsize = S_Q) then
  11001. begin
  11002. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11003. { The actual optimization }
  11004. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11005. taicpu(p).changeopsize(S_L);
  11006. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11007. Result := True;
  11008. end;
  11009. $1..$FFFFFFFF:
  11010. begin
  11011. { Code size reduction by J. Gareth "Kit" Moreton }
  11012. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11013. case taicpu(p).opsize of
  11014. S_Q:
  11015. begin
  11016. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11017. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11018. { The actual optimization }
  11019. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11020. taicpu(p).changeopsize(S_L);
  11021. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11022. Result := True;
  11023. end;
  11024. else
  11025. { Do nothing };
  11026. end;
  11027. {$endif x86_64}
  11028. end;
  11029. -1:
  11030. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11031. if (cs_opt_size in current_settings.optimizerswitches) and
  11032. (taicpu(p).opsize <> S_B) and
  11033. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11034. begin
  11035. { change "mov $-1,%reg" into "or $-1,%reg" }
  11036. { NOTES:
  11037. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11038. - This operation creates a false dependency on the register, so only do it when optimising for size
  11039. - 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
  11040. }
  11041. taicpu(p).opcode := A_OR;
  11042. Result := True;
  11043. end;
  11044. else
  11045. { Do nothing };
  11046. end;
  11047. end;
  11048. end;
  11049. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11050. var
  11051. hp1: tai;
  11052. begin
  11053. { Detect:
  11054. andw x, %ax (0 <= x < $8000)
  11055. ...
  11056. movzwl %ax,%eax
  11057. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11058. }
  11059. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11060. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11061. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11062. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11063. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11064. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11065. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11066. begin
  11067. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11068. taicpu(hp1).opcode := A_CWDE;
  11069. taicpu(hp1).clearop(0);
  11070. taicpu(hp1).clearop(1);
  11071. taicpu(hp1).ops := 0;
  11072. { A change was made, but not with p, so move forward 1 }
  11073. p := tai(p.Next);
  11074. Result := True;
  11075. end;
  11076. end;
  11077. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11078. begin
  11079. Result := False;
  11080. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11081. Exit;
  11082. { Convert:
  11083. movswl %ax,%eax -> cwtl
  11084. movslq %eax,%rax -> cdqe
  11085. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11086. refer to the same opcode and depends only on the assembler's
  11087. current operand-size attribute. [Kit]
  11088. }
  11089. with taicpu(p) do
  11090. case opsize of
  11091. S_WL:
  11092. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11093. begin
  11094. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11095. opcode := A_CWDE;
  11096. clearop(0);
  11097. clearop(1);
  11098. ops := 0;
  11099. Result := True;
  11100. end;
  11101. {$ifdef x86_64}
  11102. S_LQ:
  11103. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11104. begin
  11105. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11106. opcode := A_CDQE;
  11107. clearop(0);
  11108. clearop(1);
  11109. ops := 0;
  11110. Result := True;
  11111. end;
  11112. {$endif x86_64}
  11113. else
  11114. ;
  11115. end;
  11116. end;
  11117. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11118. var
  11119. hp1: tai;
  11120. begin
  11121. { Detect:
  11122. shr x, %ax (x > 0)
  11123. ...
  11124. movzwl %ax,%eax
  11125. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11126. }
  11127. Result := False;
  11128. if MatchOpType(taicpu(p), top_const, top_reg) and
  11129. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11130. (taicpu(p).oper[0]^.val > 0) and
  11131. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11132. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11133. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11134. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11135. begin
  11136. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11137. taicpu(hp1).opcode := A_CWDE;
  11138. taicpu(hp1).clearop(0);
  11139. taicpu(hp1).clearop(1);
  11140. taicpu(hp1).ops := 0;
  11141. { A change was made, but not with p, so move forward 1 }
  11142. p := tai(p.Next);
  11143. Result := True;
  11144. end;
  11145. end;
  11146. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11147. var
  11148. hp1, hp2: tai;
  11149. Opposite, SecondOpposite: TAsmOp;
  11150. NewCond: TAsmCond;
  11151. begin
  11152. Result := False;
  11153. { Change:
  11154. add/sub 128,(dest)
  11155. To:
  11156. sub/add -128,(dest)
  11157. This generaally takes fewer bytes to encode because -128 can be stored
  11158. in a signed byte, whereas +128 cannot.
  11159. }
  11160. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11161. begin
  11162. if taicpu(p).opcode = A_ADD then
  11163. Opposite := A_SUB
  11164. else
  11165. Opposite := A_ADD;
  11166. { Be careful if the flags are in use, because the CF flag inverts
  11167. when changing from ADD to SUB and vice versa }
  11168. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11169. GetNextInstruction(p, hp1) then
  11170. begin
  11171. TransferUsedRegs(TmpUsedRegs);
  11172. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11173. hp2 := hp1;
  11174. { Scan ahead to check if everything's safe }
  11175. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11176. begin
  11177. if (hp1.typ <> ait_instruction) then
  11178. { Probably unsafe since the flags are still in use }
  11179. Exit;
  11180. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11181. { Stop searching at an unconditional jump }
  11182. Break;
  11183. if not
  11184. (
  11185. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11186. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11187. ) and
  11188. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11189. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11190. Exit;
  11191. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11192. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11193. { Move to the next instruction }
  11194. GetNextInstruction(hp1, hp1);
  11195. end;
  11196. while Assigned(hp2) and (hp2 <> hp1) do
  11197. begin
  11198. NewCond := C_None;
  11199. case taicpu(hp2).condition of
  11200. C_A, C_NBE:
  11201. NewCond := C_BE;
  11202. C_B, C_C, C_NAE:
  11203. NewCond := C_AE;
  11204. C_AE, C_NB, C_NC:
  11205. NewCond := C_B;
  11206. C_BE, C_NA:
  11207. NewCond := C_A;
  11208. else
  11209. { No change needed };
  11210. end;
  11211. if NewCond <> C_None then
  11212. begin
  11213. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11214. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11215. taicpu(hp2).condition := NewCond;
  11216. end
  11217. else
  11218. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11219. begin
  11220. { Because of the flipping of the carry bit, to ensure
  11221. the operation remains equivalent, ADC becomes SBB
  11222. and vice versa, and the constant is not-inverted.
  11223. If multiple ADCs or SBBs appear in a row, each one
  11224. changed causes the carry bit to invert, so they all
  11225. need to be flipped }
  11226. if taicpu(hp2).opcode = A_ADC then
  11227. SecondOpposite := A_SBB
  11228. else
  11229. SecondOpposite := A_ADC;
  11230. if taicpu(hp2).oper[0]^.typ <> top_const then
  11231. { Should have broken out of this optimisation already }
  11232. InternalError(2021112901);
  11233. 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]^) + ' -> ' +
  11234. 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);
  11235. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11236. taicpu(hp2).opcode := SecondOpposite;
  11237. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11238. end;
  11239. { Move to the next instruction }
  11240. GetNextInstruction(hp2, hp2);
  11241. end;
  11242. if (hp2 <> hp1) then
  11243. InternalError(2021111501);
  11244. end;
  11245. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11246. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11247. taicpu(p).opcode := Opposite;
  11248. taicpu(p).oper[0]^.val := -128;
  11249. { No further optimisations can be made on this instruction, so move
  11250. onto the next one to save time }
  11251. p := tai(p.Next);
  11252. UpdateUsedRegs(p);
  11253. Result := True;
  11254. Exit;
  11255. end;
  11256. { Detect:
  11257. add/sub %reg2,(dest)
  11258. add/sub x, (dest)
  11259. (dest can be a register or a reference)
  11260. Swap the instructions to minimise a pipeline stall. This reverses the
  11261. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11262. optimisations could be made.
  11263. }
  11264. if (taicpu(p).oper[0]^.typ = top_reg) and
  11265. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11266. (
  11267. (
  11268. (taicpu(p).oper[1]^.typ = top_reg) and
  11269. { We can try searching further ahead if we're writing to a register }
  11270. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11271. ) or
  11272. (
  11273. (taicpu(p).oper[1]^.typ = top_ref) and
  11274. GetNextInstruction(p, hp1)
  11275. )
  11276. ) and
  11277. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11278. (taicpu(hp1).oper[0]^.typ = top_const) and
  11279. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11280. begin
  11281. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11282. TransferUsedRegs(TmpUsedRegs);
  11283. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11284. hp2 := p;
  11285. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11286. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11287. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11288. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11289. begin
  11290. asml.remove(hp1);
  11291. asml.InsertBefore(hp1, p);
  11292. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11293. Result := True;
  11294. end;
  11295. end;
  11296. end;
  11297. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11298. begin
  11299. Result:=false;
  11300. { change "cmp $0, %reg" to "test %reg, %reg" }
  11301. if MatchOpType(taicpu(p),top_const,top_reg) and
  11302. (taicpu(p).oper[0]^.val = 0) then
  11303. begin
  11304. taicpu(p).opcode := A_TEST;
  11305. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11306. Result:=true;
  11307. end;
  11308. end;
  11309. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11310. var
  11311. IsTestConstX : Boolean;
  11312. hp1,hp2 : tai;
  11313. begin
  11314. Result:=false;
  11315. { removes the line marked with (x) from the sequence
  11316. and/or/xor/add/sub/... $x, %y
  11317. test/or %y, %y | test $-1, %y (x)
  11318. j(n)z _Label
  11319. as the first instruction already adjusts the ZF
  11320. %y operand may also be a reference }
  11321. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11322. MatchOperand(taicpu(p).oper[0]^,-1);
  11323. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11324. GetLastInstruction(p, hp1) and
  11325. (tai(hp1).typ = ait_instruction) and
  11326. GetNextInstruction(p,hp2) and
  11327. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11328. case taicpu(hp1).opcode Of
  11329. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11330. { These two instructions set the zero flag if the result is zero }
  11331. A_POPCNT, A_LZCNT:
  11332. begin
  11333. if (
  11334. { With POPCNT, an input of zero will set the zero flag
  11335. because the population count of zero is zero }
  11336. (taicpu(hp1).opcode = A_POPCNT) and
  11337. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11338. (
  11339. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11340. { Faster than going through the second half of the 'or'
  11341. condition below }
  11342. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11343. )
  11344. ) or (
  11345. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11346. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11347. { and in case of carry for A(E)/B(E)/C/NC }
  11348. (
  11349. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11350. (
  11351. (taicpu(hp1).opcode <> A_ADD) and
  11352. (taicpu(hp1).opcode <> A_SUB) and
  11353. (taicpu(hp1).opcode <> A_LZCNT)
  11354. )
  11355. )
  11356. ) then
  11357. begin
  11358. RemoveCurrentP(p, hp2);
  11359. Result:=true;
  11360. Exit;
  11361. end;
  11362. end;
  11363. A_SHL, A_SAL, A_SHR, A_SAR:
  11364. begin
  11365. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11366. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11367. { therefore, it's only safe to do this optimization for }
  11368. { shifts by a (nonzero) constant }
  11369. (taicpu(hp1).oper[0]^.typ = top_const) and
  11370. (taicpu(hp1).oper[0]^.val <> 0) and
  11371. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11372. { and in case of carry for A(E)/B(E)/C/NC }
  11373. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11374. begin
  11375. RemoveCurrentP(p, hp2);
  11376. Result:=true;
  11377. Exit;
  11378. end;
  11379. end;
  11380. A_DEC, A_INC, A_NEG:
  11381. begin
  11382. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11383. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11384. { and in case of carry for A(E)/B(E)/C/NC }
  11385. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11386. begin
  11387. RemoveCurrentP(p, hp2);
  11388. Result:=true;
  11389. Exit;
  11390. end;
  11391. end
  11392. else
  11393. ;
  11394. end; { case }
  11395. { change "test $-1,%reg" into "test %reg,%reg" }
  11396. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11397. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11398. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11399. if MatchInstruction(p, A_OR, []) and
  11400. { Can only match if they're both registers }
  11401. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11402. begin
  11403. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11404. taicpu(p).opcode := A_TEST;
  11405. { No need to set Result to True, as we've done all the optimisations we can }
  11406. end;
  11407. end;
  11408. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11409. var
  11410. hp1,hp3 : tai;
  11411. {$ifndef x86_64}
  11412. hp2 : taicpu;
  11413. {$endif x86_64}
  11414. begin
  11415. Result:=false;
  11416. hp3:=nil;
  11417. {$ifndef x86_64}
  11418. { don't do this on modern CPUs, this really hurts them due to
  11419. broken call/ret pairing }
  11420. if (current_settings.optimizecputype < cpu_Pentium2) and
  11421. not(cs_create_pic in current_settings.moduleswitches) and
  11422. GetNextInstruction(p, hp1) and
  11423. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11424. MatchOpType(taicpu(hp1),top_ref) and
  11425. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11426. begin
  11427. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11428. InsertLLItem(p.previous, p, hp2);
  11429. taicpu(p).opcode := A_JMP;
  11430. taicpu(p).is_jmp := true;
  11431. RemoveInstruction(hp1);
  11432. Result:=true;
  11433. end
  11434. else
  11435. {$endif x86_64}
  11436. { replace
  11437. call procname
  11438. ret
  11439. by
  11440. jmp procname
  11441. but do it only on level 4 because it destroys stack back traces
  11442. else if the subroutine is marked as no return, remove the ret
  11443. }
  11444. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11445. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11446. GetNextInstruction(p, hp1) and
  11447. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11448. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11449. SetAndTest(hp1,hp3) and
  11450. GetNextInstruction(hp1,hp1) and
  11451. MatchInstruction(hp1,A_RET,[S_NO])
  11452. )
  11453. ) and
  11454. (taicpu(hp1).ops=0) then
  11455. begin
  11456. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11457. { we might destroy stack alignment here if we do not do a call }
  11458. (target_info.stackalign<=sizeof(SizeUInt)) then
  11459. begin
  11460. taicpu(p).opcode := A_JMP;
  11461. taicpu(p).is_jmp := true;
  11462. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11463. end
  11464. else
  11465. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11466. RemoveInstruction(hp1);
  11467. if Assigned(hp3) then
  11468. begin
  11469. AsmL.Remove(hp3);
  11470. AsmL.InsertBefore(hp3,p)
  11471. end;
  11472. Result:=true;
  11473. end;
  11474. end;
  11475. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11476. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11477. begin
  11478. case OpSize of
  11479. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11480. Result := (Val <= $FF) and (Val >= -128);
  11481. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11482. Result := (Val <= $FFFF) and (Val >= -32768);
  11483. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11484. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11485. else
  11486. Result := True;
  11487. end;
  11488. end;
  11489. var
  11490. hp1, hp2 : tai;
  11491. SizeChange: Boolean;
  11492. PreMessage: string;
  11493. begin
  11494. Result := False;
  11495. if (taicpu(p).oper[0]^.typ = top_reg) and
  11496. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11497. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11498. begin
  11499. { Change (using movzbl %al,%eax as an example):
  11500. movzbl %al, %eax movzbl %al, %eax
  11501. cmpl x, %eax testl %eax,%eax
  11502. To:
  11503. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11504. movzbl %al, %eax movzbl %al, %eax
  11505. Smaller instruction and minimises pipeline stall as the CPU
  11506. doesn't have to wait for the register to get zero-extended. [Kit]
  11507. Also allow if the smaller of the two registers is being checked,
  11508. as this still removes the false dependency.
  11509. }
  11510. if
  11511. (
  11512. (
  11513. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11514. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11515. ) or (
  11516. { If MatchOperand returns True, they must both be registers }
  11517. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11518. )
  11519. ) and
  11520. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11521. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11522. begin
  11523. 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);
  11524. asml.Remove(hp1);
  11525. asml.InsertBefore(hp1, p);
  11526. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11527. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11528. begin
  11529. taicpu(hp1).opcode := A_TEST;
  11530. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11531. end;
  11532. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11533. case taicpu(p).opsize of
  11534. S_BW, S_BL:
  11535. begin
  11536. SizeChange := taicpu(hp1).opsize <> S_B;
  11537. taicpu(hp1).changeopsize(S_B);
  11538. end;
  11539. S_WL:
  11540. begin
  11541. SizeChange := taicpu(hp1).opsize <> S_W;
  11542. taicpu(hp1).changeopsize(S_W);
  11543. end
  11544. else
  11545. InternalError(2020112701);
  11546. end;
  11547. UpdateUsedRegs(tai(p.Next));
  11548. { Check if the register is used aferwards - if not, we can
  11549. remove the movzx instruction completely }
  11550. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11551. begin
  11552. { Hp1 is a better position than p for debugging purposes }
  11553. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11554. RemoveCurrentp(p, hp1);
  11555. Result := True;
  11556. end;
  11557. if SizeChange then
  11558. DebugMsg(SPeepholeOptimization + PreMessage +
  11559. 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)
  11560. else
  11561. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11562. Exit;
  11563. end;
  11564. { Change (using movzwl %ax,%eax as an example):
  11565. movzwl %ax, %eax
  11566. movb %al, (dest) (Register is smaller than read register in movz)
  11567. To:
  11568. movb %al, (dest) (Move one back to avoid a false dependency)
  11569. movzwl %ax, %eax
  11570. }
  11571. if (taicpu(hp1).opcode = A_MOV) and
  11572. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11573. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11574. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11575. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11576. begin
  11577. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11578. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11579. asml.Remove(hp1);
  11580. asml.InsertBefore(hp1, p);
  11581. if taicpu(hp1).oper[1]^.typ = top_reg then
  11582. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11583. { Check if the register is used aferwards - if not, we can
  11584. remove the movzx instruction completely }
  11585. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11586. begin
  11587. { Hp1 is a better position than p for debugging purposes }
  11588. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11589. RemoveCurrentp(p, hp1);
  11590. Result := True;
  11591. end;
  11592. Exit;
  11593. end;
  11594. end;
  11595. end;
  11596. {$ifdef x86_64}
  11597. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11598. var
  11599. PreMessage, RegName: string;
  11600. begin
  11601. { Code size reduction by J. Gareth "Kit" Moreton }
  11602. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11603. as this removes the REX prefix }
  11604. Result := False;
  11605. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11606. Exit;
  11607. if taicpu(p).oper[0]^.typ <> top_reg then
  11608. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11609. InternalError(2018011500);
  11610. case taicpu(p).opsize of
  11611. S_Q:
  11612. begin
  11613. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11614. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11615. { The actual optimization }
  11616. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11617. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11618. taicpu(p).changeopsize(S_L);
  11619. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11620. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11621. end;
  11622. else
  11623. ;
  11624. end;
  11625. end;
  11626. {$endif}
  11627. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11628. var
  11629. XReg: TRegister;
  11630. begin
  11631. Result := False;
  11632. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11633. Smaller encoding and slightly faster on some platforms (also works for
  11634. ZMM-sized registers) }
  11635. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11636. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11637. begin
  11638. XReg := taicpu(p).oper[0]^.reg;
  11639. if (taicpu(p).oper[1]^.reg = XReg) then
  11640. begin
  11641. taicpu(p).changeopsize(S_XMM);
  11642. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11643. if (cs_opt_size in current_settings.optimizerswitches) then
  11644. begin
  11645. { Change input registers to %xmm0 to reduce size. Note that
  11646. there's a risk of a false dependency doing this, so only
  11647. optimise for size here }
  11648. XReg := NR_XMM0;
  11649. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11650. end
  11651. else
  11652. begin
  11653. setsubreg(XReg, R_SUBMMX);
  11654. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11655. end;
  11656. taicpu(p).oper[0]^.reg := XReg;
  11657. taicpu(p).oper[1]^.reg := XReg;
  11658. Result := True;
  11659. end;
  11660. end;
  11661. end;
  11662. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11663. var
  11664. OperIdx: Integer;
  11665. begin
  11666. for OperIdx := 0 to p.ops - 1 do
  11667. if p.oper[OperIdx]^.typ = top_ref then
  11668. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11669. end;
  11670. end.