aoptx86.pas 573 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. InsertLLItem(p.previous, p.next, hp1);
  1418. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1419. p.free;
  1420. p := hp1;
  1421. end
  1422. else if ((taicpu(p).ops <= 2) or
  1423. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1424. not(cs_opt_size in current_settings.optimizerswitches) and
  1425. (not(GetNextInstruction(p, hp1)) or
  1426. not((tai(hp1).typ = ait_instruction) and
  1427. ((taicpu(hp1).opcode=A_Jcc) and
  1428. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1429. begin
  1430. {
  1431. imul X, reg1, reg2 to
  1432. lea (reg1,reg1,Y), reg2
  1433. shl ZZ,reg2
  1434. imul XX, reg1 to
  1435. lea (reg1,reg1,YY), reg1
  1436. shl ZZ,reg2
  1437. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1438. it does not exist as a separate optimization target in FPC though.
  1439. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1440. at most two zeros
  1441. }
  1442. reference_reset(tmpref,1,[]);
  1443. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1444. begin
  1445. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1446. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1447. TmpRef.base := taicpu(p).oper[1]^.reg;
  1448. TmpRef.index := taicpu(p).oper[1]^.reg;
  1449. if not(BaseValue in [3,5,9]) then
  1450. Internalerror(2018110101);
  1451. TmpRef.ScaleFactor := BaseValue-1;
  1452. if (taicpu(p).ops = 2) then
  1453. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1454. else
  1455. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1456. AsmL.InsertAfter(hp1,p);
  1457. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1458. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1459. RemoveCurrentP(p, hp1);
  1460. if ShiftValue>0 then
  1461. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1462. end;
  1463. end;
  1464. end;
  1465. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1466. begin
  1467. Result := False;
  1468. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1469. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1470. begin
  1471. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1472. taicpu(p).opcode := A_MOV;
  1473. Result := True;
  1474. end;
  1475. end;
  1476. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1477. var
  1478. p: taicpu absolute hp; { Implicit typecast }
  1479. i: Integer;
  1480. begin
  1481. Result := False;
  1482. if not assigned(hp) or
  1483. (hp.typ <> ait_instruction) then
  1484. Exit;
  1485. Prefetch(insprop[p.opcode]);
  1486. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1487. with insprop[p.opcode] do
  1488. begin
  1489. case getsubreg(reg) of
  1490. R_SUBW,R_SUBD,R_SUBQ:
  1491. Result:=
  1492. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1493. uncommon flags are checked first }
  1494. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1495. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1496. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1497. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1498. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1499. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1500. R_SUBFLAGCARRY:
  1501. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1502. R_SUBFLAGPARITY:
  1503. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1504. R_SUBFLAGAUXILIARY:
  1505. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1506. R_SUBFLAGZERO:
  1507. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGSIGN:
  1509. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGOVERFLOW:
  1511. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGINTERRUPT:
  1513. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGDIRECTION:
  1515. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1516. else
  1517. internalerror(2017050501);
  1518. end;
  1519. exit;
  1520. end;
  1521. { Handle special cases first }
  1522. case p.opcode of
  1523. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1524. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1525. begin
  1526. Result :=
  1527. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1528. (p.oper[1]^.typ = top_reg) and
  1529. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1530. (
  1531. (p.oper[0]^.typ = top_const) or
  1532. (
  1533. (p.oper[0]^.typ = top_reg) and
  1534. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1535. ) or (
  1536. (p.oper[0]^.typ = top_ref) and
  1537. not RegInRef(reg,p.oper[0]^.ref^)
  1538. )
  1539. );
  1540. end;
  1541. A_MUL, A_IMUL:
  1542. Result :=
  1543. (
  1544. (p.ops=3) and { IMUL only }
  1545. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1546. (
  1547. (
  1548. (p.oper[1]^.typ=top_reg) and
  1549. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1550. ) or (
  1551. (p.oper[1]^.typ=top_ref) and
  1552. not RegInRef(reg,p.oper[1]^.ref^)
  1553. )
  1554. )
  1555. ) or (
  1556. (
  1557. (p.ops=1) and
  1558. (
  1559. (
  1560. (
  1561. (p.oper[0]^.typ=top_reg) and
  1562. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1563. )
  1564. ) or (
  1565. (p.oper[0]^.typ=top_ref) and
  1566. not RegInRef(reg,p.oper[0]^.ref^)
  1567. )
  1568. ) and (
  1569. (
  1570. (p.opsize=S_B) and
  1571. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1572. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1573. ) or (
  1574. (p.opsize=S_W) and
  1575. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1576. ) or (
  1577. (p.opsize=S_L) and
  1578. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1579. {$ifdef x86_64}
  1580. ) or (
  1581. (p.opsize=S_Q) and
  1582. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1583. {$endif x86_64}
  1584. )
  1585. )
  1586. )
  1587. );
  1588. A_CBW:
  1589. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1590. {$ifndef x86_64}
  1591. A_LDS:
  1592. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1593. A_LES:
  1594. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1595. {$endif not x86_64}
  1596. A_LFS:
  1597. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1598. A_LGS:
  1599. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1600. A_LSS:
  1601. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1602. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1603. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1604. A_LODSB:
  1605. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1606. A_LODSW:
  1607. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1608. {$ifdef x86_64}
  1609. A_LODSQ:
  1610. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1611. {$endif x86_64}
  1612. A_LODSD:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1614. A_FSTSW, A_FNSTSW:
  1615. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1616. else
  1617. begin
  1618. with insprop[p.opcode] do
  1619. begin
  1620. if (
  1621. { xor %reg,%reg etc. is classed as a new value }
  1622. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1623. MatchOpType(p, top_reg, top_reg) and
  1624. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1625. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1626. ) then
  1627. begin
  1628. Result := True;
  1629. Exit;
  1630. end;
  1631. { Make sure the entire register is overwritten }
  1632. if (getregtype(reg) = R_INTREGISTER) then
  1633. begin
  1634. if (p.ops > 0) then
  1635. begin
  1636. if RegInOp(reg, p.oper[0]^) then
  1637. begin
  1638. if (p.oper[0]^.typ = top_ref) then
  1639. begin
  1640. if RegInRef(reg, p.oper[0]^.ref^) then
  1641. begin
  1642. Result := False;
  1643. Exit;
  1644. end;
  1645. end
  1646. else if (p.oper[0]^.typ = top_reg) then
  1647. begin
  1648. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1649. begin
  1650. Result := False;
  1651. Exit;
  1652. end
  1653. else if ([Ch_WOp1]*Ch<>[]) then
  1654. begin
  1655. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1656. Result := True
  1657. else
  1658. begin
  1659. Result := False;
  1660. Exit;
  1661. end;
  1662. end;
  1663. end;
  1664. end;
  1665. if (p.ops > 1) then
  1666. begin
  1667. if RegInOp(reg, p.oper[1]^) then
  1668. begin
  1669. if (p.oper[1]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[1]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[1]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp2]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 2) then
  1697. begin
  1698. if RegInOp(reg, p.oper[2]^) then
  1699. begin
  1700. if (p.oper[2]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[2]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[2]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp3]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1728. begin
  1729. if (p.oper[3]^.typ = top_ref) then
  1730. begin
  1731. if RegInRef(reg, p.oper[3]^.ref^) then
  1732. begin
  1733. Result := False;
  1734. Exit;
  1735. end;
  1736. end
  1737. else if (p.oper[3]^.typ = top_reg) then
  1738. begin
  1739. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1740. begin
  1741. Result := False;
  1742. Exit;
  1743. end
  1744. else if ([Ch_WOp4]*Ch<>[]) then
  1745. begin
  1746. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1747. Result := True
  1748. else
  1749. begin
  1750. Result := False;
  1751. Exit;
  1752. end;
  1753. end;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1760. case getsupreg(reg) of
  1761. RS_EAX:
  1762. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1763. begin
  1764. Result := True;
  1765. Exit;
  1766. end;
  1767. RS_ECX:
  1768. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_EDX:
  1774. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EBX:
  1780. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_ESP:
  1786. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_EBP:
  1792. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_ESI:
  1798. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_EDI:
  1804. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. else
  1810. ;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1818. var
  1819. hp2,hp3 : tai;
  1820. begin
  1821. { some x86-64 issue a NOP before the real exit code }
  1822. if MatchInstruction(p,A_NOP,[]) then
  1823. GetNextInstruction(p,p);
  1824. result:=assigned(p) and (p.typ=ait_instruction) and
  1825. ((taicpu(p).opcode = A_RET) or
  1826. ((taicpu(p).opcode=A_LEAVE) and
  1827. GetNextInstruction(p,hp2) and
  1828. MatchInstruction(hp2,A_RET,[S_NO])
  1829. ) or
  1830. (((taicpu(p).opcode=A_LEA) and
  1831. MatchOpType(taicpu(p),top_ref,top_reg) and
  1832. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1833. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1834. ) and
  1835. GetNextInstruction(p,hp2) and
  1836. MatchInstruction(hp2,A_RET,[S_NO])
  1837. ) or
  1838. ((((taicpu(p).opcode=A_MOV) and
  1839. MatchOpType(taicpu(p),top_reg,top_reg) and
  1840. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1841. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1842. ((taicpu(p).opcode=A_LEA) and
  1843. MatchOpType(taicpu(p),top_ref,top_reg) and
  1844. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1845. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1846. )
  1847. ) and
  1848. GetNextInstruction(p,hp2) and
  1849. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1850. MatchOpType(taicpu(hp2),top_reg) and
  1851. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1852. GetNextInstruction(hp2,hp3) and
  1853. MatchInstruction(hp3,A_RET,[S_NO])
  1854. )
  1855. );
  1856. end;
  1857. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1858. begin
  1859. isFoldableArithOp := False;
  1860. case hp1.opcode of
  1861. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1862. isFoldableArithOp :=
  1863. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1864. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1865. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1867. (taicpu(hp1).oper[1]^.reg = reg);
  1868. A_INC,A_DEC,A_NEG,A_NOT:
  1869. isFoldableArithOp :=
  1870. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg = reg);
  1872. else
  1873. ;
  1874. end;
  1875. end;
  1876. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1877. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1878. var
  1879. hp2: tai;
  1880. begin
  1881. hp2 := p;
  1882. repeat
  1883. hp2 := tai(hp2.previous);
  1884. if assigned(hp2) and
  1885. (hp2.typ = ait_regalloc) and
  1886. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1887. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1888. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1889. begin
  1890. RemoveInstruction(hp2);
  1891. break;
  1892. end;
  1893. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1894. end;
  1895. begin
  1896. case current_procinfo.procdef.returndef.typ of
  1897. arraydef,recorddef,pointerdef,
  1898. stringdef,enumdef,procdef,objectdef,errordef,
  1899. filedef,setdef,procvardef,
  1900. classrefdef,forwarddef:
  1901. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1902. orddef:
  1903. if current_procinfo.procdef.returndef.size <> 0 then
  1904. begin
  1905. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1906. { for int64/qword }
  1907. if current_procinfo.procdef.returndef.size = 8 then
  1908. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1909. end;
  1910. else
  1911. ;
  1912. end;
  1913. end;
  1914. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1915. var
  1916. hp1,hp2 : tai;
  1917. begin
  1918. result:=false;
  1919. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1920. begin
  1921. { vmova* reg1,reg1
  1922. =>
  1923. <nop> }
  1924. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1925. begin
  1926. RemoveCurrentP(p);
  1927. result:=true;
  1928. exit;
  1929. end
  1930. else if GetNextInstruction(p,hp1) then
  1931. begin
  1932. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1933. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1934. begin
  1935. { vmova* reg1,reg2
  1936. vmova* reg2,reg3
  1937. dealloc reg2
  1938. =>
  1939. vmova* reg1,reg3 }
  1940. TransferUsedRegs(TmpUsedRegs);
  1941. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1942. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1943. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1944. begin
  1945. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1946. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1947. RemoveInstruction(hp1);
  1948. result:=true;
  1949. exit;
  1950. end
  1951. { special case:
  1952. vmova* reg1,<op>
  1953. vmova* <op>,reg1
  1954. =>
  1955. vmova* reg1,<op> }
  1956. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1957. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1958. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1959. ) then
  1960. begin
  1961. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1962. RemoveInstruction(hp1);
  1963. result:=true;
  1964. exit;
  1965. end
  1966. end
  1967. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1968. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1969. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1970. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1971. ) and
  1972. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1973. begin
  1974. { vmova* reg1,reg2
  1975. vmovs* reg2,<op>
  1976. dealloc reg2
  1977. =>
  1978. vmovs* reg1,reg3 }
  1979. TransferUsedRegs(TmpUsedRegs);
  1980. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1981. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1982. begin
  1983. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1984. taicpu(p).opcode:=taicpu(hp1).opcode;
  1985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1986. RemoveInstruction(hp1);
  1987. result:=true;
  1988. exit;
  1989. end
  1990. end;
  1991. end;
  1992. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1993. begin
  1994. if MatchInstruction(hp1,[A_VFMADDPD,
  1995. A_VFMADD132PD,
  1996. A_VFMADD132PS,
  1997. A_VFMADD132SD,
  1998. A_VFMADD132SS,
  1999. A_VFMADD213PD,
  2000. A_VFMADD213PS,
  2001. A_VFMADD213SD,
  2002. A_VFMADD213SS,
  2003. A_VFMADD231PD,
  2004. A_VFMADD231PS,
  2005. A_VFMADD231SD,
  2006. A_VFMADD231SS,
  2007. A_VFMADDSUB132PD,
  2008. A_VFMADDSUB132PS,
  2009. A_VFMADDSUB213PD,
  2010. A_VFMADDSUB213PS,
  2011. A_VFMADDSUB231PD,
  2012. A_VFMADDSUB231PS,
  2013. A_VFMSUB132PD,
  2014. A_VFMSUB132PS,
  2015. A_VFMSUB132SD,
  2016. A_VFMSUB132SS,
  2017. A_VFMSUB213PD,
  2018. A_VFMSUB213PS,
  2019. A_VFMSUB213SD,
  2020. A_VFMSUB213SS,
  2021. A_VFMSUB231PD,
  2022. A_VFMSUB231PS,
  2023. A_VFMSUB231SD,
  2024. A_VFMSUB231SS,
  2025. A_VFMSUBADD132PD,
  2026. A_VFMSUBADD132PS,
  2027. A_VFMSUBADD213PD,
  2028. A_VFMSUBADD213PS,
  2029. A_VFMSUBADD231PD,
  2030. A_VFMSUBADD231PS,
  2031. A_VFNMADD132PD,
  2032. A_VFNMADD132PS,
  2033. A_VFNMADD132SD,
  2034. A_VFNMADD132SS,
  2035. A_VFNMADD213PD,
  2036. A_VFNMADD213PS,
  2037. A_VFNMADD213SD,
  2038. A_VFNMADD213SS,
  2039. A_VFNMADD231PD,
  2040. A_VFNMADD231PS,
  2041. A_VFNMADD231SD,
  2042. A_VFNMADD231SS,
  2043. A_VFNMSUB132PD,
  2044. A_VFNMSUB132PS,
  2045. A_VFNMSUB132SD,
  2046. A_VFNMSUB132SS,
  2047. A_VFNMSUB213PD,
  2048. A_VFNMSUB213PS,
  2049. A_VFNMSUB213SD,
  2050. A_VFNMSUB213SS,
  2051. A_VFNMSUB231PD,
  2052. A_VFNMSUB231PS,
  2053. A_VFNMSUB231SD,
  2054. A_VFNMSUB231SS],[S_NO]) and
  2055. { we mix single and double opperations here because we assume that the compiler
  2056. generates vmovapd only after double operations and vmovaps only after single operations }
  2057. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2058. GetNextInstruction(hp1,hp2) and
  2059. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2060. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2061. begin
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2065. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2066. begin
  2067. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2068. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  2069. RemoveInstruction(hp2);
  2070. end;
  2071. end
  2072. else if (hp1.typ = ait_instruction) and
  2073. GetNextInstruction(hp1, hp2) and
  2074. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2075. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2076. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2077. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2078. (((taicpu(p).opcode=A_MOVAPS) and
  2079. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2080. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2081. ((taicpu(p).opcode=A_MOVAPD) and
  2082. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2083. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2084. ) then
  2085. { change
  2086. movapX reg,reg2
  2087. addsX/subsX/... reg3, reg2
  2088. movapX reg2,reg
  2089. to
  2090. addsX/subsX/... reg3,reg
  2091. }
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2099. debug_op2str(taicpu(p).opcode)+' '+
  2100. debug_op2str(taicpu(hp1).opcode)+' '+
  2101. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2102. { we cannot eliminate the first move if
  2103. the operations uses the same register for source and dest }
  2104. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2105. RemoveCurrentP(p, nil);
  2106. p:=hp1;
  2107. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2108. RemoveInstruction(hp2);
  2109. result:=true;
  2110. end;
  2111. end
  2112. else if (hp1.typ = ait_instruction) and
  2113. (((taicpu(p).opcode=A_VMOVAPD) and
  2114. (taicpu(hp1).opcode=A_VCOMISD)) or
  2115. ((taicpu(p).opcode=A_VMOVAPS) and
  2116. ((taicpu(hp1).opcode=A_VCOMISS))
  2117. )
  2118. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2119. { change
  2120. movapX reg,reg1
  2121. vcomisX reg1,reg1
  2122. to
  2123. vcomisX reg,reg
  2124. }
  2125. begin
  2126. TransferUsedRegs(TmpUsedRegs);
  2127. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2128. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2129. begin
  2130. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2131. debug_op2str(taicpu(p).opcode)+' '+
  2132. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2133. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2134. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2135. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2136. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2137. RemoveCurrentP(p, nil);
  2138. result:=true;
  2139. exit;
  2140. end;
  2141. end
  2142. end;
  2143. end;
  2144. end;
  2145. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2146. var
  2147. hp1 : tai;
  2148. begin
  2149. result:=false;
  2150. { replace
  2151. V<Op>X %mreg1,%mreg2,%mreg3
  2152. VMovX %mreg3,%mreg4
  2153. dealloc %mreg3
  2154. by
  2155. V<Op>X %mreg1,%mreg2,%mreg4
  2156. ?
  2157. }
  2158. if GetNextInstruction(p,hp1) and
  2159. { we mix single and double operations here because we assume that the compiler
  2160. generates vmovapd only after double operations and vmovaps only after single operations }
  2161. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2162. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2163. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2164. begin
  2165. TransferUsedRegs(TmpUsedRegs);
  2166. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2167. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2168. begin
  2169. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2170. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2171. RemoveInstruction(hp1);
  2172. result:=true;
  2173. end;
  2174. end;
  2175. end;
  2176. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2177. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2178. begin
  2179. Result := False;
  2180. { For safety reasons, only check for exact register matches }
  2181. { Check base register }
  2182. if (ref.base = AOldReg) then
  2183. begin
  2184. ref.base := ANewReg;
  2185. Result := True;
  2186. end;
  2187. { Check index register }
  2188. if (ref.index = AOldReg) then
  2189. begin
  2190. ref.index := ANewReg;
  2191. Result := True;
  2192. end;
  2193. end;
  2194. { Replaces all references to AOldReg in an operand to ANewReg }
  2195. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2196. var
  2197. OldSupReg, NewSupReg: TSuperRegister;
  2198. OldSubReg, NewSubReg: TSubRegister;
  2199. OldRegType: TRegisterType;
  2200. ThisOper: POper;
  2201. begin
  2202. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2203. Result := False;
  2204. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2205. InternalError(2020011801);
  2206. OldSupReg := getsupreg(AOldReg);
  2207. OldSubReg := getsubreg(AOldReg);
  2208. OldRegType := getregtype(AOldReg);
  2209. NewSupReg := getsupreg(ANewReg);
  2210. NewSubReg := getsubreg(ANewReg);
  2211. if OldRegType <> getregtype(ANewReg) then
  2212. InternalError(2020011802);
  2213. if OldSubReg <> NewSubReg then
  2214. InternalError(2020011803);
  2215. case ThisOper^.typ of
  2216. top_reg:
  2217. if (
  2218. (ThisOper^.reg = AOldReg) or
  2219. (
  2220. (OldRegType = R_INTREGISTER) and
  2221. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2222. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2223. (
  2224. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2225. {$ifndef x86_64}
  2226. and (
  2227. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2228. don't have an 8-bit representation }
  2229. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2230. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2231. )
  2232. {$endif x86_64}
  2233. )
  2234. )
  2235. ) then
  2236. begin
  2237. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2238. Result := True;
  2239. end;
  2240. top_ref:
  2241. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2242. Result := True;
  2243. else
  2244. ;
  2245. end;
  2246. end;
  2247. { Replaces all references to AOldReg in an instruction to ANewReg }
  2248. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2249. const
  2250. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2251. var
  2252. OperIdx: Integer;
  2253. begin
  2254. Result := False;
  2255. for OperIdx := 0 to p.ops - 1 do
  2256. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2257. begin
  2258. { The shift and rotate instructions can only use CL }
  2259. if not (
  2260. (OperIdx = 0) and
  2261. { This second condition just helps to avoid unnecessarily
  2262. calling MatchInstruction for 10 different opcodes }
  2263. (p.oper[0]^.reg = NR_CL) and
  2264. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2265. ) then
  2266. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2267. end
  2268. else if p.oper[OperIdx]^.typ = top_ref then
  2269. { It's okay to replace registers in references that get written to }
  2270. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2271. end;
  2272. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2273. begin
  2274. with ref^ do
  2275. Result :=
  2276. (index = NR_NO) and
  2277. (
  2278. {$ifdef x86_64}
  2279. (
  2280. (base = NR_RIP) and
  2281. (refaddr in [addr_pic, addr_pic_no_got])
  2282. ) or
  2283. {$endif x86_64}
  2284. (base = NR_STACK_POINTER_REG) or
  2285. (base = current_procinfo.framepointer)
  2286. );
  2287. end;
  2288. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2289. var
  2290. l: asizeint;
  2291. begin
  2292. Result := False;
  2293. { Should have been checked previously }
  2294. if p.opcode <> A_LEA then
  2295. InternalError(2020072501);
  2296. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2297. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2298. not(cs_opt_size in current_settings.optimizerswitches) then
  2299. exit;
  2300. with p.oper[0]^.ref^ do
  2301. begin
  2302. if (base <> p.oper[1]^.reg) or
  2303. (index <> NR_NO) or
  2304. assigned(symbol) then
  2305. exit;
  2306. l:=offset;
  2307. if (l=1) and UseIncDec then
  2308. begin
  2309. p.opcode:=A_INC;
  2310. p.loadreg(0,p.oper[1]^.reg);
  2311. p.ops:=1;
  2312. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2313. end
  2314. else if (l=-1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_DEC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2320. end
  2321. else
  2322. begin
  2323. if (l<0) and (l<>-2147483648) then
  2324. begin
  2325. p.opcode:=A_SUB;
  2326. p.loadConst(0,-l);
  2327. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2328. end
  2329. else
  2330. begin
  2331. p.opcode:=A_ADD;
  2332. p.loadConst(0,l);
  2333. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2334. end;
  2335. end;
  2336. end;
  2337. Result := True;
  2338. end;
  2339. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2340. var
  2341. CurrentReg, ReplaceReg: TRegister;
  2342. begin
  2343. Result := False;
  2344. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2345. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2346. case hp.opcode of
  2347. A_FSTSW, A_FNSTSW,
  2348. A_IN, A_INS, A_OUT, A_OUTS,
  2349. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2350. { These routines have explicit operands, but they are restricted in
  2351. what they can be (e.g. IN and OUT can only read from AL, AX or
  2352. EAX. }
  2353. Exit;
  2354. A_IMUL:
  2355. begin
  2356. { The 1-operand version writes to implicit registers
  2357. The 2-operand version reads from the first operator, and reads
  2358. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2359. the 3-operand version reads from a register that it doesn't write to
  2360. }
  2361. case hp.ops of
  2362. 1:
  2363. if (
  2364. (
  2365. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2366. ) or
  2367. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2368. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2369. begin
  2370. Result := True;
  2371. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2372. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2373. end;
  2374. 2:
  2375. { Only modify the first parameter }
  2376. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2377. begin
  2378. Result := True;
  2379. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2380. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2381. end;
  2382. 3:
  2383. { Only modify the second parameter }
  2384. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2385. begin
  2386. Result := True;
  2387. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2388. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2389. end;
  2390. else
  2391. InternalError(2020012901);
  2392. end;
  2393. end;
  2394. else
  2395. if (hp.ops > 0) and
  2396. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2397. begin
  2398. Result := True;
  2399. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2400. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2401. end;
  2402. end;
  2403. end;
  2404. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2405. var
  2406. hp1, hp2, hp3: tai;
  2407. DoOptimisation, TempBool: Boolean;
  2408. {$ifdef x86_64}
  2409. NewConst: TCGInt;
  2410. {$endif x86_64}
  2411. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2412. begin
  2413. if taicpu(hp1).opcode = signed_movop then
  2414. begin
  2415. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2416. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2417. end
  2418. else
  2419. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2420. end;
  2421. function TryConstMerge(var p1, p2: tai): Boolean;
  2422. var
  2423. ThisRef: TReference;
  2424. begin
  2425. Result := False;
  2426. ThisRef := taicpu(p2).oper[1]^.ref^;
  2427. { Only permit writes to the stack, since we can guarantee alignment with that }
  2428. if (ThisRef.index = NR_NO) and
  2429. (
  2430. (ThisRef.base = NR_STACK_POINTER_REG) or
  2431. (ThisRef.base = current_procinfo.framepointer)
  2432. ) then
  2433. begin
  2434. case taicpu(p).opsize of
  2435. S_B:
  2436. begin
  2437. { Word writes must be on a 2-byte boundary }
  2438. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2439. begin
  2440. { Reduce offset of second reference to see if it is sequential with the first }
  2441. Dec(ThisRef.offset, 1);
  2442. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2443. begin
  2444. { Make sure the constants aren't represented as a
  2445. negative number, as these won't merge properly }
  2446. taicpu(p1).opsize := S_W;
  2447. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2448. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2449. RemoveInstruction(p2);
  2450. Result := True;
  2451. end;
  2452. end;
  2453. end;
  2454. S_W:
  2455. begin
  2456. { Longword writes must be on a 4-byte boundary }
  2457. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2458. begin
  2459. { Reduce offset of second reference to see if it is sequential with the first }
  2460. Dec(ThisRef.offset, 2);
  2461. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2462. begin
  2463. { Make sure the constants aren't represented as a
  2464. negative number, as these won't merge properly }
  2465. taicpu(p1).opsize := S_L;
  2466. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2467. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2468. RemoveInstruction(p2);
  2469. Result := True;
  2470. end;
  2471. end;
  2472. end;
  2473. {$ifdef x86_64}
  2474. S_L:
  2475. begin
  2476. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2477. see if the constants can be encoded this way. }
  2478. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2479. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2480. { Quadword writes must be on an 8-byte boundary }
  2481. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2482. begin
  2483. { Reduce offset of second reference to see if it is sequential with the first }
  2484. Dec(ThisRef.offset, 4);
  2485. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2486. begin
  2487. { Make sure the constants aren't represented as a
  2488. negative number, as these won't merge properly }
  2489. taicpu(p1).opsize := S_Q;
  2490. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2491. taicpu(p1).oper[0]^.val := NewConst;
  2492. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2493. RemoveInstruction(p2);
  2494. Result := True;
  2495. end;
  2496. end;
  2497. end;
  2498. {$endif x86_64}
  2499. else
  2500. ;
  2501. end;
  2502. end;
  2503. end;
  2504. var
  2505. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2506. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2507. NewSize: topsize;
  2508. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2509. SourceRef, TargetRef: TReference;
  2510. MovAligned, MovUnaligned: TAsmOp;
  2511. ThisRef: TReference;
  2512. JumpTracking: TLinkedList;
  2513. begin
  2514. Result:=false;
  2515. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2516. { remove mov reg1,reg1? }
  2517. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2518. then
  2519. begin
  2520. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2521. { take care of the register (de)allocs following p }
  2522. RemoveCurrentP(p, hp1);
  2523. Result:=true;
  2524. exit;
  2525. end;
  2526. { All the next optimisations require a next instruction }
  2527. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2528. Exit;
  2529. { Prevent compiler warnings }
  2530. p_TargetReg := NR_NO;
  2531. if taicpu(p).oper[1]^.typ = top_reg then
  2532. begin
  2533. { Saves on a large number of dereferences }
  2534. p_TargetReg := taicpu(p).oper[1]^.reg;
  2535. { Look for:
  2536. mov %reg1,%reg2
  2537. ??? %reg2,r/m
  2538. Change to:
  2539. mov %reg1,%reg2
  2540. ??? %reg1,r/m
  2541. }
  2542. if taicpu(p).oper[0]^.typ = top_reg then
  2543. begin
  2544. if RegReadByInstruction(p_TargetReg, hp1) and
  2545. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2546. begin
  2547. { A change has occurred, just not in p }
  2548. Result := True;
  2549. TransferUsedRegs(TmpUsedRegs);
  2550. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2551. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2552. { Just in case something didn't get modified (e.g. an
  2553. implicit register) }
  2554. not RegReadByInstruction(p_TargetReg, hp1) then
  2555. begin
  2556. { We can remove the original MOV }
  2557. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2558. RemoveCurrentp(p, hp1);
  2559. { UsedRegs got updated by RemoveCurrentp }
  2560. Result := True;
  2561. Exit;
  2562. end;
  2563. { If we know a MOV instruction has become a null operation, we might as well
  2564. get rid of it now to save time. }
  2565. if (taicpu(hp1).opcode = A_MOV) and
  2566. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2567. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2568. { Just being a register is enough to confirm it's a null operation }
  2569. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2570. begin
  2571. Result := True;
  2572. { Speed-up to reduce a pipeline stall... if we had something like...
  2573. movl %eax,%edx
  2574. movw %dx,%ax
  2575. ... the second instruction would change to movw %ax,%ax, but
  2576. given that it is now %ax that's active rather than %eax,
  2577. penalties might occur due to a partial register write, so instead,
  2578. change it to a MOVZX instruction when optimising for speed.
  2579. }
  2580. if not (cs_opt_size in current_settings.optimizerswitches) and
  2581. IsMOVZXAcceptable and
  2582. (taicpu(hp1).opsize < taicpu(p).opsize)
  2583. {$ifdef x86_64}
  2584. { operations already implicitly set the upper 64 bits to zero }
  2585. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2586. {$endif x86_64}
  2587. then
  2588. begin
  2589. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2590. case taicpu(p).opsize of
  2591. S_W:
  2592. if taicpu(hp1).opsize = S_B then
  2593. taicpu(hp1).opsize := S_BL
  2594. else
  2595. InternalError(2020012911);
  2596. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2597. case taicpu(hp1).opsize of
  2598. S_B:
  2599. taicpu(hp1).opsize := S_BL;
  2600. S_W:
  2601. taicpu(hp1).opsize := S_WL;
  2602. else
  2603. InternalError(2020012912);
  2604. end;
  2605. else
  2606. InternalError(2020012910);
  2607. end;
  2608. taicpu(hp1).opcode := A_MOVZX;
  2609. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2610. end
  2611. else
  2612. begin
  2613. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2614. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2615. RemoveInstruction(hp1);
  2616. { The instruction after what was hp1 is now the immediate next instruction,
  2617. so we can continue to make optimisations if it's present }
  2618. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2619. Exit;
  2620. hp1 := hp2;
  2621. end;
  2622. end;
  2623. end;
  2624. end;
  2625. end;
  2626. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2627. overwrites the original destination register. e.g.
  2628. movl ###,%reg2d
  2629. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2630. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2631. }
  2632. if (taicpu(p).oper[1]^.typ = top_reg) and
  2633. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2634. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2635. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2636. begin
  2637. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2638. begin
  2639. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2640. case taicpu(p).oper[0]^.typ of
  2641. top_const:
  2642. { We have something like:
  2643. movb $x, %regb
  2644. movzbl %regb,%regd
  2645. Change to:
  2646. movl $x, %regd
  2647. }
  2648. begin
  2649. case taicpu(hp1).opsize of
  2650. S_BW:
  2651. begin
  2652. convert_mov_value(A_MOVSX, $FF);
  2653. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2654. taicpu(p).opsize := S_W;
  2655. end;
  2656. S_BL:
  2657. begin
  2658. convert_mov_value(A_MOVSX, $FF);
  2659. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2660. taicpu(p).opsize := S_L;
  2661. end;
  2662. S_WL:
  2663. begin
  2664. convert_mov_value(A_MOVSX, $FFFF);
  2665. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2666. taicpu(p).opsize := S_L;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_BQ:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2673. taicpu(p).opsize := S_Q;
  2674. end;
  2675. S_WQ:
  2676. begin
  2677. convert_mov_value(A_MOVSX, $FFFF);
  2678. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2679. taicpu(p).opsize := S_Q;
  2680. end;
  2681. S_LQ:
  2682. begin
  2683. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2684. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2685. taicpu(p).opsize := S_Q;
  2686. end;
  2687. {$endif x86_64}
  2688. else
  2689. { If hp1 was a MOV instruction, it should have been
  2690. optimised already }
  2691. InternalError(2020021001);
  2692. end;
  2693. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2694. RemoveInstruction(hp1);
  2695. Result := True;
  2696. Exit;
  2697. end;
  2698. top_ref:
  2699. begin
  2700. { We have something like:
  2701. movb mem, %regb
  2702. movzbl %regb,%regd
  2703. Change to:
  2704. movzbl mem, %regd
  2705. }
  2706. ThisRef := taicpu(p).oper[0]^.ref^;
  2707. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2708. begin
  2709. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2710. taicpu(hp1).loadref(0, ThisRef);
  2711. { Make sure any registers in the references are properly tracked }
  2712. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2713. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2714. if (ThisRef.index <> NR_NO) then
  2715. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2716. RemoveCurrentP(p, hp1);
  2717. Result := True;
  2718. Exit;
  2719. end;
  2720. end;
  2721. else
  2722. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2723. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2724. Exit;
  2725. end;
  2726. end
  2727. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2728. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2729. optimised }
  2730. else
  2731. begin
  2732. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2733. RemoveCurrentP(p, hp1);
  2734. Result := True;
  2735. Exit;
  2736. end;
  2737. end;
  2738. if (taicpu(hp1).opcode = A_AND) and
  2739. (taicpu(p).oper[1]^.typ = top_reg) and
  2740. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2741. begin
  2742. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2743. begin
  2744. case taicpu(p).opsize of
  2745. S_L:
  2746. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2747. begin
  2748. { Optimize out:
  2749. mov x, %reg
  2750. and ffffffffh, %reg
  2751. }
  2752. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2753. RemoveInstruction(hp1);
  2754. Result:=true;
  2755. exit;
  2756. end;
  2757. S_Q: { TODO: Confirm if this is even possible }
  2758. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2759. begin
  2760. { Optimize out:
  2761. mov x, %reg
  2762. and ffffffffffffffffh, %reg
  2763. }
  2764. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2765. RemoveInstruction(hp1);
  2766. Result:=true;
  2767. exit;
  2768. end;
  2769. else
  2770. ;
  2771. end;
  2772. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2773. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2774. GetNextInstruction(hp1,hp2) and
  2775. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2776. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2777. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2778. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2779. GetNextInstruction(hp2,hp3) and
  2780. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2781. (taicpu(hp3).condition in [C_E,C_NE]) then
  2782. begin
  2783. TransferUsedRegs(TmpUsedRegs);
  2784. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2785. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2786. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2787. begin
  2788. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2789. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2790. taicpu(hp1).opcode:=A_TEST;
  2791. RemoveInstruction(hp2);
  2792. RemoveCurrentP(p, hp1);
  2793. Result:=true;
  2794. exit;
  2795. end;
  2796. end;
  2797. end
  2798. else if IsMOVZXAcceptable and
  2799. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2800. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2801. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2802. then
  2803. begin
  2804. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2805. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2806. case taicpu(p).opsize of
  2807. S_B:
  2808. if (taicpu(hp1).oper[0]^.val = $ff) then
  2809. begin
  2810. { Convert:
  2811. movb x, %regl movb x, %regl
  2812. andw ffh, %regw andl ffh, %regd
  2813. To:
  2814. movzbw x, %regd movzbl x, %regd
  2815. (Identical registers, just different sizes)
  2816. }
  2817. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2818. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2819. case taicpu(hp1).opsize of
  2820. S_W: NewSize := S_BW;
  2821. S_L: NewSize := S_BL;
  2822. {$ifdef x86_64}
  2823. S_Q: NewSize := S_BQ;
  2824. {$endif x86_64}
  2825. else
  2826. InternalError(2018011510);
  2827. end;
  2828. end
  2829. else
  2830. NewSize := S_NO;
  2831. S_W:
  2832. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2833. begin
  2834. { Convert:
  2835. movw x, %regw
  2836. andl ffffh, %regd
  2837. To:
  2838. movzwl x, %regd
  2839. (Identical registers, just different sizes)
  2840. }
  2841. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2842. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2843. case taicpu(hp1).opsize of
  2844. S_L: NewSize := S_WL;
  2845. {$ifdef x86_64}
  2846. S_Q: NewSize := S_WQ;
  2847. {$endif x86_64}
  2848. else
  2849. InternalError(2018011511);
  2850. end;
  2851. end
  2852. else
  2853. NewSize := S_NO;
  2854. else
  2855. NewSize := S_NO;
  2856. end;
  2857. if NewSize <> S_NO then
  2858. begin
  2859. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2860. { The actual optimization }
  2861. taicpu(p).opcode := A_MOVZX;
  2862. taicpu(p).changeopsize(NewSize);
  2863. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2864. { Safeguard if "and" is followed by a conditional command }
  2865. TransferUsedRegs(TmpUsedRegs);
  2866. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2867. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2868. begin
  2869. { At this point, the "and" command is effectively equivalent to
  2870. "test %reg,%reg". This will be handled separately by the
  2871. Peephole Optimizer. [Kit] }
  2872. DebugMsg(SPeepholeOptimization + PreMessage +
  2873. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2874. end
  2875. else
  2876. begin
  2877. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2878. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2879. RemoveInstruction(hp1);
  2880. end;
  2881. Result := True;
  2882. Exit;
  2883. end;
  2884. end;
  2885. end;
  2886. if (taicpu(hp1).opcode = A_OR) and
  2887. (taicpu(p).oper[1]^.typ = top_reg) and
  2888. MatchOperand(taicpu(p).oper[0]^, 0) and
  2889. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2890. begin
  2891. { mov 0, %reg
  2892. or ###,%reg
  2893. Change to (only if the flags are not used):
  2894. mov ###,%reg
  2895. }
  2896. TransferUsedRegs(TmpUsedRegs);
  2897. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2898. DoOptimisation := True;
  2899. { Even if the flags are used, we might be able to do the optimisation
  2900. if the conditions are predictable }
  2901. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2902. begin
  2903. { Only perform if ### = %reg (the same register) or equal to 0,
  2904. so %reg is guaranteed to still have a value of zero }
  2905. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2906. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2907. begin
  2908. hp2 := hp1;
  2909. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2910. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2911. GetNextInstruction(hp2, hp3) do
  2912. begin
  2913. { Don't continue modifying if the flags state is getting changed }
  2914. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2915. Break;
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2917. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2918. begin
  2919. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2920. begin
  2921. { Condition is always true }
  2922. case taicpu(hp3).opcode of
  2923. A_Jcc:
  2924. begin
  2925. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2926. { Check for jump shortcuts before we destroy the condition }
  2927. DoJumpOptimizations(hp3, TempBool);
  2928. MakeUnconditional(taicpu(hp3));
  2929. Result := True;
  2930. end;
  2931. A_CMOVcc:
  2932. begin
  2933. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2934. taicpu(hp3).opcode := A_MOV;
  2935. taicpu(hp3).condition := C_None;
  2936. Result := True;
  2937. end;
  2938. A_SETcc:
  2939. begin
  2940. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2941. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2942. taicpu(hp3).opcode := A_MOV;
  2943. taicpu(hp3).ops := 2;
  2944. taicpu(hp3).condition := C_None;
  2945. taicpu(hp3).opsize := S_B;
  2946. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2947. taicpu(hp3).loadconst(0, 1);
  2948. Result := True;
  2949. end;
  2950. else
  2951. InternalError(2021090701);
  2952. end;
  2953. end
  2954. 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
  2955. begin
  2956. { Condition is always false }
  2957. case taicpu(hp3).opcode of
  2958. A_Jcc:
  2959. begin
  2960. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2961. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2962. RemoveInstruction(hp3);
  2963. Result := True;
  2964. { Since hp3 was deleted, hp2 must not be updated }
  2965. Continue;
  2966. end;
  2967. A_CMOVcc:
  2968. begin
  2969. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2970. RemoveInstruction(hp3);
  2971. Result := True;
  2972. { Since hp3 was deleted, hp2 must not be updated }
  2973. Continue;
  2974. end;
  2975. A_SETcc:
  2976. begin
  2977. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2978. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2979. taicpu(hp3).opcode := A_MOV;
  2980. taicpu(hp3).ops := 2;
  2981. taicpu(hp3).condition := C_None;
  2982. taicpu(hp3).opsize := S_B;
  2983. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2984. taicpu(hp3).loadconst(0, 0);
  2985. Result := True;
  2986. end;
  2987. else
  2988. InternalError(2021090702);
  2989. end;
  2990. end
  2991. else
  2992. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2993. DoOptimisation := False;
  2994. end;
  2995. hp2 := hp3;
  2996. end;
  2997. { Flags are still in use - don't optimise }
  2998. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2999. DoOptimisation := False;
  3000. end
  3001. else
  3002. DoOptimisation := False;
  3003. end;
  3004. if DoOptimisation then
  3005. begin
  3006. {$ifdef x86_64}
  3007. { OR only supports 32-bit sign-extended constants for 64-bit
  3008. instructions, so compensate for this if the constant is
  3009. encoded as a value greater than or equal to 2^31 }
  3010. if (taicpu(hp1).opsize = S_Q) and
  3011. (taicpu(hp1).oper[0]^.typ = top_const) and
  3012. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3013. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3014. {$endif x86_64}
  3015. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3016. taicpu(hp1).opcode := A_MOV;
  3017. RemoveCurrentP(p, hp1);
  3018. Result := True;
  3019. Exit;
  3020. end;
  3021. end;
  3022. { Next instruction is also a MOV ? }
  3023. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3024. begin
  3025. if MatchOpType(taicpu(p), top_const, top_ref) and
  3026. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3027. TryConstMerge(p, hp1) then
  3028. begin
  3029. Result := True;
  3030. { In case we have four byte writes in a row, check for 2 more
  3031. right now so we don't have to wait for another iteration of
  3032. pass 1
  3033. }
  3034. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3035. case taicpu(p).opsize of
  3036. S_W:
  3037. begin
  3038. if GetNextInstruction(p, hp1) and
  3039. MatchInstruction(hp1, A_MOV, [S_B]) and
  3040. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3041. GetNextInstruction(hp1, hp2) and
  3042. MatchInstruction(hp2, A_MOV, [S_B]) and
  3043. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3044. { Try to merge the two bytes }
  3045. TryConstMerge(hp1, hp2) then
  3046. { Now try to merge the two words (hp2 will get deleted) }
  3047. TryConstMerge(p, hp1);
  3048. end;
  3049. S_L:
  3050. begin
  3051. { Though this only really benefits x86_64 and not i386, it
  3052. gets a potential optimisation done faster and hence
  3053. reduces the number of times OptPass1MOV is entered }
  3054. if GetNextInstruction(p, hp1) and
  3055. MatchInstruction(hp1, A_MOV, [S_W]) and
  3056. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3057. GetNextInstruction(hp1, hp2) and
  3058. MatchInstruction(hp2, A_MOV, [S_W]) and
  3059. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3060. { Try to merge the two words }
  3061. TryConstMerge(hp1, hp2) then
  3062. { This will always fail on i386, so don't bother
  3063. calling it unless we're doing x86_64 }
  3064. {$ifdef x86_64}
  3065. { Now try to merge the two longwords (hp2 will get deleted) }
  3066. TryConstMerge(p, hp1)
  3067. {$endif x86_64}
  3068. ;
  3069. end;
  3070. else
  3071. ;
  3072. end;
  3073. Exit;
  3074. end;
  3075. if (taicpu(p).oper[1]^.typ = top_reg) and
  3076. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3077. begin
  3078. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3079. TransferUsedRegs(TmpUsedRegs);
  3080. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3081. { we have
  3082. mov x, %treg
  3083. mov %treg, y
  3084. }
  3085. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3086. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3087. { we've got
  3088. mov x, %treg
  3089. mov %treg, y
  3090. with %treg is not used after }
  3091. case taicpu(p).oper[0]^.typ Of
  3092. { top_reg is covered by DeepMOVOpt }
  3093. top_const:
  3094. begin
  3095. { change
  3096. mov const, %treg
  3097. mov %treg, y
  3098. to
  3099. mov const, y
  3100. }
  3101. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3102. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3103. begin
  3104. if taicpu(hp1).oper[1]^.typ=top_reg then
  3105. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3106. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3107. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3108. RemoveInstruction(hp1);
  3109. Result:=true;
  3110. Exit;
  3111. end;
  3112. end;
  3113. top_ref:
  3114. case taicpu(hp1).oper[1]^.typ of
  3115. top_reg:
  3116. begin
  3117. { change
  3118. mov mem, %treg
  3119. mov %treg, %reg
  3120. to
  3121. mov mem, %reg"
  3122. }
  3123. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3124. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3125. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3126. RemoveInstruction(hp1);
  3127. Result:=true;
  3128. Exit;
  3129. end;
  3130. top_ref:
  3131. begin
  3132. {$ifdef x86_64}
  3133. { Look for the following to simplify:
  3134. mov x(mem1), %reg
  3135. mov %reg, y(mem2)
  3136. mov x+8(mem1), %reg
  3137. mov %reg, y+8(mem2)
  3138. Change to:
  3139. movdqu x(mem1), %xmmreg
  3140. movdqu %xmmreg, y(mem2)
  3141. ...but only as long as the memory blocks don't overlap
  3142. }
  3143. SourceRef := taicpu(p).oper[0]^.ref^;
  3144. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3145. if (taicpu(p).opsize = S_Q) and
  3146. GetNextInstruction(hp1, hp2) and
  3147. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3148. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3149. begin
  3150. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3151. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3152. Inc(SourceRef.offset, 8);
  3153. if UseAVX then
  3154. begin
  3155. MovAligned := A_VMOVDQA;
  3156. MovUnaligned := A_VMOVDQU;
  3157. end
  3158. else
  3159. begin
  3160. MovAligned := A_MOVDQA;
  3161. MovUnaligned := A_MOVDQU;
  3162. end;
  3163. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3164. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3165. begin
  3166. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3167. Inc(TargetRef.offset, 8);
  3168. if GetNextInstruction(hp2, hp3) and
  3169. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3170. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3171. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3172. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3173. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3174. begin
  3175. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3176. if NewMMReg <> NR_NO then
  3177. begin
  3178. { Remember that the offsets are 8 ahead }
  3179. if ((SourceRef.offset mod 16) = 8) and
  3180. (
  3181. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3182. (SourceRef.base = current_procinfo.framepointer) or
  3183. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3184. ) then
  3185. taicpu(p).opcode := MovAligned
  3186. else
  3187. taicpu(p).opcode := MovUnaligned;
  3188. taicpu(p).opsize := S_XMM;
  3189. taicpu(p).oper[1]^.reg := NewMMReg;
  3190. if ((TargetRef.offset mod 16) = 8) and
  3191. (
  3192. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3193. (TargetRef.base = current_procinfo.framepointer) or
  3194. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3195. ) then
  3196. taicpu(hp1).opcode := MovAligned
  3197. else
  3198. taicpu(hp1).opcode := MovUnaligned;
  3199. taicpu(hp1).opsize := S_XMM;
  3200. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3201. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3202. RemoveInstruction(hp2);
  3203. RemoveInstruction(hp3);
  3204. Result := True;
  3205. Exit;
  3206. end;
  3207. end;
  3208. end
  3209. else
  3210. begin
  3211. { See if the next references are 8 less rather than 8 greater }
  3212. Dec(SourceRef.offset, 16); { -8 the other way }
  3213. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3214. begin
  3215. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3216. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3217. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3218. GetNextInstruction(hp2, hp3) and
  3219. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3220. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3221. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3222. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3223. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3224. begin
  3225. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3226. if NewMMReg <> NR_NO then
  3227. begin
  3228. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3229. if ((SourceRef.offset mod 16) = 0) and
  3230. (
  3231. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3232. (SourceRef.base = current_procinfo.framepointer) or
  3233. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3234. ) then
  3235. taicpu(hp2).opcode := MovAligned
  3236. else
  3237. taicpu(hp2).opcode := MovUnaligned;
  3238. taicpu(hp2).opsize := S_XMM;
  3239. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3240. if ((TargetRef.offset mod 16) = 0) and
  3241. (
  3242. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3243. (TargetRef.base = current_procinfo.framepointer) or
  3244. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3245. ) then
  3246. taicpu(hp3).opcode := MovAligned
  3247. else
  3248. taicpu(hp3).opcode := MovUnaligned;
  3249. taicpu(hp3).opsize := S_XMM;
  3250. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3251. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3252. RemoveInstruction(hp1);
  3253. RemoveCurrentP(p, hp2);
  3254. Result := True;
  3255. Exit;
  3256. end;
  3257. end;
  3258. end;
  3259. end;
  3260. end;
  3261. {$endif x86_64}
  3262. end;
  3263. else
  3264. { The write target should be a reg or a ref }
  3265. InternalError(2021091601);
  3266. end;
  3267. else
  3268. ;
  3269. end
  3270. else
  3271. { %treg is used afterwards, but all eventualities
  3272. other than the first MOV instruction being a constant
  3273. are covered by DeepMOVOpt, so only check for that }
  3274. if (taicpu(p).oper[0]^.typ = top_const) and
  3275. (
  3276. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3277. not (cs_opt_size in current_settings.optimizerswitches) or
  3278. (taicpu(hp1).opsize = S_B)
  3279. ) and
  3280. (
  3281. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3282. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3283. ) then
  3284. begin
  3285. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3286. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3287. end;
  3288. end;
  3289. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3290. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3291. { mov reg1, mem1 or mov mem1, reg1
  3292. mov mem2, reg2 mov reg2, mem2}
  3293. begin
  3294. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3295. { mov reg1, mem1 or mov mem1, reg1
  3296. mov mem2, reg1 mov reg2, mem1}
  3297. begin
  3298. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3299. { Removes the second statement from
  3300. mov reg1, mem1/reg2
  3301. mov mem1/reg2, reg1 }
  3302. begin
  3303. if taicpu(p).oper[0]^.typ=top_reg then
  3304. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3305. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3306. RemoveInstruction(hp1);
  3307. Result:=true;
  3308. exit;
  3309. end
  3310. else
  3311. begin
  3312. TransferUsedRegs(TmpUsedRegs);
  3313. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3314. if (taicpu(p).oper[1]^.typ = top_ref) and
  3315. { mov reg1, mem1
  3316. mov mem2, reg1 }
  3317. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3320. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3321. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3322. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3323. { change to
  3324. mov reg1, mem1 mov reg1, mem1
  3325. mov mem2, reg1 cmp reg1, mem2
  3326. cmp mem1, reg1
  3327. }
  3328. begin
  3329. RemoveInstruction(hp2);
  3330. taicpu(hp1).opcode := A_CMP;
  3331. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3332. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3333. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3334. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3335. end;
  3336. end;
  3337. end
  3338. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3339. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3340. begin
  3341. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3342. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3343. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3344. end
  3345. else
  3346. begin
  3347. TransferUsedRegs(TmpUsedRegs);
  3348. if GetNextInstruction(hp1, hp2) and
  3349. MatchOpType(taicpu(p),top_ref,top_reg) and
  3350. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3351. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3352. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3353. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3354. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3355. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3356. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3357. { mov mem1, %reg1
  3358. mov %reg1, mem2
  3359. mov mem2, reg2
  3360. to:
  3361. mov mem1, reg2
  3362. mov reg2, mem2}
  3363. begin
  3364. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3365. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3366. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3367. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3368. RemoveInstruction(hp2);
  3369. Result := True;
  3370. end
  3371. {$ifdef i386}
  3372. { this is enabled for i386 only, as the rules to create the reg sets below
  3373. are too complicated for x86-64, so this makes this code too error prone
  3374. on x86-64
  3375. }
  3376. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3377. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3378. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3379. { mov mem1, reg1 mov mem1, reg1
  3380. mov reg1, mem2 mov reg1, mem2
  3381. mov mem2, reg2 mov mem2, reg1
  3382. to: to:
  3383. mov mem1, reg1 mov mem1, reg1
  3384. mov mem1, reg2 mov reg1, mem2
  3385. mov reg1, mem2
  3386. or (if mem1 depends on reg1
  3387. and/or if mem2 depends on reg2)
  3388. to:
  3389. mov mem1, reg1
  3390. mov reg1, mem2
  3391. mov reg1, reg2
  3392. }
  3393. begin
  3394. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3395. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3396. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3397. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3398. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3399. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3400. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3401. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3402. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3403. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3404. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3405. end
  3406. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3407. begin
  3408. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3409. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3410. end
  3411. else
  3412. begin
  3413. RemoveInstruction(hp2);
  3414. end
  3415. {$endif i386}
  3416. ;
  3417. end;
  3418. end
  3419. { movl [mem1],reg1
  3420. movl [mem1],reg2
  3421. to
  3422. movl [mem1],reg1
  3423. movl reg1,reg2
  3424. }
  3425. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3426. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3427. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3428. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3429. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3430. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3431. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3432. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3433. begin
  3434. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3435. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3436. end;
  3437. { movl const1,[mem1]
  3438. movl [mem1],reg1
  3439. to
  3440. movl const1,reg1
  3441. movl reg1,[mem1]
  3442. }
  3443. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3444. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3445. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3446. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3447. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3448. begin
  3449. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3450. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3451. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3452. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3453. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3454. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3455. Result:=true;
  3456. exit;
  3457. end;
  3458. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3459. { Change:
  3460. movl %reg1,%reg2
  3461. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3462. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3463. To:
  3464. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3465. movl x(%reg1),%reg1
  3466. movl %reg1,%regX
  3467. }
  3468. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3469. begin
  3470. p_SourceReg := taicpu(p).oper[0]^.reg;
  3471. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3472. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3473. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3474. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3475. GetNextInstruction(hp1, hp2) and
  3476. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3477. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3478. begin
  3479. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3480. if RegInRef(p_TargetReg, SourceRef) and
  3481. { If %reg1 also appears in the second reference, then it will
  3482. not refer to the same memory block as the first reference }
  3483. not RegInRef(p_SourceReg, SourceRef) then
  3484. begin
  3485. { Check to see if the references match if %reg2 is changed to %reg1 }
  3486. if SourceRef.base = p_TargetReg then
  3487. SourceRef.base := p_SourceReg;
  3488. if SourceRef.index = p_TargetReg then
  3489. SourceRef.index := p_SourceReg;
  3490. { RefsEqual also checks to ensure both references are non-volatile }
  3491. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3492. begin
  3493. taicpu(hp2).loadreg(0, p_SourceReg);
  3494. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3495. Result := True;
  3496. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3497. begin
  3498. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3499. RemoveCurrentP(p, hp1);
  3500. Exit;
  3501. end
  3502. else
  3503. begin
  3504. { Check to see if %reg2 is no longer in use }
  3505. TransferUsedRegs(TmpUsedRegs);
  3506. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3507. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3508. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3509. begin
  3510. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3511. RemoveCurrentP(p, hp1);
  3512. Exit;
  3513. end;
  3514. end;
  3515. { If we reach this point, p and hp1 weren't actually modified,
  3516. so we can do a bit more work on this pass }
  3517. end;
  3518. end;
  3519. end;
  3520. end;
  3521. end;
  3522. { search further than the next instruction for a mov (as long as it's not a jump) }
  3523. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3524. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3525. (taicpu(p).oper[1]^.typ = top_reg) and
  3526. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3527. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3528. begin
  3529. { we work with hp2 here, so hp1 can be still used later on when
  3530. checking for GetNextInstruction_p }
  3531. hp3 := hp1;
  3532. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3533. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3534. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3535. TransferUsedRegs(TmpUsedRegs);
  3536. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3537. if NotFirstIteration then
  3538. JumpTracking := TLinkedList.Create
  3539. else
  3540. JumpTracking := nil;
  3541. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3542. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3543. (hp2.typ=ait_instruction) do
  3544. begin
  3545. case taicpu(hp2).opcode of
  3546. A_POP:
  3547. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3548. begin
  3549. if not CrossJump and
  3550. not RegUsedBetween(p_TargetReg, p, hp2) then
  3551. begin
  3552. { We can remove the original MOV since the register
  3553. wasn't used between it and its popping from the stack }
  3554. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3555. RemoveCurrentp(p, hp1);
  3556. Result := True;
  3557. JumpTracking.Free;
  3558. Exit;
  3559. end;
  3560. { Can't go any further }
  3561. Break;
  3562. end;
  3563. A_MOV:
  3564. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3565. ((taicpu(p).oper[0]^.typ=top_const) or
  3566. ((taicpu(p).oper[0]^.typ=top_reg) and
  3567. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3568. )
  3569. ) then
  3570. begin
  3571. { we have
  3572. mov x, %treg
  3573. mov %treg, y
  3574. }
  3575. { We don't need to call UpdateUsedRegs for every instruction between
  3576. p and hp2 because the register we're concerned about will not
  3577. become deallocated (otherwise GetNextInstructionUsingReg would
  3578. have stopped at an earlier instruction). [Kit] }
  3579. TempRegUsed :=
  3580. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3581. RegReadByInstruction(p_TargetReg, hp3) or
  3582. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3583. case taicpu(p).oper[0]^.typ Of
  3584. top_reg:
  3585. begin
  3586. { change
  3587. mov %reg, %treg
  3588. mov %treg, y
  3589. to
  3590. mov %reg, y
  3591. }
  3592. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3593. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3594. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3595. begin
  3596. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3597. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3598. if TempRegUsed then
  3599. begin
  3600. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3601. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3602. { Set the start of the next GetNextInstructionUsingRegCond search
  3603. to start at the entry right before hp2 (which is about to be removed) }
  3604. hp3 := tai(hp2.Previous);
  3605. RemoveInstruction(hp2);
  3606. { See if there's more we can optimise }
  3607. Continue;
  3608. end
  3609. else
  3610. begin
  3611. RemoveInstruction(hp2);
  3612. { We can remove the original MOV too }
  3613. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3614. RemoveCurrentP(p, hp1);
  3615. Result:=true;
  3616. JumpTracking.Free;
  3617. Exit;
  3618. end;
  3619. end
  3620. else
  3621. begin
  3622. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3623. taicpu(hp2).loadReg(0, p_SourceReg);
  3624. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3625. { Check to see if the register also appears in the reference }
  3626. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3627. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3628. { Don't remove the first instruction if the temporary register is in use }
  3629. if not TempRegUsed and
  3630. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3631. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3632. begin
  3633. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3634. RemoveCurrentP(p, hp1);
  3635. Result:=true;
  3636. JumpTracking.Free;
  3637. Exit;
  3638. end;
  3639. { No need to set Result to True here. If there's another instruction later
  3640. on that can be optimised, it will be detected when the main Pass 1 loop
  3641. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3642. end;
  3643. end;
  3644. top_const:
  3645. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3646. begin
  3647. { change
  3648. mov const, %treg
  3649. mov %treg, y
  3650. to
  3651. mov const, y
  3652. }
  3653. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3654. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3655. begin
  3656. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3657. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3658. if TempRegUsed then
  3659. begin
  3660. { Don't remove the first instruction if the temporary register is in use }
  3661. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3662. { No need to set Result to True. If there's another instruction later on
  3663. that can be optimised, it will be detected when the main Pass 1 loop
  3664. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3665. end
  3666. else
  3667. begin
  3668. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3669. RemoveCurrentP(p, hp1);
  3670. Result:=true;
  3671. Exit;
  3672. end;
  3673. end;
  3674. end;
  3675. else
  3676. Internalerror(2019103001);
  3677. end;
  3678. end
  3679. else
  3680. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3681. begin
  3682. if not CrossJump and
  3683. not RegUsedBetween(p_TargetReg, p, hp2) and
  3684. not RegReadByInstruction(p_TargetReg, hp2) then
  3685. begin
  3686. { Register is not used before it is overwritten }
  3687. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3688. RemoveCurrentp(p, hp1);
  3689. Result := True;
  3690. Exit;
  3691. end;
  3692. if (taicpu(p).oper[0]^.typ = top_const) and
  3693. (taicpu(hp2).oper[0]^.typ = top_const) then
  3694. begin
  3695. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3696. begin
  3697. { Same value - register hasn't changed }
  3698. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3699. RemoveInstruction(hp2);
  3700. Result := True;
  3701. { See if there's more we can optimise }
  3702. Continue;
  3703. end;
  3704. end;
  3705. end;
  3706. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3707. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3708. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3709. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3710. begin
  3711. {
  3712. Change from:
  3713. mov ###, %reg
  3714. ...
  3715. movs/z %reg,%reg (Same register, just different sizes)
  3716. To:
  3717. movs/z ###, %reg (Longer version)
  3718. ...
  3719. (remove)
  3720. }
  3721. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3722. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3723. { Keep the first instruction as mov if ### is a constant }
  3724. if taicpu(p).oper[0]^.typ = top_const then
  3725. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3726. else
  3727. begin
  3728. taicpu(p).opcode := taicpu(hp2).opcode;
  3729. taicpu(p).opsize := taicpu(hp2).opsize;
  3730. end;
  3731. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3732. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3733. RemoveInstruction(hp2);
  3734. Result := True;
  3735. JumpTracking.Free;
  3736. Exit;
  3737. end;
  3738. else
  3739. { Move down to the MatchOpType if-block below };
  3740. end;
  3741. { Also catches MOV/S/Z instructions that aren't modified }
  3742. if taicpu(p).oper[0]^.typ = top_reg then
  3743. begin
  3744. p_SourceReg := taicpu(p).oper[0]^.reg;
  3745. if
  3746. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3747. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3748. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3749. begin
  3750. Result := True;
  3751. { Just in case something didn't get modified (e.g. an
  3752. implicit register). Also, if it does read from this
  3753. register, then there's no longer an advantage to
  3754. changing the register on subsequent instructions.}
  3755. if not RegReadByInstruction(p_TargetReg, hp2) then
  3756. begin
  3757. { If a conditional jump was crossed, do not delete
  3758. the original MOV no matter what }
  3759. if not CrossJump and
  3760. { RegEndOfLife returns True if the register is
  3761. deallocated before the next instruction or has
  3762. been loaded with a new value }
  3763. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3764. begin
  3765. { We can remove the original MOV }
  3766. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3767. RemoveCurrentp(p, hp1);
  3768. JumpTracking.Free;
  3769. Result := True;
  3770. Exit;
  3771. end;
  3772. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3773. begin
  3774. { See if there's more we can optimise }
  3775. hp3 := hp2;
  3776. Continue;
  3777. end;
  3778. end;
  3779. end;
  3780. end;
  3781. { Break out of the while loop under normal circumstances }
  3782. Break;
  3783. end;
  3784. JumpTracking.Free;
  3785. end;
  3786. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3787. (taicpu(p).oper[1]^.typ = top_reg) and
  3788. (taicpu(p).opsize = S_L) and
  3789. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3790. (taicpu(hp2).opcode = A_AND) and
  3791. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3792. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3793. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3794. ) then
  3795. begin
  3796. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3797. begin
  3798. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3799. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3800. begin
  3801. { Optimize out:
  3802. mov x, %reg
  3803. and ffffffffh, %reg
  3804. }
  3805. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3806. RemoveInstruction(hp2);
  3807. Result:=true;
  3808. exit;
  3809. end;
  3810. end;
  3811. end;
  3812. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3813. x >= RetOffset) as it doesn't do anything (it writes either to a
  3814. parameter or to the temporary storage room for the function
  3815. result)
  3816. }
  3817. if IsExitCode(hp1) and
  3818. (taicpu(p).oper[1]^.typ = top_ref) and
  3819. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3820. (
  3821. (
  3822. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3823. not (
  3824. assigned(current_procinfo.procdef.funcretsym) and
  3825. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3826. )
  3827. ) or
  3828. { Also discard writes to the stack that are below the base pointer,
  3829. as this is temporary storage rather than a function result on the
  3830. stack, say. }
  3831. (
  3832. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3833. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3834. )
  3835. ) then
  3836. begin
  3837. RemoveCurrentp(p, hp1);
  3838. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3839. RemoveLastDeallocForFuncRes(p);
  3840. Result:=true;
  3841. exit;
  3842. end;
  3843. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3844. begin
  3845. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3846. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3847. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3848. begin
  3849. { change
  3850. mov reg1, mem1
  3851. test/cmp x, mem1
  3852. to
  3853. mov reg1, mem1
  3854. test/cmp x, reg1
  3855. }
  3856. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3857. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3858. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3859. Result := True;
  3860. Exit;
  3861. end;
  3862. if DoMovCmpMemOpt(p, hp1, True) then
  3863. begin
  3864. Result := True;
  3865. Exit;
  3866. end;
  3867. end;
  3868. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3869. { If the flags register is in use, don't change the instruction to an
  3870. ADD otherwise this will scramble the flags. [Kit] }
  3871. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3872. begin
  3873. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3874. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3875. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3876. ) or
  3877. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3878. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3879. )
  3880. ) then
  3881. { mov reg1,ref
  3882. lea reg2,[reg1,reg2]
  3883. to
  3884. add reg2,ref}
  3885. begin
  3886. TransferUsedRegs(TmpUsedRegs);
  3887. { reg1 may not be used afterwards }
  3888. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3889. begin
  3890. Taicpu(hp1).opcode:=A_ADD;
  3891. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3892. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3893. RemoveCurrentp(p, hp1);
  3894. result:=true;
  3895. exit;
  3896. end;
  3897. end;
  3898. { If the LEA instruction can be converted into an arithmetic instruction,
  3899. it may be possible to then fold it in the next optimisation, otherwise
  3900. there's nothing more that can be optimised here. }
  3901. if not ConvertLEA(taicpu(hp1)) then
  3902. Exit;
  3903. end;
  3904. if (taicpu(p).oper[1]^.typ = top_reg) and
  3905. (hp1.typ = ait_instruction) and
  3906. GetNextInstruction(hp1, hp2) and
  3907. MatchInstruction(hp2,A_MOV,[]) and
  3908. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3909. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3910. (
  3911. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3912. {$ifdef x86_64}
  3913. or
  3914. (
  3915. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3916. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3917. )
  3918. {$endif x86_64}
  3919. ) then
  3920. begin
  3921. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3922. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3923. { change movsX/movzX reg/ref, reg2
  3924. add/sub/or/... reg3/$const, reg2
  3925. mov reg2 reg/ref
  3926. dealloc reg2
  3927. to
  3928. add/sub/or/... reg3/$const, reg/ref }
  3929. begin
  3930. TransferUsedRegs(TmpUsedRegs);
  3931. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3932. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3933. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3934. begin
  3935. { by example:
  3936. movswl %si,%eax movswl %si,%eax p
  3937. decl %eax addl %edx,%eax hp1
  3938. movw %ax,%si movw %ax,%si hp2
  3939. ->
  3940. movswl %si,%eax movswl %si,%eax p
  3941. decw %eax addw %edx,%eax hp1
  3942. movw %ax,%si movw %ax,%si hp2
  3943. }
  3944. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3945. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3946. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3947. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3948. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3949. {
  3950. ->
  3951. movswl %si,%eax movswl %si,%eax p
  3952. decw %si addw %dx,%si hp1
  3953. movw %ax,%si movw %ax,%si hp2
  3954. }
  3955. case taicpu(hp1).ops of
  3956. 1:
  3957. begin
  3958. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3959. if taicpu(hp1).oper[0]^.typ=top_reg then
  3960. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3961. end;
  3962. 2:
  3963. begin
  3964. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3965. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3966. (taicpu(hp1).opcode<>A_SHL) and
  3967. (taicpu(hp1).opcode<>A_SHR) and
  3968. (taicpu(hp1).opcode<>A_SAR) then
  3969. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3970. end;
  3971. else
  3972. internalerror(2008042701);
  3973. end;
  3974. {
  3975. ->
  3976. decw %si addw %dx,%si p
  3977. }
  3978. RemoveInstruction(hp2);
  3979. RemoveCurrentP(p, hp1);
  3980. Result:=True;
  3981. Exit;
  3982. end;
  3983. end;
  3984. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3985. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3986. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3987. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3988. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3989. )
  3990. {$ifdef i386}
  3991. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3992. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3993. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3994. {$endif i386}
  3995. then
  3996. { change movsX/movzX reg/ref, reg2
  3997. add/sub/or/... regX/$const, reg2
  3998. mov reg2, reg3
  3999. dealloc reg2
  4000. to
  4001. movsX/movzX reg/ref, reg3
  4002. add/sub/or/... reg3/$const, reg3
  4003. }
  4004. begin
  4005. TransferUsedRegs(TmpUsedRegs);
  4006. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4007. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4008. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4009. begin
  4010. { by example:
  4011. movswl %si,%eax movswl %si,%eax p
  4012. decl %eax addl %edx,%eax hp1
  4013. movw %ax,%si movw %ax,%si hp2
  4014. ->
  4015. movswl %si,%eax movswl %si,%eax p
  4016. decw %eax addw %edx,%eax hp1
  4017. movw %ax,%si movw %ax,%si hp2
  4018. }
  4019. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4020. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4021. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4022. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4023. { limit size of constants as well to avoid assembler errors, but
  4024. check opsize to avoid overflow when left shifting the 1 }
  4025. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4026. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4027. {$ifdef x86_64}
  4028. { Be careful of, for example:
  4029. movl %reg1,%reg2
  4030. addl %reg3,%reg2
  4031. movq %reg2,%reg4
  4032. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4033. }
  4034. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4035. begin
  4036. taicpu(hp2).changeopsize(S_L);
  4037. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4038. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4039. end;
  4040. {$endif x86_64}
  4041. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4042. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4043. if taicpu(p).oper[0]^.typ=top_reg then
  4044. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4045. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4046. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4047. {
  4048. ->
  4049. movswl %si,%eax movswl %si,%eax p
  4050. decw %si addw %dx,%si hp1
  4051. movw %ax,%si movw %ax,%si hp2
  4052. }
  4053. case taicpu(hp1).ops of
  4054. 1:
  4055. begin
  4056. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4057. if taicpu(hp1).oper[0]^.typ=top_reg then
  4058. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4059. end;
  4060. 2:
  4061. begin
  4062. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4063. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4064. (taicpu(hp1).opcode<>A_SHL) and
  4065. (taicpu(hp1).opcode<>A_SHR) and
  4066. (taicpu(hp1).opcode<>A_SAR) then
  4067. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4068. end;
  4069. else
  4070. internalerror(2018111801);
  4071. end;
  4072. {
  4073. ->
  4074. decw %si addw %dx,%si p
  4075. }
  4076. RemoveInstruction(hp2);
  4077. end;
  4078. end;
  4079. end;
  4080. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4081. GetNextInstruction(hp1, hp2) and
  4082. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4083. MatchOperand(Taicpu(p).oper[0]^,0) and
  4084. (Taicpu(p).oper[1]^.typ = top_reg) and
  4085. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4086. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4087. { mov reg1,0
  4088. bts reg1,operand1 --> mov reg1,operand2
  4089. or reg1,operand2 bts reg1,operand1}
  4090. begin
  4091. Taicpu(hp2).opcode:=A_MOV;
  4092. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4093. asml.remove(hp1);
  4094. insertllitem(hp2,hp2.next,hp1);
  4095. RemoveCurrentp(p, hp1);
  4096. Result:=true;
  4097. exit;
  4098. end;
  4099. {
  4100. mov ref,reg0
  4101. <op> reg0,reg1
  4102. dealloc reg0
  4103. to
  4104. <op> ref,reg1
  4105. }
  4106. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4107. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4108. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4109. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4110. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4111. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4112. begin
  4113. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4114. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4115. RemoveCurrentp(p, hp1);
  4116. Result:=true;
  4117. exit;
  4118. end;
  4119. {$ifdef x86_64}
  4120. { Convert:
  4121. movq x(ref),%reg64
  4122. shrq y,%reg64
  4123. To:
  4124. movl x+4(ref),%reg32
  4125. shrl y-32,%reg32 (Remove if y = 32)
  4126. }
  4127. if (taicpu(p).opsize = S_Q) and
  4128. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4129. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4130. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4131. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4132. (taicpu(hp1).oper[0]^.val >= 32) and
  4133. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4134. begin
  4135. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4136. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4137. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4138. { Convert to 32-bit }
  4139. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4140. taicpu(p).opsize := S_L;
  4141. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4142. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4143. if (taicpu(hp1).oper[0]^.val = 32) then
  4144. begin
  4145. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4146. RemoveInstruction(hp1);
  4147. end
  4148. else
  4149. begin
  4150. { This will potentially open up more arithmetic operations since
  4151. the peephole optimizer now has a big hint that only the lower
  4152. 32 bits are currently in use (and opcodes are smaller in size) }
  4153. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4154. taicpu(hp1).opsize := S_L;
  4155. Dec(taicpu(hp1).oper[0]^.val, 32);
  4156. DebugMsg(SPeepholeOptimization + PreMessage +
  4157. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4158. end;
  4159. Result := True;
  4160. Exit;
  4161. end;
  4162. {$endif x86_64}
  4163. { Backward optimisation. If we have:
  4164. func. %reg1,%reg2
  4165. mov %reg2,%reg3
  4166. (dealloc %reg2)
  4167. Change to:
  4168. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4169. }
  4170. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4171. begin
  4172. p_SourceReg := taicpu(p).oper[0]^.reg;
  4173. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4174. TransferUsedRegs(TmpUsedRegs);
  4175. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4176. GetLastInstruction(p, hp2) and
  4177. (hp2.typ = ait_instruction) and
  4178. { Have to make sure it's an instruction that only reads from
  4179. operand 1 and only writes (not reads or modifies) from operand 2;
  4180. in essence, a one-operand pure function such as BSR or POPCNT }
  4181. (taicpu(hp2).ops = 2) and
  4182. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4183. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4184. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4185. begin
  4186. case taicpu(hp2).opcode of
  4187. A_FSTSW, A_FNSTSW,
  4188. A_IN, A_INS, A_OUT, A_OUTS,
  4189. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4190. { These routines have explicit operands, but they are restricted in
  4191. what they can be (e.g. IN and OUT can only read from AL, AX or
  4192. EAX. }
  4193. ;
  4194. else
  4195. begin
  4196. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4197. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4198. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4199. RemoveCurrentp(p, hp1);
  4200. Result := True;
  4201. Exit;
  4202. end;
  4203. end;
  4204. end;
  4205. end;
  4206. end;
  4207. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4208. var
  4209. hp1 : tai;
  4210. begin
  4211. Result:=false;
  4212. if taicpu(p).ops <> 2 then
  4213. exit;
  4214. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4215. GetNextInstruction(p,hp1) then
  4216. begin
  4217. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4218. (taicpu(hp1).ops = 2) then
  4219. begin
  4220. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4221. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4222. { movXX reg1, mem1 or movXX mem1, reg1
  4223. movXX mem2, reg2 movXX reg2, mem2}
  4224. begin
  4225. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4226. { movXX reg1, mem1 or movXX mem1, reg1
  4227. movXX mem2, reg1 movXX reg2, mem1}
  4228. begin
  4229. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4230. begin
  4231. { Removes the second statement from
  4232. movXX reg1, mem1/reg2
  4233. movXX mem1/reg2, reg1
  4234. }
  4235. if taicpu(p).oper[0]^.typ=top_reg then
  4236. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4237. { Removes the second statement from
  4238. movXX mem1/reg1, reg2
  4239. movXX reg2, mem1/reg1
  4240. }
  4241. if (taicpu(p).oper[1]^.typ=top_reg) and
  4242. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4243. begin
  4244. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4245. RemoveInstruction(hp1);
  4246. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4247. Result:=true;
  4248. exit;
  4249. end
  4250. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4251. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4252. begin
  4253. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4254. RemoveInstruction(hp1);
  4255. Result:=true;
  4256. exit;
  4257. end;
  4258. end
  4259. end;
  4260. end;
  4261. end;
  4262. end;
  4263. end;
  4264. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4265. var
  4266. hp1 : tai;
  4267. begin
  4268. result:=false;
  4269. { replace
  4270. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4271. MovX %mreg2,%mreg1
  4272. dealloc %mreg2
  4273. by
  4274. <Op>X %mreg2,%mreg1
  4275. ?
  4276. }
  4277. if GetNextInstruction(p,hp1) and
  4278. { we mix single and double opperations here because we assume that the compiler
  4279. generates vmovapd only after double operations and vmovaps only after single operations }
  4280. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4281. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4282. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4283. (taicpu(p).oper[0]^.typ=top_reg) then
  4284. begin
  4285. TransferUsedRegs(TmpUsedRegs);
  4286. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4287. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4288. begin
  4289. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4290. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4291. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4292. RemoveInstruction(hp1);
  4293. result:=true;
  4294. end;
  4295. end;
  4296. end;
  4297. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4298. var
  4299. hp1, p_label, p_dist, hp1_dist: tai;
  4300. JumpLabel, JumpLabel_dist: TAsmLabel;
  4301. FirstValue, SecondValue: TCGInt;
  4302. begin
  4303. Result := False;
  4304. if (taicpu(p).oper[0]^.typ = top_const) and
  4305. (taicpu(p).oper[0]^.val <> -1) then
  4306. begin
  4307. { Convert unsigned maximum constants to -1 to aid optimisation }
  4308. case taicpu(p).opsize of
  4309. S_B:
  4310. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4311. begin
  4312. taicpu(p).oper[0]^.val := -1;
  4313. Result := True;
  4314. Exit;
  4315. end;
  4316. S_W:
  4317. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4318. begin
  4319. taicpu(p).oper[0]^.val := -1;
  4320. Result := True;
  4321. Exit;
  4322. end;
  4323. S_L:
  4324. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4325. begin
  4326. taicpu(p).oper[0]^.val := -1;
  4327. Result := True;
  4328. Exit;
  4329. end;
  4330. {$ifdef x86_64}
  4331. S_Q:
  4332. { Storing anything greater than $7FFFFFFF is not possible so do
  4333. nothing };
  4334. {$endif x86_64}
  4335. else
  4336. InternalError(2021121001);
  4337. end;
  4338. end;
  4339. if GetNextInstruction(p, hp1) and
  4340. TrySwapMovCmp(p, hp1) then
  4341. begin
  4342. Result := True;
  4343. Exit;
  4344. end;
  4345. { Search for:
  4346. test $x,(reg/ref)
  4347. jne @lbl1
  4348. test $y,(reg/ref) (same register or reference)
  4349. jne @lbl1
  4350. Change to:
  4351. test $(x or y),(reg/ref)
  4352. jne @lbl1
  4353. (Note, this doesn't work with je instead of jne)
  4354. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4355. Also search for:
  4356. test $x,(reg/ref)
  4357. je @lbl1
  4358. test $y,(reg/ref)
  4359. je/jne @lbl2
  4360. If (x or y) = x, then the second jump is deterministic
  4361. }
  4362. if (
  4363. (
  4364. (taicpu(p).oper[0]^.typ = top_const) or
  4365. (
  4366. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4367. (taicpu(p).oper[0]^.typ = top_reg) and
  4368. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4369. )
  4370. ) and
  4371. MatchInstruction(hp1, A_JCC, [])
  4372. ) then
  4373. begin
  4374. if (taicpu(p).oper[0]^.typ = top_reg) and
  4375. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4376. FirstValue := -1
  4377. else
  4378. FirstValue := taicpu(p).oper[0]^.val;
  4379. { If we have several test/jne's in a row, it might be the case that
  4380. the second label doesn't go to the same location, but the one
  4381. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4382. so accommodate for this with a while loop.
  4383. }
  4384. hp1_dist := hp1;
  4385. if GetNextInstruction(hp1, p_dist) and
  4386. (p_dist.typ = ait_instruction) and
  4387. (
  4388. (
  4389. (taicpu(p_dist).opcode = A_TEST) and
  4390. (
  4391. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4392. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4393. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4394. )
  4395. ) or
  4396. (
  4397. { cmp 0,%reg = test %reg,%reg }
  4398. (taicpu(p_dist).opcode = A_CMP) and
  4399. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4400. )
  4401. ) and
  4402. { Make sure the destination operands are actually the same }
  4403. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4404. GetNextInstruction(p_dist, hp1_dist) and
  4405. MatchInstruction(hp1_dist, A_JCC, []) then
  4406. begin
  4407. if
  4408. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4409. (
  4410. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4411. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4412. ) then
  4413. SecondValue := -1
  4414. else
  4415. SecondValue := taicpu(p_dist).oper[0]^.val;
  4416. { If both of the TEST constants are identical, delete the second
  4417. TEST that is unnecessary. }
  4418. if (FirstValue = SecondValue) then
  4419. begin
  4420. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4421. RemoveInstruction(p_dist);
  4422. { Don't let the flags register become deallocated and reallocated between the jumps }
  4423. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4424. Result := True;
  4425. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4426. begin
  4427. { Since the second jump's condition is a subset of the first, we
  4428. know it will never branch because the first jump dominates it.
  4429. Get it out of the way now rather than wait for the jump
  4430. optimisations for a speed boost. }
  4431. if IsJumpToLabel(taicpu(hp1_dist)) then
  4432. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4433. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4434. RemoveInstruction(hp1_dist);
  4435. end
  4436. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4437. begin
  4438. { If the inverse of the first condition is a subset of the second,
  4439. the second one will definitely branch if the first one doesn't }
  4440. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4441. MakeUnconditional(taicpu(hp1_dist));
  4442. RemoveDeadCodeAfterJump(hp1_dist);
  4443. end;
  4444. Exit;
  4445. end;
  4446. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4447. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4448. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4449. then the second jump will never branch, so it can also be
  4450. removed regardless of where it goes }
  4451. (
  4452. (FirstValue = -1) or
  4453. (SecondValue = -1) or
  4454. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4455. ) then
  4456. begin
  4457. { Same jump location... can be a register since nothing's changed }
  4458. { If any of the entries are equivalent to test %reg,%reg, then the
  4459. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4460. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4461. if IsJumpToLabel(taicpu(hp1_dist)) then
  4462. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4463. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4464. RemoveInstruction(hp1_dist);
  4465. { Only remove the second test if no jumps or other conditional instructions follow }
  4466. TransferUsedRegs(TmpUsedRegs);
  4467. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4468. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4469. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4470. RemoveInstruction(p_dist);
  4471. Result := True;
  4472. Exit;
  4473. end;
  4474. end;
  4475. end;
  4476. { Search for:
  4477. test %reg,%reg
  4478. j(c1) @lbl1
  4479. ...
  4480. @lbl:
  4481. test %reg,%reg (same register)
  4482. j(c2) @lbl2
  4483. If c2 is a subset of c1, change to:
  4484. test %reg,%reg
  4485. j(c1) @lbl2
  4486. (@lbl1 may become a dead label as a result)
  4487. }
  4488. if (taicpu(p).oper[1]^.typ = top_reg) and
  4489. (taicpu(p).oper[0]^.typ = top_reg) and
  4490. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4491. MatchInstruction(hp1, A_JCC, []) and
  4492. IsJumpToLabel(taicpu(hp1)) then
  4493. begin
  4494. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4495. p_label := nil;
  4496. if Assigned(JumpLabel) then
  4497. p_label := getlabelwithsym(JumpLabel);
  4498. if Assigned(p_label) and
  4499. GetNextInstruction(p_label, p_dist) and
  4500. MatchInstruction(p_dist, A_TEST, []) and
  4501. { It's fine if the second test uses smaller sub-registers }
  4502. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4503. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4504. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4505. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4506. GetNextInstruction(p_dist, hp1_dist) and
  4507. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4508. begin
  4509. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4510. if JumpLabel = JumpLabel_dist then
  4511. { This is an infinite loop }
  4512. Exit;
  4513. { Best optimisation when the first condition is a subset (or equal) of the second }
  4514. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4515. begin
  4516. { Any registers used here will already be allocated }
  4517. if Assigned(JumpLabel_dist) then
  4518. JumpLabel_dist.IncRefs;
  4519. if Assigned(JumpLabel) then
  4520. JumpLabel.DecRefs;
  4521. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4522. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4523. Result := True;
  4524. Exit;
  4525. end;
  4526. end;
  4527. end;
  4528. end;
  4529. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4530. var
  4531. hp1, hp2: tai;
  4532. ActiveReg: TRegister;
  4533. OldOffset: asizeint;
  4534. ThisConst: TCGInt;
  4535. function RegDeallocated: Boolean;
  4536. begin
  4537. TransferUsedRegs(TmpUsedRegs);
  4538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4539. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4540. end;
  4541. begin
  4542. result:=false;
  4543. hp1 := nil;
  4544. { replace
  4545. addX const,%reg1
  4546. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4547. dealloc %reg1
  4548. by
  4549. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4550. }
  4551. if MatchOpType(taicpu(p),top_const,top_reg) then
  4552. begin
  4553. ActiveReg := taicpu(p).oper[1]^.reg;
  4554. { Ensures the entire register was updated }
  4555. if (taicpu(p).opsize >= S_L) and
  4556. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4557. MatchInstruction(hp1,A_LEA,[]) and
  4558. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4559. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4560. (
  4561. { Cover the case where the register in the reference is also the destination register }
  4562. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4563. (
  4564. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4565. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4566. RegDeallocated
  4567. )
  4568. ) then
  4569. begin
  4570. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4571. {$push}
  4572. {$R-}{$Q-}
  4573. { Explicitly disable overflow checking for these offset calculation
  4574. as those do not matter for the final result }
  4575. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4576. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4577. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4578. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4579. {$pop}
  4580. {$ifdef x86_64}
  4581. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4582. begin
  4583. { Overflow; abort }
  4584. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4585. end
  4586. else
  4587. {$endif x86_64}
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4590. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4591. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4592. RemoveCurrentP(p, hp1)
  4593. else
  4594. RemoveCurrentP(p);
  4595. result:=true;
  4596. Exit;
  4597. end;
  4598. end;
  4599. if (
  4600. { Save calling GetNextInstructionUsingReg again }
  4601. Assigned(hp1) or
  4602. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4603. ) and
  4604. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4605. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4606. begin
  4607. if taicpu(hp1).oper[0]^.typ = top_const then
  4608. begin
  4609. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4610. if taicpu(hp1).opcode = A_ADD then
  4611. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4612. else
  4613. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4614. Result := True;
  4615. { Handle any overflows }
  4616. case taicpu(p).opsize of
  4617. S_B:
  4618. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4619. S_W:
  4620. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4621. S_L:
  4622. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4623. {$ifdef x86_64}
  4624. S_Q:
  4625. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4626. { Overflow; abort }
  4627. Result := False
  4628. else
  4629. taicpu(p).oper[0]^.val := ThisConst;
  4630. {$endif x86_64}
  4631. else
  4632. InternalError(2021102610);
  4633. end;
  4634. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4635. if Result then
  4636. begin
  4637. if (taicpu(p).oper[0]^.val < 0) and
  4638. (
  4639. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4640. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4641. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4642. ) then
  4643. begin
  4644. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4645. taicpu(p).opcode := A_SUB;
  4646. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4647. end
  4648. else
  4649. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4650. RemoveInstruction(hp1);
  4651. end;
  4652. end
  4653. else
  4654. begin
  4655. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4656. TransferUsedRegs(TmpUsedRegs);
  4657. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4658. hp2 := p;
  4659. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4660. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4661. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4662. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4663. begin
  4664. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4665. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4666. Asml.Remove(p);
  4667. Asml.InsertAfter(p, hp1);
  4668. p := hp1;
  4669. Result := True;
  4670. end;
  4671. end;
  4672. end;
  4673. end;
  4674. end;
  4675. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4676. var
  4677. hp1: tai;
  4678. ref: Integer;
  4679. saveref: treference;
  4680. Multiple: TCGInt;
  4681. Adjacent: Boolean;
  4682. begin
  4683. Result:=false;
  4684. { play save and throw an error if LEA uses a seg register prefix,
  4685. this is most likely an error somewhere else }
  4686. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4687. internalerror(2022022001);
  4688. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4689. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4690. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4691. (
  4692. { do not mess with leas accessing the stack pointer
  4693. unless it's a null operation }
  4694. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4695. (
  4696. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4697. (taicpu(p).oper[0]^.ref^.offset = 0)
  4698. )
  4699. ) and
  4700. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4701. begin
  4702. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4703. begin
  4704. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4705. begin
  4706. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4707. taicpu(p).oper[1]^.reg);
  4708. InsertLLItem(p.previous,p.next, hp1);
  4709. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4710. p.free;
  4711. p:=hp1;
  4712. end
  4713. else
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4716. RemoveCurrentP(p);
  4717. end;
  4718. Result:=true;
  4719. exit;
  4720. end
  4721. else if (
  4722. { continue to use lea to adjust the stack pointer,
  4723. it is the recommended way, but only if not optimizing for size }
  4724. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4725. (cs_opt_size in current_settings.optimizerswitches)
  4726. ) and
  4727. { If the flags register is in use, don't change the instruction
  4728. to an ADD otherwise this will scramble the flags. [Kit] }
  4729. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4730. ConvertLEA(taicpu(p)) then
  4731. begin
  4732. Result:=true;
  4733. exit;
  4734. end;
  4735. end;
  4736. { Don't optimise if the stack or frame pointer is the destination register }
  4737. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4738. Exit;
  4739. if GetNextInstruction(p,hp1) and
  4740. (hp1.typ=ait_instruction) then
  4741. begin
  4742. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4745. begin
  4746. TransferUsedRegs(TmpUsedRegs);
  4747. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4748. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4749. begin
  4750. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4751. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4752. RemoveInstruction(hp1);
  4753. result:=true;
  4754. exit;
  4755. end;
  4756. end;
  4757. { changes
  4758. lea <ref1>, reg1
  4759. <op> ...,<ref. with reg1>,...
  4760. to
  4761. <op> ...,<ref1>,... }
  4762. { find a reference which uses reg1 }
  4763. 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
  4764. ref:=0
  4765. 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
  4766. ref:=1
  4767. else
  4768. ref:=-1;
  4769. if (ref<>-1) and
  4770. { reg1 must be either the base or the index }
  4771. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4772. begin
  4773. { reg1 can be removed from the reference }
  4774. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4775. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4776. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4777. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4778. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4779. else
  4780. Internalerror(2019111201);
  4781. { check if the can insert all data of the lea into the second instruction }
  4782. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4783. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4784. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4785. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4786. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4787. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4788. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4789. {$ifdef x86_64}
  4790. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4791. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4792. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4793. )
  4794. {$endif x86_64}
  4795. then
  4796. begin
  4797. { reg1 might not used by the second instruction after it is remove from the reference }
  4798. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4799. begin
  4800. TransferUsedRegs(TmpUsedRegs);
  4801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4802. { reg1 is not updated so it might not be used afterwards }
  4803. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4804. begin
  4805. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4806. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4807. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4808. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4809. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4810. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4811. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4812. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4813. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4814. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4815. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4816. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4817. RemoveCurrentP(p, hp1);
  4818. result:=true;
  4819. exit;
  4820. end
  4821. end;
  4822. end;
  4823. { recover }
  4824. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4825. end;
  4826. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4827. if Adjacent or
  4828. { Check further ahead (up to 2 instructions ahead for -O2) }
  4829. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4830. begin
  4831. { Check common LEA/LEA conditions }
  4832. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4833. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4834. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4835. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4836. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4837. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4838. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4839. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4840. (
  4841. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4842. calling it (since it calls GetNextInstruction) }
  4843. Adjacent or
  4844. (
  4845. (
  4846. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4847. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4848. ) and (
  4849. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4850. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4851. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4852. )
  4853. )
  4854. ) then
  4855. begin
  4856. { changes
  4857. lea (regX,scale), reg1
  4858. lea offset(reg1,reg1), reg1
  4859. to
  4860. lea offset(regX,scale*2), reg1
  4861. and
  4862. lea (regX,scale1), reg1
  4863. lea offset(reg1,scale2), reg1
  4864. to
  4865. lea offset(regX,scale1*scale2), reg1
  4866. ... so long as the final scale does not exceed 8
  4867. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4868. }
  4869. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4870. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4871. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4872. (
  4873. (
  4874. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4875. ) or (
  4876. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4877. (
  4878. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4879. (
  4880. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4881. Adjacent or
  4882. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4883. )
  4884. )
  4885. )
  4886. ) and (
  4887. (
  4888. { lea (reg1,scale2), reg1 variant }
  4889. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4890. (
  4891. (
  4892. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4893. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4894. ) or (
  4895. { lea (regX,regX), reg1 variant }
  4896. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4897. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4898. )
  4899. )
  4900. ) or (
  4901. { lea (reg1,reg1), reg1 variant }
  4902. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4903. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4904. )
  4905. ) then
  4906. begin
  4907. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4908. { Make everything homogeneous to make calculations easier }
  4909. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4910. begin
  4911. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4912. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4913. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4914. else
  4915. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4916. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4917. end;
  4918. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4919. begin
  4920. { Just to prevent miscalculations }
  4921. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4922. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4923. else
  4924. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4925. end
  4926. else
  4927. begin
  4928. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4929. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4930. end;
  4931. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4932. RemoveCurrentP(p);
  4933. result:=true;
  4934. exit;
  4935. end
  4936. { changes
  4937. lea offset1(regX), reg1
  4938. lea offset2(reg1), reg1
  4939. to
  4940. lea offset1+offset2(regX), reg1 }
  4941. else if
  4942. (
  4943. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4944. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4945. ) or (
  4946. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4947. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4948. (
  4949. (
  4950. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4951. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4952. ) or (
  4953. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4954. (
  4955. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4956. (
  4957. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4958. (
  4959. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4960. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4961. )
  4962. )
  4963. )
  4964. )
  4965. )
  4966. ) then
  4967. begin
  4968. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4969. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4970. begin
  4971. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4972. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4973. { if the register is used as index and base, we have to increase for base as well
  4974. and adapt base }
  4975. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4976. begin
  4977. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4978. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4979. end;
  4980. end
  4981. else
  4982. begin
  4983. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4984. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4985. end;
  4986. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4987. begin
  4988. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4989. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4990. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4991. end;
  4992. RemoveCurrentP(p);
  4993. result:=true;
  4994. exit;
  4995. end;
  4996. end;
  4997. { Change:
  4998. leal/q $x(%reg1),%reg2
  4999. ...
  5000. shll/q $y,%reg2
  5001. To:
  5002. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5003. }
  5004. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5005. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5006. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5007. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5008. (taicpu(hp1).oper[0]^.val <= 3) then
  5009. begin
  5010. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5011. TransferUsedRegs(TmpUsedRegs);
  5012. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5013. if
  5014. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5015. (this works even if scalefactor is zero) }
  5016. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5017. { Ensure offset doesn't go out of bounds }
  5018. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5019. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5020. (
  5021. (
  5022. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5023. (
  5024. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5025. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5026. (
  5027. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5028. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5029. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5030. )
  5031. )
  5032. ) or (
  5033. (
  5034. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5035. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5036. ) and
  5037. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5038. )
  5039. ) then
  5040. begin
  5041. repeat
  5042. with taicpu(p).oper[0]^.ref^ do
  5043. begin
  5044. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5045. if index = base then
  5046. begin
  5047. if Multiple > 4 then
  5048. { Optimisation will no longer work because resultant
  5049. scale factor will exceed 8 }
  5050. Break;
  5051. base := NR_NO;
  5052. scalefactor := 2;
  5053. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5054. end
  5055. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5056. begin
  5057. { Scale factor only works on the index register }
  5058. index := base;
  5059. base := NR_NO;
  5060. end;
  5061. { For safety }
  5062. if scalefactor <= 1 then
  5063. begin
  5064. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5065. scalefactor := Multiple;
  5066. end
  5067. else
  5068. begin
  5069. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5070. scalefactor := scalefactor * Multiple;
  5071. end;
  5072. offset := offset * Multiple;
  5073. end;
  5074. RemoveInstruction(hp1);
  5075. Result := True;
  5076. Exit;
  5077. { This repeat..until loop exists for the benefit of Break }
  5078. until True;
  5079. end;
  5080. end;
  5081. end;
  5082. end;
  5083. end;
  5084. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5085. var
  5086. hp1 : tai;
  5087. begin
  5088. DoSubAddOpt := False;
  5089. if taicpu(p).oper[0]^.typ <> top_const then
  5090. { Should have been confirmed before calling }
  5091. InternalError(2021102601);
  5092. if GetLastInstruction(p, hp1) and
  5093. (hp1.typ = ait_instruction) and
  5094. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5095. case taicpu(hp1).opcode Of
  5096. A_DEC:
  5097. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5098. begin
  5099. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5100. RemoveInstruction(hp1);
  5101. end;
  5102. A_SUB:
  5103. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5104. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5105. begin
  5106. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5107. RemoveInstruction(hp1);
  5108. end;
  5109. A_ADD:
  5110. begin
  5111. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5112. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5113. begin
  5114. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5115. RemoveInstruction(hp1);
  5116. if (taicpu(p).oper[0]^.val = 0) then
  5117. begin
  5118. hp1 := tai(p.next);
  5119. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5120. if not GetLastInstruction(hp1, p) then
  5121. p := hp1;
  5122. DoSubAddOpt := True;
  5123. end
  5124. end;
  5125. end;
  5126. else
  5127. ;
  5128. end;
  5129. end;
  5130. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5131. begin
  5132. Result := False;
  5133. if UpdateTmpUsedRegs then
  5134. TransferUsedRegs(TmpUsedRegs);
  5135. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5136. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5137. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5138. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5139. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5140. (
  5141. (
  5142. (taicpu(hp1).opcode = A_TEST)
  5143. ) or (
  5144. (taicpu(hp1).opcode = A_CMP) and
  5145. { A sanity check more than anything }
  5146. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5147. )
  5148. ) then
  5149. begin
  5150. { change
  5151. mov mem, %reg
  5152. cmp/test x, %reg / test %reg,%reg
  5153. (reg deallocated)
  5154. to
  5155. cmp/test x, mem / cmp 0, mem
  5156. }
  5157. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5158. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5159. begin
  5160. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5161. if (taicpu(hp1).opcode = A_TEST) and
  5162. (
  5163. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5164. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5165. ) then
  5166. begin
  5167. taicpu(hp1).opcode := A_CMP;
  5168. taicpu(hp1).loadconst(0, 0);
  5169. end;
  5170. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5171. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5172. RemoveCurrentP(p, hp1);
  5173. Result := True;
  5174. Exit;
  5175. end;
  5176. end;
  5177. end;
  5178. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5179. var
  5180. hp2, hp3, hp4, hp5, hp6: tai;
  5181. ThisReg: TRegister;
  5182. JumpLoc: TAsmLabel;
  5183. begin
  5184. Result := False;
  5185. {
  5186. Convert:
  5187. j<c> .L1
  5188. .L2:
  5189. mov 1,reg
  5190. jmp .L3 (or ret, although it might not be a RET yet)
  5191. .L1:
  5192. mov 0,reg
  5193. jmp .L3 (or ret)
  5194. ( As long as .L3 <> .L1 or .L2)
  5195. To:
  5196. mov 0,reg
  5197. set<not(c)> reg
  5198. jmp .L3 (or ret)
  5199. .L2:
  5200. mov 1,reg
  5201. jmp .L3 (or ret)
  5202. .L1:
  5203. mov 0,reg
  5204. jmp .L3 (or ret)
  5205. }
  5206. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5207. Exit;
  5208. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5209. if GetNextInstruction(hp_label, hp2) and
  5210. MatchInstruction(hp2,A_MOV,[]) and
  5211. (taicpu(hp2).oper[0]^.typ = top_const) and
  5212. (
  5213. (
  5214. (taicpu(hp2).oper[1]^.typ = top_reg)
  5215. {$ifdef i386}
  5216. { Under i386, ESI, EDI, EBP and ESP
  5217. don't have an 8-bit representation }
  5218. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5219. {$endif i386}
  5220. ) or (
  5221. {$ifdef i386}
  5222. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5223. {$endif i386}
  5224. (taicpu(hp2).opsize = S_B)
  5225. )
  5226. ) and
  5227. GetNextInstruction(hp2, hp3) and
  5228. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5229. (
  5230. (taicpu(hp3).opcode=A_RET) or
  5231. (
  5232. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5233. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5234. )
  5235. ) and
  5236. GetNextInstruction(hp3, hp4) and
  5237. SkipAligns(hp4, hp4) and
  5238. (hp4.typ=ait_label) and
  5239. (tai_label(hp4).labsym=JumpLoc) and
  5240. (
  5241. not (cs_opt_size in current_settings.optimizerswitches) or
  5242. { If the initial jump is the label's only reference, then it will
  5243. become a dead label if the other conditions are met and hence
  5244. remove at least 2 instructions, including a jump }
  5245. (JumpLoc.getrefs = 1)
  5246. ) and
  5247. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5248. that will be optimised out }
  5249. GetNextInstruction(hp4, hp5) and
  5250. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5251. (taicpu(hp5).oper[0]^.typ = top_const) and
  5252. (
  5253. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5254. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5255. ) and
  5256. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5257. GetNextInstruction(hp5,hp6) and
  5258. (
  5259. (hp6.typ<>ait_label) or
  5260. SkipLabels(hp6, hp6)
  5261. ) and
  5262. (hp6.typ=ait_instruction) then
  5263. begin
  5264. { First, let's look at the two jumps that are hp3 and hp6 }
  5265. if not
  5266. (
  5267. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5268. (
  5269. (taicpu(hp6).opcode=A_RET) or
  5270. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5271. )
  5272. ) then
  5273. { If condition is False, then the JMP/RET instructions matched conventionally }
  5274. begin
  5275. { See if one of the jumps can be instantly converted into a RET }
  5276. if (taicpu(hp3).opcode=A_JMP) then
  5277. begin
  5278. { Reuse hp5 }
  5279. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5280. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5281. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5282. Exit;
  5283. if MatchInstruction(hp5, A_RET, []) then
  5284. begin
  5285. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5286. ConvertJumpToRET(hp3, hp5);
  5287. Result := True;
  5288. end
  5289. else
  5290. Exit;
  5291. end;
  5292. if (taicpu(hp6).opcode=A_JMP) then
  5293. begin
  5294. { Reuse hp5 }
  5295. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5296. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5297. Exit;
  5298. if MatchInstruction(hp5, A_RET, []) then
  5299. begin
  5300. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5301. ConvertJumpToRET(hp6, hp5);
  5302. Result := True;
  5303. end
  5304. else
  5305. Exit;
  5306. end;
  5307. if not
  5308. (
  5309. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5310. (
  5311. (taicpu(hp6).opcode=A_RET) or
  5312. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5313. )
  5314. ) then
  5315. { Still doesn't match }
  5316. Exit;
  5317. end;
  5318. if (taicpu(hp2).oper[0]^.val = 1) then
  5319. begin
  5320. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5321. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5322. end
  5323. else
  5324. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5325. if taicpu(hp2).opsize=S_B then
  5326. begin
  5327. if taicpu(hp2).oper[1]^.typ = top_reg then
  5328. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5329. else
  5330. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5331. hp2 := p;
  5332. end
  5333. else
  5334. begin
  5335. { Will be a register because the size can't be S_B otherwise }
  5336. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5337. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5338. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5339. { Inserting it right before p will guarantee that the flags are also tracked }
  5340. Asml.InsertBefore(hp2, p);
  5341. end;
  5342. taicpu(hp4).condition:=taicpu(p).condition;
  5343. asml.InsertBefore(hp4, hp2);
  5344. JumpLoc.decrefs;
  5345. if taicpu(hp3).opcode = A_JMP then
  5346. begin
  5347. MakeUnconditional(taicpu(p));
  5348. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5349. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5350. end
  5351. else
  5352. begin
  5353. taicpu(p).condition := C_None;
  5354. taicpu(p).opcode := A_RET;
  5355. taicpu(p).clearop(0);
  5356. taicpu(p).ops := 0;
  5357. end;
  5358. if (JumpLoc.getrefs = 0) then
  5359. RemoveDeadCodeAfterJump(hp3);
  5360. Result:=true;
  5361. exit;
  5362. end;
  5363. end;
  5364. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5365. var
  5366. hp1, hp2: tai;
  5367. ActiveReg: TRegister;
  5368. OldOffset: asizeint;
  5369. ThisConst: TCGInt;
  5370. function RegDeallocated: Boolean;
  5371. begin
  5372. TransferUsedRegs(TmpUsedRegs);
  5373. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5374. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5375. end;
  5376. begin
  5377. Result:=false;
  5378. hp1 := nil;
  5379. { replace
  5380. subX const,%reg1
  5381. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5382. dealloc %reg1
  5383. by
  5384. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5385. }
  5386. if MatchOpType(taicpu(p),top_const,top_reg) then
  5387. begin
  5388. ActiveReg := taicpu(p).oper[1]^.reg;
  5389. { Ensures the entire register was updated }
  5390. if (taicpu(p).opsize >= S_L) and
  5391. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5392. MatchInstruction(hp1,A_LEA,[]) and
  5393. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5394. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5395. (
  5396. { Cover the case where the register in the reference is also the destination register }
  5397. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5398. (
  5399. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5400. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5401. RegDeallocated
  5402. )
  5403. ) then
  5404. begin
  5405. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5406. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5407. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5408. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5409. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5410. {$ifdef x86_64}
  5411. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5412. begin
  5413. { Overflow; abort }
  5414. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5415. end
  5416. else
  5417. {$endif x86_64}
  5418. begin
  5419. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5420. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5421. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5422. RemoveCurrentP(p, hp1)
  5423. else
  5424. RemoveCurrentP(p);
  5425. result:=true;
  5426. Exit;
  5427. end;
  5428. end;
  5429. if (
  5430. { Save calling GetNextInstructionUsingReg again }
  5431. Assigned(hp1) or
  5432. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5433. ) and
  5434. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5435. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5436. begin
  5437. if taicpu(hp1).oper[0]^.typ = top_const then
  5438. begin
  5439. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5440. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5441. Result := True;
  5442. { Handle any overflows }
  5443. case taicpu(p).opsize of
  5444. S_B:
  5445. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5446. S_W:
  5447. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5448. S_L:
  5449. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5450. {$ifdef x86_64}
  5451. S_Q:
  5452. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5453. { Overflow; abort }
  5454. Result := False
  5455. else
  5456. taicpu(p).oper[0]^.val := ThisConst;
  5457. {$endif x86_64}
  5458. else
  5459. InternalError(2021102610);
  5460. end;
  5461. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5462. if Result then
  5463. begin
  5464. if (taicpu(p).oper[0]^.val < 0) and
  5465. (
  5466. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5467. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5468. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5469. ) then
  5470. begin
  5471. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5472. taicpu(p).opcode := A_SUB;
  5473. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5474. end
  5475. else
  5476. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5477. RemoveInstruction(hp1);
  5478. end;
  5479. end
  5480. else
  5481. begin
  5482. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5483. TransferUsedRegs(TmpUsedRegs);
  5484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5485. hp2 := p;
  5486. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5487. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5488. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5489. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5490. begin
  5491. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5492. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5493. Asml.Remove(p);
  5494. Asml.InsertAfter(p, hp1);
  5495. p := hp1;
  5496. Result := True;
  5497. Exit;
  5498. end;
  5499. end;
  5500. end;
  5501. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5502. { * change "sub/add const1, reg" or "dec reg" followed by
  5503. "sub const2, reg" to one "sub ..., reg" }
  5504. {$ifdef i386}
  5505. if (taicpu(p).oper[0]^.val = 2) and
  5506. (ActiveReg = NR_ESP) and
  5507. { Don't do the sub/push optimization if the sub }
  5508. { comes from setting up the stack frame (JM) }
  5509. (not(GetLastInstruction(p,hp1)) or
  5510. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5511. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5512. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5513. begin
  5514. hp1 := tai(p.next);
  5515. while Assigned(hp1) and
  5516. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5517. not RegReadByInstruction(NR_ESP,hp1) and
  5518. not RegModifiedByInstruction(NR_ESP,hp1) do
  5519. hp1 := tai(hp1.next);
  5520. if Assigned(hp1) and
  5521. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5522. begin
  5523. taicpu(hp1).changeopsize(S_L);
  5524. if taicpu(hp1).oper[0]^.typ=top_reg then
  5525. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5526. hp1 := tai(p.next);
  5527. RemoveCurrentp(p, hp1);
  5528. Result:=true;
  5529. exit;
  5530. end;
  5531. end;
  5532. {$endif i386}
  5533. if DoSubAddOpt(p) then
  5534. Result:=true;
  5535. end;
  5536. end;
  5537. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5538. var
  5539. TmpBool1,TmpBool2 : Boolean;
  5540. tmpref : treference;
  5541. hp1,hp2: tai;
  5542. mask: tcgint;
  5543. begin
  5544. Result:=false;
  5545. { All these optimisations work on "shl/sal const,%reg" }
  5546. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5547. Exit;
  5548. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5549. (taicpu(p).oper[0]^.val <= 3) then
  5550. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5551. begin
  5552. { should we check the next instruction? }
  5553. TmpBool1 := True;
  5554. { have we found an add/sub which could be
  5555. integrated in the lea? }
  5556. TmpBool2 := False;
  5557. reference_reset(tmpref,2,[]);
  5558. TmpRef.index := taicpu(p).oper[1]^.reg;
  5559. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5560. while TmpBool1 and
  5561. GetNextInstruction(p, hp1) and
  5562. (tai(hp1).typ = ait_instruction) and
  5563. ((((taicpu(hp1).opcode = A_ADD) or
  5564. (taicpu(hp1).opcode = A_SUB)) and
  5565. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5566. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5567. (((taicpu(hp1).opcode = A_INC) or
  5568. (taicpu(hp1).opcode = A_DEC)) and
  5569. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5570. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5571. ((taicpu(hp1).opcode = A_LEA) and
  5572. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5573. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5574. (not GetNextInstruction(hp1,hp2) or
  5575. not instrReadsFlags(hp2)) Do
  5576. begin
  5577. TmpBool1 := False;
  5578. if taicpu(hp1).opcode=A_LEA then
  5579. begin
  5580. if (TmpRef.base = NR_NO) and
  5581. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5582. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5583. { Segment register isn't a concern here }
  5584. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5585. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5586. begin
  5587. TmpBool1 := True;
  5588. TmpBool2 := True;
  5589. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5590. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5591. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5592. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5593. RemoveInstruction(hp1);
  5594. end
  5595. end
  5596. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5597. begin
  5598. TmpBool1 := True;
  5599. TmpBool2 := True;
  5600. case taicpu(hp1).opcode of
  5601. A_ADD:
  5602. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5603. A_SUB:
  5604. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5605. else
  5606. internalerror(2019050536);
  5607. end;
  5608. RemoveInstruction(hp1);
  5609. end
  5610. else
  5611. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5612. (((taicpu(hp1).opcode = A_ADD) and
  5613. (TmpRef.base = NR_NO)) or
  5614. (taicpu(hp1).opcode = A_INC) or
  5615. (taicpu(hp1).opcode = A_DEC)) then
  5616. begin
  5617. TmpBool1 := True;
  5618. TmpBool2 := True;
  5619. case taicpu(hp1).opcode of
  5620. A_ADD:
  5621. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5622. A_INC:
  5623. inc(TmpRef.offset);
  5624. A_DEC:
  5625. dec(TmpRef.offset);
  5626. else
  5627. internalerror(2019050535);
  5628. end;
  5629. RemoveInstruction(hp1);
  5630. end;
  5631. end;
  5632. if TmpBool2
  5633. {$ifndef x86_64}
  5634. or
  5635. ((current_settings.optimizecputype < cpu_Pentium2) and
  5636. (taicpu(p).oper[0]^.val <= 3) and
  5637. not(cs_opt_size in current_settings.optimizerswitches))
  5638. {$endif x86_64}
  5639. then
  5640. begin
  5641. if not(TmpBool2) and
  5642. (taicpu(p).oper[0]^.val=1) then
  5643. begin
  5644. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5645. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5646. end
  5647. else
  5648. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5649. taicpu(p).oper[1]^.reg);
  5650. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5651. InsertLLItem(p.previous, p.next, hp1);
  5652. p.free;
  5653. p := hp1;
  5654. end;
  5655. end
  5656. {$ifndef x86_64}
  5657. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5658. begin
  5659. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5660. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5661. (unlike shl, which is only Tairable in the U pipe) }
  5662. if taicpu(p).oper[0]^.val=1 then
  5663. begin
  5664. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5665. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5666. InsertLLItem(p.previous, p.next, hp1);
  5667. p.free;
  5668. p := hp1;
  5669. end
  5670. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5671. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5672. else if (taicpu(p).opsize = S_L) and
  5673. (taicpu(p).oper[0]^.val<= 3) then
  5674. begin
  5675. reference_reset(tmpref,2,[]);
  5676. TmpRef.index := taicpu(p).oper[1]^.reg;
  5677. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5678. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5679. InsertLLItem(p.previous, p.next, hp1);
  5680. p.free;
  5681. p := hp1;
  5682. end;
  5683. end
  5684. {$endif x86_64}
  5685. else if
  5686. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5687. (
  5688. (
  5689. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5690. SetAndTest(hp1, hp2)
  5691. {$ifdef x86_64}
  5692. ) or
  5693. (
  5694. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5695. GetNextInstruction(hp1, hp2) and
  5696. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5697. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5698. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5699. {$endif x86_64}
  5700. )
  5701. ) and
  5702. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5703. begin
  5704. { Change:
  5705. shl x, %reg1
  5706. mov -(1<<x), %reg2
  5707. and %reg2, %reg1
  5708. Or:
  5709. shl x, %reg1
  5710. and -(1<<x), %reg1
  5711. To just:
  5712. shl x, %reg1
  5713. Since the and operation only zeroes bits that are already zero from the shl operation
  5714. }
  5715. case taicpu(p).oper[0]^.val of
  5716. 8:
  5717. mask:=$FFFFFFFFFFFFFF00;
  5718. 16:
  5719. mask:=$FFFFFFFFFFFF0000;
  5720. 32:
  5721. mask:=$FFFFFFFF00000000;
  5722. 63:
  5723. { Constant pre-calculated to prevent overflow errors with Int64 }
  5724. mask:=$8000000000000000;
  5725. else
  5726. begin
  5727. if taicpu(p).oper[0]^.val >= 64 then
  5728. { Shouldn't happen realistically, since the register
  5729. is guaranteed to be set to zero at this point }
  5730. mask := 0
  5731. else
  5732. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5733. end;
  5734. end;
  5735. if taicpu(hp1).oper[0]^.val = mask then
  5736. begin
  5737. { Everything checks out, perform the optimisation, as long as
  5738. the FLAGS register isn't being used}
  5739. TransferUsedRegs(TmpUsedRegs);
  5740. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5741. {$ifdef x86_64}
  5742. if (hp1 <> hp2) then
  5743. begin
  5744. { "shl/mov/and" version }
  5745. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5746. { Don't do the optimisation if the FLAGS register is in use }
  5747. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5748. begin
  5749. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5750. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5751. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5752. begin
  5753. RemoveInstruction(hp1);
  5754. Result := True;
  5755. end;
  5756. { Only set Result to True if the 'mov' instruction was removed }
  5757. RemoveInstruction(hp2);
  5758. end;
  5759. end
  5760. else
  5761. {$endif x86_64}
  5762. begin
  5763. { "shl/and" version }
  5764. { Don't do the optimisation if the FLAGS register is in use }
  5765. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5766. begin
  5767. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5768. RemoveInstruction(hp1);
  5769. Result := True;
  5770. end;
  5771. end;
  5772. Exit;
  5773. end
  5774. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5775. begin
  5776. { Even if the mask doesn't allow for its removal, we might be
  5777. able to optimise the mask for the "shl/and" version, which
  5778. may permit other peephole optimisations }
  5779. {$ifdef DEBUG_AOPTCPU}
  5780. mask := taicpu(hp1).oper[0]^.val and mask;
  5781. if taicpu(hp1).oper[0]^.val <> mask then
  5782. begin
  5783. DebugMsg(
  5784. SPeepholeOptimization +
  5785. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5786. ' to $' + debug_tostr(mask) +
  5787. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5788. taicpu(hp1).oper[0]^.val := mask;
  5789. end;
  5790. {$else DEBUG_AOPTCPU}
  5791. { If debugging is off, just set the operand even if it's the same }
  5792. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5793. {$endif DEBUG_AOPTCPU}
  5794. end;
  5795. end;
  5796. {
  5797. change
  5798. shl/sal const,reg
  5799. <op> ...(...,reg,1),...
  5800. into
  5801. <op> ...(...,reg,1 shl const),...
  5802. if const in 1..3
  5803. }
  5804. if MatchOpType(taicpu(p), top_const, top_reg) and
  5805. (taicpu(p).oper[0]^.val in [1..3]) and
  5806. GetNextInstruction(p, hp1) and
  5807. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5808. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5809. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5810. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5811. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5812. begin
  5813. TransferUsedRegs(TmpUsedRegs);
  5814. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5815. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5816. begin
  5817. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5818. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5819. RemoveCurrentP(p);
  5820. Result:=true;
  5821. end;
  5822. end;
  5823. end;
  5824. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5825. var
  5826. CurrentRef: TReference;
  5827. FullReg: TRegister;
  5828. hp1, hp2: tai;
  5829. begin
  5830. Result := False;
  5831. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5832. Exit;
  5833. { We assume you've checked if the operand is actually a reference by
  5834. this point. If it isn't, you'll most likely get an access violation }
  5835. CurrentRef := first_mov.oper[1]^.ref^;
  5836. { Memory must be aligned }
  5837. if (CurrentRef.offset mod 4) <> 0 then
  5838. Exit;
  5839. Inc(CurrentRef.offset);
  5840. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5841. if MatchOperand(second_mov.oper[0]^, 0) and
  5842. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5843. GetNextInstruction(second_mov, hp1) and
  5844. (hp1.typ = ait_instruction) and
  5845. (taicpu(hp1).opcode = A_MOV) and
  5846. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5847. (taicpu(hp1).oper[0]^.val = 0) then
  5848. begin
  5849. Inc(CurrentRef.offset);
  5850. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5851. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5852. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5853. begin
  5854. case taicpu(hp1).opsize of
  5855. S_B:
  5856. if GetNextInstruction(hp1, hp2) and
  5857. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5858. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5859. (taicpu(hp2).oper[0]^.val = 0) then
  5860. begin
  5861. Inc(CurrentRef.offset);
  5862. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5863. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5864. (taicpu(hp2).opsize = S_B) then
  5865. begin
  5866. RemoveInstruction(hp1);
  5867. RemoveInstruction(hp2);
  5868. first_mov.opsize := S_L;
  5869. if first_mov.oper[0]^.typ = top_reg then
  5870. begin
  5871. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5872. { Reuse second_mov as a MOVZX instruction }
  5873. second_mov.opcode := A_MOVZX;
  5874. second_mov.opsize := S_BL;
  5875. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5876. second_mov.loadreg(1, FullReg);
  5877. first_mov.oper[0]^.reg := FullReg;
  5878. asml.Remove(second_mov);
  5879. asml.InsertBefore(second_mov, first_mov);
  5880. end
  5881. else
  5882. { It's a value }
  5883. begin
  5884. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5885. RemoveInstruction(second_mov);
  5886. end;
  5887. Result := True;
  5888. Exit;
  5889. end;
  5890. end;
  5891. S_W:
  5892. begin
  5893. RemoveInstruction(hp1);
  5894. first_mov.opsize := S_L;
  5895. if first_mov.oper[0]^.typ = top_reg then
  5896. begin
  5897. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5898. { Reuse second_mov as a MOVZX instruction }
  5899. second_mov.opcode := A_MOVZX;
  5900. second_mov.opsize := S_BL;
  5901. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5902. second_mov.loadreg(1, FullReg);
  5903. first_mov.oper[0]^.reg := FullReg;
  5904. asml.Remove(second_mov);
  5905. asml.InsertBefore(second_mov, first_mov);
  5906. end
  5907. else
  5908. { It's a value }
  5909. begin
  5910. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5911. RemoveInstruction(second_mov);
  5912. end;
  5913. Result := True;
  5914. Exit;
  5915. end;
  5916. else
  5917. ;
  5918. end;
  5919. end;
  5920. end;
  5921. end;
  5922. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5923. { returns true if a "continue" should be done after this optimization }
  5924. var
  5925. hp1, hp2: tai;
  5926. begin
  5927. Result := false;
  5928. if MatchOpType(taicpu(p),top_ref) and
  5929. GetNextInstruction(p, hp1) and
  5930. (hp1.typ = ait_instruction) and
  5931. (((taicpu(hp1).opcode = A_FLD) and
  5932. (taicpu(p).opcode = A_FSTP)) or
  5933. ((taicpu(p).opcode = A_FISTP) and
  5934. (taicpu(hp1).opcode = A_FILD))) and
  5935. MatchOpType(taicpu(hp1),top_ref) and
  5936. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5937. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5938. begin
  5939. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5940. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5941. GetNextInstruction(hp1, hp2) and
  5942. (hp2.typ = ait_instruction) and
  5943. IsExitCode(hp2) and
  5944. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5945. not(assigned(current_procinfo.procdef.funcretsym) and
  5946. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5947. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5948. begin
  5949. RemoveInstruction(hp1);
  5950. RemoveCurrentP(p, hp2);
  5951. RemoveLastDeallocForFuncRes(p);
  5952. Result := true;
  5953. end
  5954. else
  5955. { we can do this only in fast math mode as fstp is rounding ...
  5956. ... still disabled as it breaks the compiler and/or rtl }
  5957. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5958. { ... or if another fstp equal to the first one follows }
  5959. (GetNextInstruction(hp1,hp2) and
  5960. (hp2.typ = ait_instruction) and
  5961. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5962. (taicpu(p).opsize=taicpu(hp2).opsize))
  5963. ) and
  5964. { fst can't store an extended/comp value }
  5965. (taicpu(p).opsize <> S_FX) and
  5966. (taicpu(p).opsize <> S_IQ) then
  5967. begin
  5968. if (taicpu(p).opcode = A_FSTP) then
  5969. taicpu(p).opcode := A_FST
  5970. else
  5971. taicpu(p).opcode := A_FIST;
  5972. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5973. RemoveInstruction(hp1);
  5974. end;
  5975. end;
  5976. end;
  5977. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5978. var
  5979. hp1, hp2: tai;
  5980. begin
  5981. result:=false;
  5982. if MatchOpType(taicpu(p),top_reg) and
  5983. GetNextInstruction(p, hp1) and
  5984. (hp1.typ = Ait_Instruction) and
  5985. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5986. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5987. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5988. { change to
  5989. fld reg fxxx reg,st
  5990. fxxxp st, st1 (hp1)
  5991. Remark: non commutative operations must be reversed!
  5992. }
  5993. begin
  5994. case taicpu(hp1).opcode Of
  5995. A_FMULP,A_FADDP,
  5996. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5997. begin
  5998. case taicpu(hp1).opcode Of
  5999. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6000. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6001. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6002. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6003. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6004. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6005. else
  6006. internalerror(2019050534);
  6007. end;
  6008. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6009. taicpu(hp1).oper[1]^.reg := NR_ST;
  6010. RemoveCurrentP(p, hp1);
  6011. Result:=true;
  6012. exit;
  6013. end;
  6014. else
  6015. ;
  6016. end;
  6017. end
  6018. else
  6019. if MatchOpType(taicpu(p),top_ref) and
  6020. GetNextInstruction(p, hp2) and
  6021. (hp2.typ = Ait_Instruction) and
  6022. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6023. (taicpu(p).opsize in [S_FS, S_FL]) and
  6024. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6025. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6026. if GetLastInstruction(p, hp1) and
  6027. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6028. MatchOpType(taicpu(hp1),top_ref) and
  6029. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6030. if ((taicpu(hp2).opcode = A_FMULP) or
  6031. (taicpu(hp2).opcode = A_FADDP)) then
  6032. { change to
  6033. fld/fst mem1 (hp1) fld/fst mem1
  6034. fld mem1 (p) fadd/
  6035. faddp/ fmul st, st
  6036. fmulp st, st1 (hp2) }
  6037. begin
  6038. RemoveCurrentP(p, hp1);
  6039. if (taicpu(hp2).opcode = A_FADDP) then
  6040. taicpu(hp2).opcode := A_FADD
  6041. else
  6042. taicpu(hp2).opcode := A_FMUL;
  6043. taicpu(hp2).oper[1]^.reg := NR_ST;
  6044. end
  6045. else
  6046. { change to
  6047. fld/fst mem1 (hp1) fld/fst mem1
  6048. fld mem1 (p) fld st}
  6049. begin
  6050. taicpu(p).changeopsize(S_FL);
  6051. taicpu(p).loadreg(0,NR_ST);
  6052. end
  6053. else
  6054. begin
  6055. case taicpu(hp2).opcode Of
  6056. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6057. { change to
  6058. fld/fst mem1 (hp1) fld/fst mem1
  6059. fld mem2 (p) fxxx mem2
  6060. fxxxp st, st1 (hp2) }
  6061. begin
  6062. case taicpu(hp2).opcode Of
  6063. A_FADDP: taicpu(p).opcode := A_FADD;
  6064. A_FMULP: taicpu(p).opcode := A_FMUL;
  6065. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6066. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6067. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6068. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6069. else
  6070. internalerror(2019050533);
  6071. end;
  6072. RemoveInstruction(hp2);
  6073. end
  6074. else
  6075. ;
  6076. end
  6077. end
  6078. end;
  6079. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6080. begin
  6081. Result := condition_in(cond1, cond2) or
  6082. { Not strictly subsets due to the actual flags checked, but because we're
  6083. comparing integers, E is a subset of AE and GE and their aliases }
  6084. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6085. end;
  6086. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6087. var
  6088. v: TCGInt;
  6089. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6090. FirstMatch: Boolean;
  6091. NewReg: TRegister;
  6092. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6093. begin
  6094. Result:=false;
  6095. { All these optimisations need a next instruction }
  6096. if not GetNextInstruction(p, hp1) then
  6097. Exit;
  6098. { Search for:
  6099. cmp ###,###
  6100. j(c1) @lbl1
  6101. ...
  6102. @lbl:
  6103. cmp ###.### (same comparison as above)
  6104. j(c2) @lbl2
  6105. If c1 is a subset of c2, change to:
  6106. cmp ###,###
  6107. j(c2) @lbl2
  6108. (@lbl1 may become a dead label as a result)
  6109. }
  6110. { Also handle cases where there are multiple jumps in a row }
  6111. p_jump := hp1;
  6112. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6113. begin
  6114. if IsJumpToLabel(taicpu(p_jump)) then
  6115. begin
  6116. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6117. p_label := nil;
  6118. if Assigned(JumpLabel) then
  6119. p_label := getlabelwithsym(JumpLabel);
  6120. if Assigned(p_label) and
  6121. GetNextInstruction(p_label, p_dist) and
  6122. MatchInstruction(p_dist, A_CMP, []) and
  6123. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6124. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6125. GetNextInstruction(p_dist, hp1_dist) and
  6126. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6127. begin
  6128. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6129. if JumpLabel = JumpLabel_dist then
  6130. { This is an infinite loop }
  6131. Exit;
  6132. { Best optimisation when the first condition is a subset (or equal) of the second }
  6133. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6134. begin
  6135. { Any registers used here will already be allocated }
  6136. if Assigned(JumpLabel_dist) then
  6137. JumpLabel_dist.IncRefs;
  6138. if Assigned(JumpLabel) then
  6139. JumpLabel.DecRefs;
  6140. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6141. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  6142. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  6143. Result := True;
  6144. { Don't exit yet. Since p and p_jump haven't actually been
  6145. removed, we can check for more on this iteration }
  6146. end
  6147. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6148. GetNextInstruction(hp1_dist, hp1_label) and
  6149. SkipAligns(hp1_label, hp1_label) and
  6150. (hp1_label.typ = ait_label) then
  6151. begin
  6152. JumpLabel_far := tai_label(hp1_label).labsym;
  6153. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6154. { This is an infinite loop }
  6155. Exit;
  6156. if Assigned(JumpLabel_far) then
  6157. begin
  6158. { In this situation, if the first jump branches, the second one will never,
  6159. branch so change the destination label to after the second jump }
  6160. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6161. if Assigned(JumpLabel) then
  6162. JumpLabel.DecRefs;
  6163. JumpLabel_far.IncRefs;
  6164. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6165. Result := True;
  6166. { Don't exit yet. Since p and p_jump haven't actually been
  6167. removed, we can check for more on this iteration }
  6168. Continue;
  6169. end;
  6170. end;
  6171. end;
  6172. end;
  6173. { Search for:
  6174. cmp ###,###
  6175. j(c1) @lbl1
  6176. cmp ###,### (same as first)
  6177. Remove second cmp
  6178. }
  6179. if GetNextInstruction(p_jump, hp2) and
  6180. (
  6181. (
  6182. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6183. (
  6184. (
  6185. MatchOpType(taicpu(p), top_const, top_reg) and
  6186. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6187. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6188. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6189. ) or (
  6190. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6191. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6192. )
  6193. )
  6194. ) or (
  6195. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6196. MatchOperand(taicpu(p).oper[0]^, 0) and
  6197. (taicpu(p).oper[1]^.typ = top_reg) and
  6198. MatchInstruction(hp2, A_TEST, []) and
  6199. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6200. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6201. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6202. )
  6203. ) then
  6204. begin
  6205. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6206. RemoveInstruction(hp2);
  6207. Result := True;
  6208. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6209. end;
  6210. GetNextInstruction(p_jump, p_jump);
  6211. end;
  6212. {
  6213. Try to optimise the following:
  6214. cmp $x,### ($x and $y can be registers or constants)
  6215. je @lbl1 (only reference)
  6216. cmp $y,### (### are identical)
  6217. @Lbl:
  6218. sete %reg1
  6219. Change to:
  6220. cmp $x,###
  6221. sete %reg2 (allocate new %reg2)
  6222. cmp $y,###
  6223. sete %reg1
  6224. orb %reg2,%reg1
  6225. (dealloc %reg2)
  6226. This adds an instruction (so don't perform under -Os), but it removes
  6227. a conditional branch.
  6228. }
  6229. if not (cs_opt_size in current_settings.optimizerswitches) and
  6230. (
  6231. (hp1 = p_jump) or
  6232. GetNextInstruction(p, hp1)
  6233. ) and
  6234. MatchInstruction(hp1, A_Jcc, []) and
  6235. IsJumpToLabel(taicpu(hp1)) and
  6236. (taicpu(hp1).condition in [C_E, C_Z]) and
  6237. GetNextInstruction(hp1, hp2) and
  6238. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6239. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6240. { The first operand of CMP instructions can only be a register or
  6241. immediate anyway, so no need to check }
  6242. GetNextInstruction(hp2, p_label) and
  6243. (p_label.typ = ait_label) and
  6244. (tai_label(p_label).labsym.getrefs = 1) and
  6245. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6246. GetNextInstruction(p_label, p_dist) and
  6247. MatchInstruction(p_dist, A_SETcc, []) and
  6248. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6249. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6250. begin
  6251. TransferUsedRegs(TmpUsedRegs);
  6252. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6253. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6254. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6255. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6256. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6257. { Get the instruction after the SETcc instruction so we can
  6258. allocate a new register over the entire range }
  6259. GetNextInstruction(p_dist, hp1_dist) then
  6260. begin
  6261. { Register can appear in p if it's not used afterwards, so only
  6262. allocate between hp1 and hp1_dist }
  6263. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6264. if NewReg <> NR_NO then
  6265. begin
  6266. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6267. { Change the jump instruction into a SETcc instruction }
  6268. taicpu(hp1).opcode := A_SETcc;
  6269. taicpu(hp1).opsize := S_B;
  6270. taicpu(hp1).loadreg(0, NewReg);
  6271. { This is now a dead label }
  6272. tai_label(p_label).labsym.decrefs;
  6273. { Prefer adding before the next instruction so the FLAGS
  6274. register is deallicated first }
  6275. AsmL.InsertBefore(
  6276. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6277. hp1_dist
  6278. );
  6279. Result := True;
  6280. { Don't exit yet, as p wasn't changed and hp1, while
  6281. modified, is still intact and might be optimised by the
  6282. SETcc optimisation below }
  6283. end;
  6284. end;
  6285. end;
  6286. if taicpu(p).oper[0]^.typ = top_const then
  6287. begin
  6288. if (taicpu(p).oper[0]^.val = 0) and
  6289. (taicpu(p).oper[1]^.typ = top_reg) and
  6290. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6291. begin
  6292. hp2 := p;
  6293. FirstMatch := True;
  6294. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6295. anything meaningful once it's converted to "test %reg,%reg";
  6296. additionally, some jumps will always (or never) branch, so
  6297. evaluate every jump immediately following the
  6298. comparison, optimising the conditions if possible.
  6299. Similarly with SETcc... those that are always set to 0 or 1
  6300. are changed to MOV instructions }
  6301. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6302. (
  6303. GetNextInstruction(hp2, hp1) and
  6304. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6305. ) do
  6306. begin
  6307. FirstMatch := False;
  6308. case taicpu(hp1).condition of
  6309. C_B, C_C, C_NAE, C_O:
  6310. { For B/NAE:
  6311. Will never branch since an unsigned integer can never be below zero
  6312. For C/O:
  6313. Result cannot overflow because 0 is being subtracted
  6314. }
  6315. begin
  6316. if taicpu(hp1).opcode = A_Jcc then
  6317. begin
  6318. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6319. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6320. RemoveInstruction(hp1);
  6321. { Since hp1 was deleted, hp2 must not be updated }
  6322. Continue;
  6323. end
  6324. else
  6325. begin
  6326. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6327. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6328. taicpu(hp1).opcode := A_MOV;
  6329. taicpu(hp1).ops := 2;
  6330. taicpu(hp1).condition := C_None;
  6331. taicpu(hp1).opsize := S_B;
  6332. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6333. taicpu(hp1).loadconst(0, 0);
  6334. end;
  6335. end;
  6336. C_BE, C_NA:
  6337. begin
  6338. { Will only branch if equal to zero }
  6339. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6340. taicpu(hp1).condition := C_E;
  6341. end;
  6342. C_A, C_NBE:
  6343. begin
  6344. { Will only branch if not equal to zero }
  6345. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6346. taicpu(hp1).condition := C_NE;
  6347. end;
  6348. C_AE, C_NB, C_NC, C_NO:
  6349. begin
  6350. { Will always branch }
  6351. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6352. if taicpu(hp1).opcode = A_Jcc then
  6353. begin
  6354. MakeUnconditional(taicpu(hp1));
  6355. { Any jumps/set that follow will now be dead code }
  6356. RemoveDeadCodeAfterJump(taicpu(hp1));
  6357. Break;
  6358. end
  6359. else
  6360. begin
  6361. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6362. taicpu(hp1).opcode := A_MOV;
  6363. taicpu(hp1).ops := 2;
  6364. taicpu(hp1).condition := C_None;
  6365. taicpu(hp1).opsize := S_B;
  6366. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6367. taicpu(hp1).loadconst(0, 1);
  6368. end;
  6369. end;
  6370. C_None:
  6371. InternalError(2020012201);
  6372. C_P, C_PE, C_NP, C_PO:
  6373. { We can't handle parity checks and they should never be generated
  6374. after a general-purpose CMP (it's used in some floating-point
  6375. comparisons that don't use CMP) }
  6376. InternalError(2020012202);
  6377. else
  6378. { Zero/Equality, Sign, their complements and all of the
  6379. signed comparisons do not need to be converted };
  6380. end;
  6381. hp2 := hp1;
  6382. end;
  6383. { Convert the instruction to a TEST }
  6384. taicpu(p).opcode := A_TEST;
  6385. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6386. Result := True;
  6387. Exit;
  6388. end
  6389. else if (taicpu(p).oper[0]^.val = 1) and
  6390. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6391. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6392. begin
  6393. { Convert; To:
  6394. cmp $1,r/m cmp $0,r/m
  6395. jl @lbl jle @lbl
  6396. }
  6397. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6398. taicpu(p).oper[0]^.val := 0;
  6399. taicpu(hp1).condition := C_LE;
  6400. { If the instruction is now "cmp $0,%reg", convert it to a
  6401. TEST (and effectively do the work of the "cmp $0,%reg" in
  6402. the block above)
  6403. If it's a reference, we can get away with not setting
  6404. Result to True because he haven't evaluated the jump
  6405. in this pass yet.
  6406. }
  6407. if (taicpu(p).oper[1]^.typ = top_reg) then
  6408. begin
  6409. taicpu(p).opcode := A_TEST;
  6410. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6411. Result := True;
  6412. end;
  6413. Exit;
  6414. end
  6415. else if (taicpu(p).oper[1]^.typ = top_reg)
  6416. {$ifdef x86_64}
  6417. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6418. {$endif x86_64}
  6419. then
  6420. begin
  6421. { cmp register,$8000 neg register
  6422. je target --> jo target
  6423. .... only if register is deallocated before jump.}
  6424. case Taicpu(p).opsize of
  6425. S_B: v:=$80;
  6426. S_W: v:=$8000;
  6427. S_L: v:=qword($80000000);
  6428. else
  6429. internalerror(2013112905);
  6430. end;
  6431. if (taicpu(p).oper[0]^.val=v) and
  6432. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6433. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6434. begin
  6435. TransferUsedRegs(TmpUsedRegs);
  6436. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6437. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6438. begin
  6439. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6440. Taicpu(p).opcode:=A_NEG;
  6441. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6442. Taicpu(p).clearop(1);
  6443. Taicpu(p).ops:=1;
  6444. if Taicpu(hp1).condition=C_E then
  6445. Taicpu(hp1).condition:=C_O
  6446. else
  6447. Taicpu(hp1).condition:=C_NO;
  6448. Result:=true;
  6449. exit;
  6450. end;
  6451. end;
  6452. end;
  6453. end;
  6454. if TrySwapMovCmp(p, hp1) then
  6455. begin
  6456. Result := True;
  6457. Exit;
  6458. end;
  6459. end;
  6460. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6461. var
  6462. hp1: tai;
  6463. begin
  6464. {
  6465. remove the second (v)pxor from
  6466. pxor reg,reg
  6467. ...
  6468. pxor reg,reg
  6469. }
  6470. Result:=false;
  6471. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6472. MatchOpType(taicpu(p),top_reg,top_reg) and
  6473. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6474. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6475. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6476. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6477. begin
  6478. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6479. RemoveInstruction(hp1);
  6480. Result:=true;
  6481. Exit;
  6482. end
  6483. {
  6484. replace
  6485. pxor reg1,reg1
  6486. movapd/s reg1,reg2
  6487. dealloc reg1
  6488. by
  6489. pxor reg2,reg2
  6490. }
  6491. else if GetNextInstruction(p,hp1) and
  6492. { we mix single and double opperations here because we assume that the compiler
  6493. generates vmovapd only after double operations and vmovaps only after single operations }
  6494. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6495. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6496. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6497. (taicpu(p).oper[0]^.typ=top_reg) then
  6498. begin
  6499. TransferUsedRegs(TmpUsedRegs);
  6500. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6501. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6502. begin
  6503. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6504. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6505. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6506. RemoveInstruction(hp1);
  6507. result:=true;
  6508. end;
  6509. end;
  6510. end;
  6511. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6512. var
  6513. hp1: tai;
  6514. begin
  6515. {
  6516. remove the second (v)pxor from
  6517. (v)pxor reg,reg
  6518. ...
  6519. (v)pxor reg,reg
  6520. }
  6521. Result:=false;
  6522. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6523. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6524. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6525. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6526. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6527. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6528. begin
  6529. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6530. RemoveInstruction(hp1);
  6531. Result:=true;
  6532. Exit;
  6533. end
  6534. else
  6535. Result:=OptPass1VOP(p);
  6536. end;
  6537. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6538. var
  6539. hp1 : tai;
  6540. begin
  6541. result:=false;
  6542. { replace
  6543. IMul const,%mreg1,%mreg2
  6544. Mov %reg2,%mreg3
  6545. dealloc %mreg3
  6546. by
  6547. Imul const,%mreg1,%mreg23
  6548. }
  6549. if (taicpu(p).ops=3) and
  6550. GetNextInstruction(p,hp1) and
  6551. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6552. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6553. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6554. begin
  6555. TransferUsedRegs(TmpUsedRegs);
  6556. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6557. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6558. begin
  6559. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6560. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6561. RemoveInstruction(hp1);
  6562. result:=true;
  6563. end;
  6564. end;
  6565. end;
  6566. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6567. var
  6568. hp1 : tai;
  6569. begin
  6570. result:=false;
  6571. { replace
  6572. IMul %reg0,%reg1,%reg2
  6573. Mov %reg2,%reg3
  6574. dealloc %reg2
  6575. by
  6576. Imul %reg0,%reg1,%reg3
  6577. }
  6578. if GetNextInstruction(p,hp1) and
  6579. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6580. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6581. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6582. begin
  6583. TransferUsedRegs(TmpUsedRegs);
  6584. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6585. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6586. begin
  6587. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6588. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6589. RemoveInstruction(hp1);
  6590. result:=true;
  6591. end;
  6592. end;
  6593. end;
  6594. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6595. var
  6596. hp1: tai;
  6597. begin
  6598. Result:=false;
  6599. { get rid of
  6600. (v)cvtss2sd reg0,<reg1,>reg2
  6601. (v)cvtss2sd reg2,<reg2,>reg0
  6602. }
  6603. if GetNextInstruction(p,hp1) and
  6604. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6605. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6606. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6607. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6608. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6609. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6610. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6611. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6612. )
  6613. ) then
  6614. begin
  6615. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6616. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6617. begin
  6618. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6619. RemoveCurrentP(p);
  6620. RemoveInstruction(hp1);
  6621. end
  6622. else
  6623. begin
  6624. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6625. if taicpu(hp1).opcode=A_CVTSD2SS then
  6626. begin
  6627. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6628. taicpu(p).opcode:=A_MOVAPS;
  6629. end
  6630. else
  6631. begin
  6632. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6633. taicpu(p).opcode:=A_VMOVAPS;
  6634. end;
  6635. taicpu(p).ops:=2;
  6636. RemoveInstruction(hp1);
  6637. end;
  6638. Result:=true;
  6639. Exit;
  6640. end;
  6641. end;
  6642. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6643. var
  6644. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6645. ThisReg: TRegister;
  6646. begin
  6647. Result := False;
  6648. if not GetNextInstruction(p,hp1) then
  6649. Exit;
  6650. {
  6651. convert
  6652. j<c> .L1
  6653. mov 1,reg
  6654. jmp .L2
  6655. .L1
  6656. mov 0,reg
  6657. .L2
  6658. into
  6659. mov 0,reg
  6660. set<not(c)> reg
  6661. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6662. would destroy the flag contents
  6663. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6664. executed at the same time as a previous comparison.
  6665. set<not(c)> reg
  6666. movzx reg, reg
  6667. }
  6668. if MatchInstruction(hp1,A_MOV,[]) and
  6669. (taicpu(hp1).oper[0]^.typ = top_const) and
  6670. (
  6671. (
  6672. (taicpu(hp1).oper[1]^.typ = top_reg)
  6673. {$ifdef i386}
  6674. { Under i386, ESI, EDI, EBP and ESP
  6675. don't have an 8-bit representation }
  6676. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6677. {$endif i386}
  6678. ) or (
  6679. {$ifdef i386}
  6680. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6681. {$endif i386}
  6682. (taicpu(hp1).opsize = S_B)
  6683. )
  6684. ) and
  6685. GetNextInstruction(hp1,hp2) and
  6686. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6687. GetNextInstruction(hp2,hp3) and
  6688. SkipAligns(hp3, hp3) and
  6689. (hp3.typ=ait_label) and
  6690. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6691. GetNextInstruction(hp3,hp4) and
  6692. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6693. (taicpu(hp4).oper[0]^.typ = top_const) and
  6694. (
  6695. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6696. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6697. ) and
  6698. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6699. GetNextInstruction(hp4,hp5) and
  6700. SkipAligns(hp5, hp5) and
  6701. (hp5.typ=ait_label) and
  6702. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6703. begin
  6704. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6705. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6706. tai_label(hp3).labsym.DecRefs;
  6707. { If this isn't the only reference to the middle label, we can
  6708. still make a saving - only that the first jump and everything
  6709. that follows will remain. }
  6710. if (tai_label(hp3).labsym.getrefs = 0) then
  6711. begin
  6712. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6713. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6714. else
  6715. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6716. { remove jump, first label and second MOV (also catching any aligns) }
  6717. repeat
  6718. if not GetNextInstruction(hp2, hp3) then
  6719. InternalError(2021040810);
  6720. RemoveInstruction(hp2);
  6721. hp2 := hp3;
  6722. until hp2 = hp5;
  6723. { Don't decrement reference count before the removal loop
  6724. above, otherwise GetNextInstruction won't stop on the
  6725. the label }
  6726. tai_label(hp5).labsym.DecRefs;
  6727. end
  6728. else
  6729. begin
  6730. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6731. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6732. else
  6733. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6734. end;
  6735. taicpu(p).opcode:=A_SETcc;
  6736. taicpu(p).opsize:=S_B;
  6737. taicpu(p).is_jmp:=False;
  6738. if taicpu(hp1).opsize=S_B then
  6739. begin
  6740. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6741. if taicpu(hp1).oper[1]^.typ = top_reg then
  6742. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6743. RemoveInstruction(hp1);
  6744. end
  6745. else
  6746. begin
  6747. { Will be a register because the size can't be S_B otherwise }
  6748. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6749. taicpu(p).loadreg(0, ThisReg);
  6750. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6751. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6752. begin
  6753. case taicpu(hp1).opsize of
  6754. S_W:
  6755. taicpu(hp1).opsize := S_BW;
  6756. S_L:
  6757. taicpu(hp1).opsize := S_BL;
  6758. {$ifdef x86_64}
  6759. S_Q:
  6760. begin
  6761. taicpu(hp1).opsize := S_BL;
  6762. { Change the destination register to 32-bit }
  6763. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6764. end;
  6765. {$endif x86_64}
  6766. else
  6767. InternalError(2021040820);
  6768. end;
  6769. taicpu(hp1).opcode := A_MOVZX;
  6770. taicpu(hp1).loadreg(0, ThisReg);
  6771. end
  6772. else
  6773. begin
  6774. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6775. { hp1 is already a MOV instruction with the correct register }
  6776. taicpu(hp1).loadconst(0, 0);
  6777. { Inserting it right before p will guarantee that the flags are also tracked }
  6778. asml.Remove(hp1);
  6779. asml.InsertBefore(hp1, p);
  6780. end;
  6781. end;
  6782. Result:=true;
  6783. exit;
  6784. end
  6785. else if (hp1.typ = ait_label) then
  6786. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6787. end;
  6788. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6789. var
  6790. hp1, hp2, hp3: tai;
  6791. SourceRef, TargetRef: TReference;
  6792. CurrentReg: TRegister;
  6793. begin
  6794. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6795. if not UseAVX then
  6796. InternalError(2021100501);
  6797. Result := False;
  6798. { Look for the following to simplify:
  6799. vmovdqa/u x(mem1), %xmmreg
  6800. vmovdqa/u %xmmreg, y(mem2)
  6801. vmovdqa/u x+16(mem1), %xmmreg
  6802. vmovdqa/u %xmmreg, y+16(mem2)
  6803. Change to:
  6804. vmovdqa/u x(mem1), %ymmreg
  6805. vmovdqa/u %ymmreg, y(mem2)
  6806. vpxor %ymmreg, %ymmreg, %ymmreg
  6807. ( The VPXOR instruction is to zero the upper half, thus removing the
  6808. need to call the potentially expensive VZEROUPPER instruction. Other
  6809. peephole optimisations can remove VPXOR if it's unnecessary )
  6810. }
  6811. TransferUsedRegs(TmpUsedRegs);
  6812. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6813. { NOTE: In the optimisations below, if the references dictate that an
  6814. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6815. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6816. if (taicpu(p).opsize = S_XMM) and
  6817. MatchOpType(taicpu(p), top_ref, top_reg) and
  6818. GetNextInstruction(p, hp1) and
  6819. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6820. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6821. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6822. begin
  6823. SourceRef := taicpu(p).oper[0]^.ref^;
  6824. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6825. if GetNextInstruction(hp1, hp2) and
  6826. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6827. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6828. begin
  6829. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6830. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6831. Inc(SourceRef.offset, 16);
  6832. { Reuse the register in the first block move }
  6833. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6834. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6835. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6836. begin
  6837. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6838. Inc(TargetRef.offset, 16);
  6839. if GetNextInstruction(hp2, hp3) and
  6840. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6841. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6842. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6843. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6844. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6845. begin
  6846. { Update the register tracking to the new size }
  6847. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6848. { Remember that the offsets are 16 ahead }
  6849. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6850. if not (
  6851. ((SourceRef.offset mod 32) = 16) and
  6852. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6853. ) then
  6854. taicpu(p).opcode := A_VMOVDQU;
  6855. taicpu(p).opsize := S_YMM;
  6856. taicpu(p).oper[1]^.reg := CurrentReg;
  6857. if not (
  6858. ((TargetRef.offset mod 32) = 16) and
  6859. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6860. ) then
  6861. taicpu(hp1).opcode := A_VMOVDQU;
  6862. taicpu(hp1).opsize := S_YMM;
  6863. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6864. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6865. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6866. if (pi_uses_ymm in current_procinfo.flags) then
  6867. RemoveInstruction(hp2)
  6868. else
  6869. begin
  6870. taicpu(hp2).opcode := A_VPXOR;
  6871. taicpu(hp2).opsize := S_YMM;
  6872. taicpu(hp2).loadreg(0, CurrentReg);
  6873. taicpu(hp2).loadreg(1, CurrentReg);
  6874. taicpu(hp2).loadreg(2, CurrentReg);
  6875. taicpu(hp2).ops := 3;
  6876. end;
  6877. RemoveInstruction(hp3);
  6878. Result := True;
  6879. Exit;
  6880. end;
  6881. end
  6882. else
  6883. begin
  6884. { See if the next references are 16 less rather than 16 greater }
  6885. Dec(SourceRef.offset, 32); { -16 the other way }
  6886. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6887. begin
  6888. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6889. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6890. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6891. GetNextInstruction(hp2, hp3) and
  6892. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6893. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6894. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6895. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6896. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6897. begin
  6898. { Update the register tracking to the new size }
  6899. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6900. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6901. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6902. if not(
  6903. ((SourceRef.offset mod 32) = 0) and
  6904. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6905. ) then
  6906. taicpu(hp2).opcode := A_VMOVDQU;
  6907. taicpu(hp2).opsize := S_YMM;
  6908. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6909. if not (
  6910. ((TargetRef.offset mod 32) = 0) and
  6911. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6912. ) then
  6913. taicpu(hp3).opcode := A_VMOVDQU;
  6914. taicpu(hp3).opsize := S_YMM;
  6915. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6916. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6917. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6918. if (pi_uses_ymm in current_procinfo.flags) then
  6919. RemoveInstruction(hp1)
  6920. else
  6921. begin
  6922. taicpu(hp1).opcode := A_VPXOR;
  6923. taicpu(hp1).opsize := S_YMM;
  6924. taicpu(hp1).loadreg(0, CurrentReg);
  6925. taicpu(hp1).loadreg(1, CurrentReg);
  6926. taicpu(hp1).loadreg(2, CurrentReg);
  6927. taicpu(hp1).ops := 3;
  6928. Asml.Remove(hp1);
  6929. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6930. end;
  6931. RemoveCurrentP(p, hp2);
  6932. Result := True;
  6933. Exit;
  6934. end;
  6935. end;
  6936. end;
  6937. end;
  6938. end;
  6939. end;
  6940. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6941. var
  6942. hp2, hp3, first_assignment: tai;
  6943. IncCount, OperIdx: Integer;
  6944. OrigLabel: TAsmLabel;
  6945. begin
  6946. Count := 0;
  6947. Result := False;
  6948. first_assignment := nil;
  6949. if (LoopCount >= 20) then
  6950. begin
  6951. { Guard against infinite loops }
  6952. Exit;
  6953. end;
  6954. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6955. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6956. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6957. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6958. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6959. Exit;
  6960. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6961. {
  6962. change
  6963. jmp .L1
  6964. ...
  6965. .L1:
  6966. mov ##, ## ( multiple movs possible )
  6967. jmp/ret
  6968. into
  6969. mov ##, ##
  6970. jmp/ret
  6971. }
  6972. if not Assigned(hp1) then
  6973. begin
  6974. hp1 := GetLabelWithSym(OrigLabel);
  6975. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6976. Exit;
  6977. end;
  6978. hp2 := hp1;
  6979. while Assigned(hp2) do
  6980. begin
  6981. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6982. SkipLabels(hp2,hp2);
  6983. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6984. Break;
  6985. case taicpu(hp2).opcode of
  6986. A_MOVSS:
  6987. begin
  6988. if taicpu(hp2).ops = 0 then
  6989. { Wrong MOVSS }
  6990. Break;
  6991. Inc(Count);
  6992. if Count >= 5 then
  6993. { Too many to be worthwhile }
  6994. Break;
  6995. GetNextInstruction(hp2, hp2);
  6996. Continue;
  6997. end;
  6998. A_MOV,
  6999. A_MOVD,
  7000. A_MOVQ,
  7001. A_MOVSX,
  7002. {$ifdef x86_64}
  7003. A_MOVSXD,
  7004. {$endif x86_64}
  7005. A_MOVZX,
  7006. A_MOVAPS,
  7007. A_MOVUPS,
  7008. A_MOVSD,
  7009. A_MOVAPD,
  7010. A_MOVUPD,
  7011. A_MOVDQA,
  7012. A_MOVDQU,
  7013. A_VMOVSS,
  7014. A_VMOVAPS,
  7015. A_VMOVUPS,
  7016. A_VMOVSD,
  7017. A_VMOVAPD,
  7018. A_VMOVUPD,
  7019. A_VMOVDQA,
  7020. A_VMOVDQU:
  7021. begin
  7022. Inc(Count);
  7023. if Count >= 5 then
  7024. { Too many to be worthwhile }
  7025. Break;
  7026. GetNextInstruction(hp2, hp2);
  7027. Continue;
  7028. end;
  7029. A_JMP:
  7030. begin
  7031. { Guard against infinite loops }
  7032. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7033. Exit;
  7034. { Analyse this jump first in case it also duplicates assignments }
  7035. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7036. begin
  7037. { Something did change! }
  7038. Result := True;
  7039. Inc(Count, IncCount);
  7040. if Count >= 5 then
  7041. begin
  7042. { Too many to be worthwhile }
  7043. Exit;
  7044. end;
  7045. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7046. Break;
  7047. end;
  7048. Result := True;
  7049. Break;
  7050. end;
  7051. A_RET:
  7052. begin
  7053. Result := True;
  7054. Break;
  7055. end;
  7056. else
  7057. Break;
  7058. end;
  7059. end;
  7060. if Result then
  7061. begin
  7062. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7063. if Count = 0 then
  7064. begin
  7065. Result := False;
  7066. Exit;
  7067. end;
  7068. hp3 := p;
  7069. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7070. while True do
  7071. begin
  7072. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7073. SkipLabels(hp1,hp1);
  7074. if (hp1.typ <> ait_instruction) then
  7075. InternalError(2021040720);
  7076. case taicpu(hp1).opcode of
  7077. A_JMP:
  7078. begin
  7079. { Change the original jump to the new destination }
  7080. OrigLabel.decrefs;
  7081. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7082. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7083. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7084. if not Assigned(first_assignment) then
  7085. InternalError(2021040810)
  7086. else
  7087. p := first_assignment;
  7088. Exit;
  7089. end;
  7090. A_RET:
  7091. begin
  7092. { Now change the jump into a RET instruction }
  7093. ConvertJumpToRET(p, hp1);
  7094. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7095. if not Assigned(first_assignment) then
  7096. InternalError(2021040811)
  7097. else
  7098. p := first_assignment;
  7099. Exit;
  7100. end;
  7101. else
  7102. begin
  7103. { Duplicate the MOV instruction }
  7104. hp3:=tai(hp1.getcopy);
  7105. if first_assignment = nil then
  7106. first_assignment := hp3;
  7107. asml.InsertBefore(hp3, p);
  7108. { Make sure the compiler knows about any final registers written here }
  7109. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7110. with taicpu(hp3).oper[OperIdx]^ do
  7111. begin
  7112. case typ of
  7113. top_ref:
  7114. begin
  7115. if (ref^.base <> NR_NO) and
  7116. (getsupreg(ref^.base) <> RS_ESP) and
  7117. (getsupreg(ref^.base) <> RS_EBP)
  7118. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7119. then
  7120. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7121. if (ref^.index <> NR_NO) and
  7122. (getsupreg(ref^.index) <> RS_ESP) and
  7123. (getsupreg(ref^.index) <> RS_EBP)
  7124. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7125. (ref^.index <> ref^.base) then
  7126. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7127. end;
  7128. top_reg:
  7129. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7130. else
  7131. ;
  7132. end;
  7133. end;
  7134. end;
  7135. end;
  7136. if not GetNextInstruction(hp1, hp1) then
  7137. { Should have dropped out earlier }
  7138. InternalError(2021040710);
  7139. end;
  7140. end;
  7141. end;
  7142. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7143. var
  7144. hp2: tai;
  7145. X: Integer;
  7146. const
  7147. WriteOp: array[0..3] of set of TInsChange = (
  7148. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7149. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7150. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7151. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7152. RegWriteFlags: array[0..7] of set of TInsChange = (
  7153. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7154. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7155. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7156. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7157. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7158. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7159. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7160. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7161. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7162. begin
  7163. { If we have something like:
  7164. cmp ###,%reg1
  7165. mov 0,%reg2
  7166. And no modified registers are shared, move the instruction to before
  7167. the comparison as this means it can be optimised without worrying
  7168. about the FLAGS register. (CMP/MOV is generated by
  7169. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7170. As long as the second instruction doesn't use the flags or one of the
  7171. registers used by CMP or TEST (also check any references that use the
  7172. registers), then it can be moved prior to the comparison.
  7173. }
  7174. Result := False;
  7175. if (hp1.typ <> ait_instruction) or
  7176. taicpu(hp1).is_jmp or
  7177. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7178. Exit;
  7179. { NOP is a pipeline fence, likely marking the beginning of the function
  7180. epilogue, so drop out. Similarly, drop out if POP or RET are
  7181. encountered }
  7182. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7183. Exit;
  7184. if (taicpu(hp1).opcode = A_MOVSS) and
  7185. (taicpu(hp1).ops = 0) then
  7186. { Wrong MOVSS }
  7187. Exit;
  7188. { Check for writes to specific registers first }
  7189. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7190. for X := 0 to 7 do
  7191. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7192. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7193. Exit;
  7194. for X := 0 to taicpu(hp1).ops - 1 do
  7195. begin
  7196. { Check to see if this operand writes to something }
  7197. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7198. { And matches something in the CMP/TEST instruction }
  7199. (
  7200. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7201. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7202. (
  7203. { If it's a register, make sure the register written to doesn't
  7204. appear in the cmp instruction as part of a reference }
  7205. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7206. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7207. )
  7208. ) then
  7209. Exit;
  7210. end;
  7211. { The instruction can be safely moved }
  7212. asml.Remove(hp1);
  7213. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  7214. if not GetLastInstruction(p, hp2) then
  7215. asml.InsertBefore(hp1, p)
  7216. else
  7217. asml.InsertAfter(hp1, hp2);
  7218. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7219. for X := 0 to taicpu(hp1).ops - 1 do
  7220. case taicpu(hp1).oper[X]^.typ of
  7221. top_reg:
  7222. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7223. top_ref:
  7224. begin
  7225. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7226. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7227. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7228. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7229. end;
  7230. else
  7231. ;
  7232. end;
  7233. if taicpu(hp1).opcode = A_LEA then
  7234. { The flags will be overwritten by the CMP/TEST instruction }
  7235. ConvertLEA(taicpu(hp1));
  7236. Result := True;
  7237. end;
  7238. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7239. function IsXCHGAcceptable: Boolean; inline;
  7240. begin
  7241. { Always accept if optimising for size }
  7242. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7243. (
  7244. {$ifdef x86_64}
  7245. { XCHG takes 3 cycles on AMD Athlon64 }
  7246. (current_settings.optimizecputype >= cpu_core_i)
  7247. {$else x86_64}
  7248. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7249. than 3, so it becomes a saving compared to three MOVs with two of
  7250. them able to execute simultaneously. [Kit] }
  7251. (current_settings.optimizecputype >= cpu_PentiumM)
  7252. {$endif x86_64}
  7253. );
  7254. end;
  7255. var
  7256. NewRef: TReference;
  7257. hp1, hp2, hp3, hp4: Tai;
  7258. {$ifndef x86_64}
  7259. OperIdx: Integer;
  7260. {$endif x86_64}
  7261. NewInstr : Taicpu;
  7262. NewAligh : Tai_align;
  7263. DestLabel: TAsmLabel;
  7264. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7265. var
  7266. NextInstr: tai;
  7267. begin
  7268. Result := False;
  7269. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7270. if not GetNextInstruction(InputInstr, NextInstr) or
  7271. (
  7272. { The FLAGS register isn't always tracked properly, so do not
  7273. perform this optimisation if a conditional statement follows }
  7274. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7275. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7276. ) then
  7277. begin
  7278. reference_reset(NewRef, 1, []);
  7279. NewRef.base := taicpu(p).oper[0]^.reg;
  7280. NewRef.scalefactor := 1;
  7281. if taicpu(InputInstr).opcode = A_ADD then
  7282. begin
  7283. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7284. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7285. end
  7286. else
  7287. begin
  7288. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7289. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7290. end;
  7291. taicpu(p).opcode := A_LEA;
  7292. taicpu(p).loadref(0, NewRef);
  7293. RemoveInstruction(InputInstr);
  7294. Result := True;
  7295. end;
  7296. end;
  7297. begin
  7298. Result:=false;
  7299. { This optimisation adds an instruction, so only do it for speed }
  7300. if not (cs_opt_size in current_settings.optimizerswitches) and
  7301. MatchOpType(taicpu(p), top_const, top_reg) and
  7302. (taicpu(p).oper[0]^.val = 0) then
  7303. begin
  7304. { To avoid compiler warning }
  7305. DestLabel := nil;
  7306. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7307. InternalError(2021040750);
  7308. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7309. Exit;
  7310. case hp1.typ of
  7311. ait_label:
  7312. begin
  7313. { Change:
  7314. mov $0,%reg mov $0,%reg
  7315. @Lbl1: @Lbl1:
  7316. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7317. je @Lbl2 jne @Lbl2
  7318. To: To:
  7319. mov $0,%reg mov $0,%reg
  7320. jmp @Lbl2 jmp @Lbl3
  7321. (align) (align)
  7322. @Lbl1: @Lbl1:
  7323. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7324. je @Lbl2 je @Lbl2
  7325. @Lbl3: <-- Only if label exists
  7326. (Not if it's optimised for size)
  7327. }
  7328. if not GetNextInstruction(hp1, hp2) then
  7329. Exit;
  7330. if not (cs_opt_size in current_settings.optimizerswitches) and
  7331. (hp2.typ = ait_instruction) and
  7332. (
  7333. { Register sizes must exactly match }
  7334. (
  7335. (taicpu(hp2).opcode = A_CMP) and
  7336. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7337. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7338. ) or (
  7339. (taicpu(hp2).opcode = A_TEST) and
  7340. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7341. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7342. )
  7343. ) and GetNextInstruction(hp2, hp3) and
  7344. (hp3.typ = ait_instruction) and
  7345. (taicpu(hp3).opcode = A_JCC) and
  7346. (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
  7347. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7348. begin
  7349. { Check condition of jump }
  7350. { Always true? }
  7351. if condition_in(C_E, taicpu(hp3).condition) then
  7352. begin
  7353. { Copy label symbol and obtain matching label entry for the
  7354. conditional jump, as this will be our destination}
  7355. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7356. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7357. Result := True;
  7358. end
  7359. { Always false? }
  7360. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7361. begin
  7362. { This is only worth it if there's a jump to take }
  7363. case hp2.typ of
  7364. ait_instruction:
  7365. begin
  7366. if taicpu(hp2).opcode = A_JMP then
  7367. begin
  7368. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7369. { An unconditional jump follows the conditional jump which will always be false,
  7370. so use this jump's destination for the new jump }
  7371. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7372. Result := True;
  7373. end
  7374. else if taicpu(hp2).opcode = A_JCC then
  7375. begin
  7376. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7377. if condition_in(C_E, taicpu(hp2).condition) then
  7378. begin
  7379. { A second conditional jump follows the conditional jump which will always be false,
  7380. while the second jump is always True, so use this jump's destination for the new jump }
  7381. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7382. Result := True;
  7383. end;
  7384. { Don't risk it if the jump isn't always true (Result remains False) }
  7385. end;
  7386. end;
  7387. else
  7388. { If anything else don't optimise };
  7389. end;
  7390. end;
  7391. if Result then
  7392. begin
  7393. { Just so we have something to insert as a paremeter}
  7394. reference_reset(NewRef, 1, []);
  7395. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7396. { Now actually load the correct parameter }
  7397. NewInstr.loadsymbol(0, DestLabel, 0);
  7398. { Get instruction before original label (may not be p under -O3) }
  7399. if not GetLastInstruction(hp1, hp2) then
  7400. { Shouldn't fail here }
  7401. InternalError(2021040701);
  7402. DestLabel.increfs;
  7403. AsmL.InsertAfter(NewInstr, hp2);
  7404. { Add new alignment field }
  7405. (* AsmL.InsertAfter(
  7406. cai_align.create_max(
  7407. current_settings.alignment.jumpalign,
  7408. current_settings.alignment.jumpalignskipmax
  7409. ),
  7410. NewInstr
  7411. ); *)
  7412. end;
  7413. Exit;
  7414. end;
  7415. end;
  7416. else
  7417. ;
  7418. end;
  7419. end;
  7420. if not GetNextInstruction(p, hp1) then
  7421. Exit;
  7422. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7423. and DoMovCmpMemOpt(p, hp1, True) then
  7424. begin
  7425. Result := True;
  7426. Exit;
  7427. end
  7428. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7429. begin
  7430. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7431. further, but we can't just put this jump optimisation in pass 1
  7432. because it tends to perform worse when conditional jumps are
  7433. nearby (e.g. when converting CMOV instructions). [Kit] }
  7434. if OptPass2JMP(hp1) then
  7435. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7436. Result := OptPass1MOV(p)
  7437. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7438. returned True and the instruction is still a MOV, thus checking
  7439. the optimisations below }
  7440. { If OptPass2JMP returned False, no optimisations were done to
  7441. the jump and there are no further optimisations that can be done
  7442. to the MOV instruction on this pass }
  7443. end
  7444. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7445. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7446. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7447. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7448. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7449. begin
  7450. { Change:
  7451. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7452. addl/q $x,%reg2 subl/q $x,%reg2
  7453. To:
  7454. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7455. }
  7456. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7457. { be lazy, checking separately for sub would be slightly better }
  7458. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7459. begin
  7460. TransferUsedRegs(TmpUsedRegs);
  7461. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7462. if TryMovArith2Lea(hp1) then
  7463. begin
  7464. Result := True;
  7465. Exit;
  7466. end
  7467. end
  7468. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7469. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7470. { Same as above, but also adds or subtracts to %reg2 in between.
  7471. It's still valid as long as the flags aren't in use }
  7472. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7473. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7474. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7475. { be lazy, checking separately for sub would be slightly better }
  7476. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7477. begin
  7478. TransferUsedRegs(TmpUsedRegs);
  7479. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7480. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7481. if TryMovArith2Lea(hp2) then
  7482. begin
  7483. Result := True;
  7484. Exit;
  7485. end;
  7486. end;
  7487. end
  7488. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7489. {$ifdef x86_64}
  7490. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7491. {$else x86_64}
  7492. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7493. {$endif x86_64}
  7494. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7495. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7496. { mov reg1, reg2 mov reg1, reg2
  7497. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7498. begin
  7499. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7500. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7501. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7502. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7503. TransferUsedRegs(TmpUsedRegs);
  7504. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7505. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7506. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7507. then
  7508. begin
  7509. RemoveCurrentP(p, hp1);
  7510. Result:=true;
  7511. end;
  7512. exit;
  7513. end
  7514. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7515. IsXCHGAcceptable and
  7516. { XCHG doesn't support 8-byte registers }
  7517. (taicpu(p).opsize <> S_B) and
  7518. MatchInstruction(hp1, A_MOV, []) and
  7519. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7520. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7521. GetNextInstruction(hp1, hp2) and
  7522. MatchInstruction(hp2, A_MOV, []) and
  7523. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7524. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7525. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7526. begin
  7527. { mov %reg1,%reg2
  7528. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7529. mov %reg2,%reg3
  7530. (%reg2 not used afterwards)
  7531. Note that xchg takes 3 cycles to execute, and generally mov's take
  7532. only one cycle apiece, but the first two mov's can be executed in
  7533. parallel, only taking 2 cycles overall. Older processors should
  7534. therefore only optimise for size. [Kit]
  7535. }
  7536. TransferUsedRegs(TmpUsedRegs);
  7537. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7538. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7539. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7540. begin
  7541. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7542. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7543. taicpu(hp1).opcode := A_XCHG;
  7544. RemoveCurrentP(p, hp1);
  7545. RemoveInstruction(hp2);
  7546. Result := True;
  7547. Exit;
  7548. end;
  7549. end
  7550. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7551. MatchInstruction(hp1, A_SAR, []) then
  7552. begin
  7553. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7554. begin
  7555. { the use of %edx also covers the opsize being S_L }
  7556. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7557. begin
  7558. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7559. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7560. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7561. begin
  7562. { Change:
  7563. movl %eax,%edx
  7564. sarl $31,%edx
  7565. To:
  7566. cltd
  7567. }
  7568. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7569. RemoveInstruction(hp1);
  7570. taicpu(p).opcode := A_CDQ;
  7571. taicpu(p).opsize := S_NO;
  7572. taicpu(p).clearop(1);
  7573. taicpu(p).clearop(0);
  7574. taicpu(p).ops:=0;
  7575. Result := True;
  7576. end
  7577. else if (cs_opt_size in current_settings.optimizerswitches) and
  7578. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7579. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7580. begin
  7581. { Change:
  7582. movl %edx,%eax
  7583. sarl $31,%edx
  7584. To:
  7585. movl %edx,%eax
  7586. cltd
  7587. Note that this creates a dependency between the two instructions,
  7588. so only perform if optimising for size.
  7589. }
  7590. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7591. taicpu(hp1).opcode := A_CDQ;
  7592. taicpu(hp1).opsize := S_NO;
  7593. taicpu(hp1).clearop(1);
  7594. taicpu(hp1).clearop(0);
  7595. taicpu(hp1).ops:=0;
  7596. end;
  7597. {$ifndef x86_64}
  7598. end
  7599. { Don't bother if CMOV is supported, because a more optimal
  7600. sequence would have been generated for the Abs() intrinsic }
  7601. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7602. { the use of %eax also covers the opsize being S_L }
  7603. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7604. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7605. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7606. GetNextInstruction(hp1, hp2) and
  7607. MatchInstruction(hp2, A_XOR, [S_L]) and
  7608. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7609. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7610. GetNextInstruction(hp2, hp3) and
  7611. MatchInstruction(hp3, A_SUB, [S_L]) and
  7612. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7613. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7614. begin
  7615. { Change:
  7616. movl %eax,%edx
  7617. sarl $31,%eax
  7618. xorl %eax,%edx
  7619. subl %eax,%edx
  7620. (Instruction that uses %edx)
  7621. (%eax deallocated)
  7622. (%edx deallocated)
  7623. To:
  7624. cltd
  7625. xorl %edx,%eax <-- Note the registers have swapped
  7626. subl %edx,%eax
  7627. (Instruction that uses %eax) <-- %eax rather than %edx
  7628. }
  7629. TransferUsedRegs(TmpUsedRegs);
  7630. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7631. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7632. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7633. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7634. begin
  7635. if GetNextInstruction(hp3, hp4) and
  7636. not RegModifiedByInstruction(NR_EDX, hp4) and
  7637. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7638. begin
  7639. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7640. taicpu(p).opcode := A_CDQ;
  7641. taicpu(p).clearop(1);
  7642. taicpu(p).clearop(0);
  7643. taicpu(p).ops:=0;
  7644. RemoveInstruction(hp1);
  7645. taicpu(hp2).loadreg(0, NR_EDX);
  7646. taicpu(hp2).loadreg(1, NR_EAX);
  7647. taicpu(hp3).loadreg(0, NR_EDX);
  7648. taicpu(hp3).loadreg(1, NR_EAX);
  7649. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7650. { Convert references in the following instruction (hp4) from %edx to %eax }
  7651. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7652. with taicpu(hp4).oper[OperIdx]^ do
  7653. case typ of
  7654. top_reg:
  7655. if getsupreg(reg) = RS_EDX then
  7656. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7657. top_ref:
  7658. begin
  7659. if getsupreg(reg) = RS_EDX then
  7660. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7661. if getsupreg(reg) = RS_EDX then
  7662. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7663. end;
  7664. else
  7665. ;
  7666. end;
  7667. end;
  7668. end;
  7669. {$else x86_64}
  7670. end;
  7671. end
  7672. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7673. { the use of %rdx also covers the opsize being S_Q }
  7674. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7675. begin
  7676. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7677. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7678. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7679. begin
  7680. { Change:
  7681. movq %rax,%rdx
  7682. sarq $63,%rdx
  7683. To:
  7684. cqto
  7685. }
  7686. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7687. RemoveInstruction(hp1);
  7688. taicpu(p).opcode := A_CQO;
  7689. taicpu(p).opsize := S_NO;
  7690. taicpu(p).clearop(1);
  7691. taicpu(p).clearop(0);
  7692. taicpu(p).ops:=0;
  7693. Result := True;
  7694. end
  7695. else if (cs_opt_size in current_settings.optimizerswitches) and
  7696. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7697. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7698. begin
  7699. { Change:
  7700. movq %rdx,%rax
  7701. sarq $63,%rdx
  7702. To:
  7703. movq %rdx,%rax
  7704. cqto
  7705. Note that this creates a dependency between the two instructions,
  7706. so only perform if optimising for size.
  7707. }
  7708. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7709. taicpu(hp1).opcode := A_CQO;
  7710. taicpu(hp1).opsize := S_NO;
  7711. taicpu(hp1).clearop(1);
  7712. taicpu(hp1).clearop(0);
  7713. taicpu(hp1).ops:=0;
  7714. {$endif x86_64}
  7715. end;
  7716. end;
  7717. end
  7718. else if MatchInstruction(hp1, A_MOV, []) and
  7719. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7720. { Though "GetNextInstruction" could be factored out, along with
  7721. the instructions that depend on hp2, it is an expensive call that
  7722. should be delayed for as long as possible, hence we do cheaper
  7723. checks first that are likely to be False. [Kit] }
  7724. begin
  7725. if (
  7726. (
  7727. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7728. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7729. (
  7730. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7731. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7732. )
  7733. ) or
  7734. (
  7735. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7736. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7737. (
  7738. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7739. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7740. )
  7741. )
  7742. ) and
  7743. GetNextInstruction(hp1, hp2) and
  7744. MatchInstruction(hp2, A_SAR, []) and
  7745. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7746. begin
  7747. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7748. begin
  7749. { Change:
  7750. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7751. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7752. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7753. To:
  7754. movl r/m,%eax <- Note the change in register
  7755. cltd
  7756. }
  7757. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7758. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7759. taicpu(p).loadreg(1, NR_EAX);
  7760. taicpu(hp1).opcode := A_CDQ;
  7761. taicpu(hp1).clearop(1);
  7762. taicpu(hp1).clearop(0);
  7763. taicpu(hp1).ops:=0;
  7764. RemoveInstruction(hp2);
  7765. (*
  7766. {$ifdef x86_64}
  7767. end
  7768. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7769. { This code sequence does not get generated - however it might become useful
  7770. if and when 128-bit signed integer types make an appearance, so the code
  7771. is kept here for when it is eventually needed. [Kit] }
  7772. (
  7773. (
  7774. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7775. (
  7776. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7777. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7778. )
  7779. ) or
  7780. (
  7781. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7782. (
  7783. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7784. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7785. )
  7786. )
  7787. ) and
  7788. GetNextInstruction(hp1, hp2) and
  7789. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7790. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7791. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7792. begin
  7793. { Change:
  7794. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7795. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7796. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7797. To:
  7798. movq r/m,%rax <- Note the change in register
  7799. cqto
  7800. }
  7801. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7802. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7803. taicpu(p).loadreg(1, NR_RAX);
  7804. taicpu(hp1).opcode := A_CQO;
  7805. taicpu(hp1).clearop(1);
  7806. taicpu(hp1).clearop(0);
  7807. taicpu(hp1).ops:=0;
  7808. RemoveInstruction(hp2);
  7809. {$endif x86_64}
  7810. *)
  7811. end;
  7812. end;
  7813. {$ifdef x86_64}
  7814. end
  7815. else if (taicpu(p).opsize = S_L) and
  7816. (taicpu(p).oper[1]^.typ = top_reg) and
  7817. (
  7818. MatchInstruction(hp1, A_MOV,[]) and
  7819. (taicpu(hp1).opsize = S_L) and
  7820. (taicpu(hp1).oper[1]^.typ = top_reg)
  7821. ) and (
  7822. GetNextInstruction(hp1, hp2) and
  7823. (tai(hp2).typ=ait_instruction) and
  7824. (taicpu(hp2).opsize = S_Q) and
  7825. (
  7826. (
  7827. MatchInstruction(hp2, A_ADD,[]) and
  7828. (taicpu(hp2).opsize = S_Q) and
  7829. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7830. (
  7831. (
  7832. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7833. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7834. ) or (
  7835. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7836. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7837. )
  7838. )
  7839. ) or (
  7840. MatchInstruction(hp2, A_LEA,[]) and
  7841. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7842. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7843. (
  7844. (
  7845. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7846. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7847. ) or (
  7848. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7849. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7850. )
  7851. ) and (
  7852. (
  7853. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7854. ) or (
  7855. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7856. )
  7857. )
  7858. )
  7859. )
  7860. ) and (
  7861. GetNextInstruction(hp2, hp3) and
  7862. MatchInstruction(hp3, A_SHR,[]) and
  7863. (taicpu(hp3).opsize = S_Q) and
  7864. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7865. (taicpu(hp3).oper[0]^.val = 1) and
  7866. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7867. ) then
  7868. begin
  7869. { Change movl x, reg1d movl x, reg1d
  7870. movl y, reg2d movl y, reg2d
  7871. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7872. shrq $1, reg1q shrq $1, reg1q
  7873. ( reg1d and reg2d can be switched around in the first two instructions )
  7874. To movl x, reg1d
  7875. addl y, reg1d
  7876. rcrl $1, reg1d
  7877. This corresponds to the common expression (x + y) shr 1, where
  7878. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7879. smaller code, but won't account for x + y causing an overflow). [Kit]
  7880. }
  7881. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7882. { Change first MOV command to have the same register as the final output }
  7883. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7884. else
  7885. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7886. { Change second MOV command to an ADD command. This is easier than
  7887. converting the existing command because it means we don't have to
  7888. touch 'y', which might be a complicated reference, and also the
  7889. fact that the third command might either be ADD or LEA. [Kit] }
  7890. taicpu(hp1).opcode := A_ADD;
  7891. { Delete old ADD/LEA instruction }
  7892. RemoveInstruction(hp2);
  7893. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7894. taicpu(hp3).opcode := A_RCR;
  7895. taicpu(hp3).changeopsize(S_L);
  7896. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7897. {$endif x86_64}
  7898. end;
  7899. end;
  7900. {$push}
  7901. {$q-}{$r-}
  7902. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7903. var
  7904. ThisReg: TRegister;
  7905. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7906. TargetSubReg: TSubRegister;
  7907. hp1, hp2: tai;
  7908. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7909. { Store list of found instructions so we don't have to call
  7910. GetNextInstructionUsingReg multiple times }
  7911. InstrList: array of taicpu;
  7912. InstrMax, Index: Integer;
  7913. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7914. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7915. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7916. WorkingValue: TCgInt;
  7917. PreMessage: string;
  7918. { Data flow analysis }
  7919. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7920. BitwiseOnly, OrXorUsed,
  7921. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7922. function CheckOverflowConditions: Boolean;
  7923. begin
  7924. Result := True;
  7925. if (TestValSignedMax > SignedUpperLimit) then
  7926. UpperSignedOverflow := True;
  7927. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7928. LowerSignedOverflow := True;
  7929. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7930. LowerUnsignedOverflow := True;
  7931. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7932. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7933. begin
  7934. { Absolute overflow }
  7935. Result := False;
  7936. Exit;
  7937. end;
  7938. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7939. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7940. ShiftDownOverflow := True;
  7941. if (TestValMin < 0) or (TestValMax < 0) then
  7942. begin
  7943. LowerUnsignedOverflow := True;
  7944. UpperUnsignedOverflow := True;
  7945. end;
  7946. end;
  7947. function AdjustInitialLoadAndSize: Boolean;
  7948. begin
  7949. Result := False;
  7950. if not p_removed then
  7951. begin
  7952. if TargetSize = MinSize then
  7953. begin
  7954. { Convert the input MOVZX to a MOV }
  7955. if (taicpu(p).oper[0]^.typ = top_reg) and
  7956. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7957. begin
  7958. { Or remove it completely! }
  7959. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7960. RemoveCurrentP(p);
  7961. p_removed := True;
  7962. end
  7963. else
  7964. begin
  7965. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7966. taicpu(p).opcode := A_MOV;
  7967. taicpu(p).oper[1]^.reg := ThisReg;
  7968. taicpu(p).opsize := TargetSize;
  7969. end;
  7970. Result := True;
  7971. end
  7972. else if TargetSize <> MaxSize then
  7973. begin
  7974. case MaxSize of
  7975. S_L:
  7976. if TargetSize = S_W then
  7977. begin
  7978. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7979. taicpu(p).opsize := S_BW;
  7980. taicpu(p).oper[1]^.reg := ThisReg;
  7981. Result := True;
  7982. end
  7983. else
  7984. InternalError(2020112341);
  7985. S_W:
  7986. if TargetSize = S_L then
  7987. begin
  7988. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7989. taicpu(p).opsize := S_BL;
  7990. taicpu(p).oper[1]^.reg := ThisReg;
  7991. Result := True;
  7992. end
  7993. else
  7994. InternalError(2020112342);
  7995. else
  7996. ;
  7997. end;
  7998. end
  7999. else if not hp1_removed and not RegInUse then
  8000. begin
  8001. { If we have something like:
  8002. movzbl (oper),%regd
  8003. add x, %regd
  8004. movzbl %regb, %regd
  8005. We can reduce the register size to the input of the final
  8006. movzbl instruction. Overflows won't have any effect.
  8007. }
  8008. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8009. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8010. begin
  8011. TargetSize := S_B;
  8012. setsubreg(ThisReg, R_SUBL);
  8013. Result := True;
  8014. end
  8015. else if (taicpu(p).opsize = S_WL) and
  8016. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8017. begin
  8018. TargetSize := S_W;
  8019. setsubreg(ThisReg, R_SUBW);
  8020. Result := True;
  8021. end;
  8022. if Result then
  8023. begin
  8024. { Convert the input MOVZX to a MOV }
  8025. if (taicpu(p).oper[0]^.typ = top_reg) and
  8026. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8027. begin
  8028. { Or remove it completely! }
  8029. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8030. RemoveCurrentP(p);
  8031. p_removed := True;
  8032. end
  8033. else
  8034. begin
  8035. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8036. taicpu(p).opcode := A_MOV;
  8037. taicpu(p).oper[1]^.reg := ThisReg;
  8038. taicpu(p).opsize := TargetSize;
  8039. end;
  8040. end;
  8041. end;
  8042. end;
  8043. end;
  8044. procedure AdjustFinalLoad;
  8045. begin
  8046. if not LowerUnsignedOverflow then
  8047. begin
  8048. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8049. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8050. begin
  8051. { Convert the output MOVZX to a MOV }
  8052. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8053. begin
  8054. { Or remove it completely! }
  8055. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8056. { Be careful; if p = hp1 and p was also removed, p
  8057. will become a dangling pointer }
  8058. if p = hp1 then
  8059. begin
  8060. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8061. p_removed := True;
  8062. end
  8063. else
  8064. RemoveInstruction(hp1);
  8065. hp1_removed := True;
  8066. end
  8067. else
  8068. begin
  8069. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8070. taicpu(hp1).opcode := A_MOV;
  8071. taicpu(hp1).oper[0]^.reg := ThisReg;
  8072. taicpu(hp1).opsize := TargetSize;
  8073. end;
  8074. end
  8075. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8076. begin
  8077. { Need to change the size of the output }
  8078. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8079. taicpu(hp1).oper[0]^.reg := ThisReg;
  8080. taicpu(hp1).opsize := S_BL;
  8081. end;
  8082. end;
  8083. end;
  8084. function CompressInstructions: Boolean;
  8085. var
  8086. LocalIndex: Integer;
  8087. begin
  8088. Result := False;
  8089. { The objective here is to try to find a combination that
  8090. removes one of the MOV/Z instructions. }
  8091. if (
  8092. (taicpu(p).oper[0]^.typ <> top_reg) or
  8093. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8094. ) and
  8095. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8096. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8097. begin
  8098. { Make a preference to remove the second MOVZX instruction }
  8099. case taicpu(hp1).opsize of
  8100. S_BL, S_WL:
  8101. begin
  8102. TargetSize := S_L;
  8103. TargetSubReg := R_SUBD;
  8104. end;
  8105. S_BW:
  8106. begin
  8107. TargetSize := S_W;
  8108. TargetSubReg := R_SUBW;
  8109. end;
  8110. else
  8111. InternalError(2020112302);
  8112. end;
  8113. end
  8114. else
  8115. begin
  8116. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8117. begin
  8118. { Exceeded lower bound but not upper bound }
  8119. TargetSize := MaxSize;
  8120. end
  8121. else if not LowerUnsignedOverflow then
  8122. begin
  8123. { Size didn't exceed lower bound }
  8124. TargetSize := MinSize;
  8125. end
  8126. else
  8127. Exit;
  8128. end;
  8129. case TargetSize of
  8130. S_B:
  8131. TargetSubReg := R_SUBL;
  8132. S_W:
  8133. TargetSubReg := R_SUBW;
  8134. S_L:
  8135. TargetSubReg := R_SUBD;
  8136. else
  8137. InternalError(2020112350);
  8138. end;
  8139. { Update the register to its new size }
  8140. setsubreg(ThisReg, TargetSubReg);
  8141. RegInUse := False;
  8142. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8143. begin
  8144. { Check to see if the active register is used afterwards;
  8145. if not, we can change it and make a saving. }
  8146. TransferUsedRegs(TmpUsedRegs);
  8147. { The target register may be marked as in use to cross
  8148. a jump to a distant label, so exclude it }
  8149. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8150. hp2 := p;
  8151. repeat
  8152. { Explicitly check for the excluded register (don't include the first
  8153. instruction as it may be reading from here }
  8154. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8155. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8156. begin
  8157. RegInUse := True;
  8158. Break;
  8159. end;
  8160. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8161. if not GetNextInstruction(hp2, hp2) then
  8162. InternalError(2020112340);
  8163. until (hp2 = hp1);
  8164. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8165. { We might still be able to get away with this }
  8166. RegInUse := not
  8167. (
  8168. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8169. (hp2.typ = ait_instruction) and
  8170. (
  8171. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8172. instruction that doesn't actually contain ThisReg }
  8173. (cs_opt_level3 in current_settings.optimizerswitches) or
  8174. RegInInstruction(ThisReg, hp2)
  8175. ) and
  8176. RegLoadedWithNewValue(ThisReg, hp2)
  8177. );
  8178. if not RegInUse then
  8179. begin
  8180. { Force the register size to the same as this instruction so it can be removed}
  8181. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8182. begin
  8183. TargetSize := S_L;
  8184. TargetSubReg := R_SUBD;
  8185. end
  8186. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8187. begin
  8188. TargetSize := S_W;
  8189. TargetSubReg := R_SUBW;
  8190. end;
  8191. ThisReg := taicpu(hp1).oper[1]^.reg;
  8192. setsubreg(ThisReg, TargetSubReg);
  8193. RegChanged := True;
  8194. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8195. TransferUsedRegs(TmpUsedRegs);
  8196. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8197. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8198. if p = hp1 then
  8199. begin
  8200. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8201. p_removed := True;
  8202. end
  8203. else
  8204. RemoveInstruction(hp1);
  8205. hp1_removed := True;
  8206. { Instruction will become "mov %reg,%reg" }
  8207. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8208. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8209. begin
  8210. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8211. RemoveCurrentP(p);
  8212. p_removed := True;
  8213. end
  8214. else
  8215. taicpu(p).oper[1]^.reg := ThisReg;
  8216. Result := True;
  8217. end
  8218. else
  8219. begin
  8220. if TargetSize <> MaxSize then
  8221. begin
  8222. { Since the register is in use, we have to force it to
  8223. MaxSize otherwise part of it may become undefined later on }
  8224. TargetSize := MaxSize;
  8225. case TargetSize of
  8226. S_B:
  8227. TargetSubReg := R_SUBL;
  8228. S_W:
  8229. TargetSubReg := R_SUBW;
  8230. S_L:
  8231. TargetSubReg := R_SUBD;
  8232. else
  8233. InternalError(2020112351);
  8234. end;
  8235. setsubreg(ThisReg, TargetSubReg);
  8236. end;
  8237. AdjustFinalLoad;
  8238. end;
  8239. end
  8240. else
  8241. AdjustFinalLoad;
  8242. Result := AdjustInitialLoadAndSize or Result;
  8243. { Now go through every instruction we found and change the
  8244. size. If TargetSize = MaxSize, then almost no changes are
  8245. needed and Result can remain False if it hasn't been set
  8246. yet.
  8247. If RegChanged is True, then the register requires changing
  8248. and so the point about TargetSize = MaxSize doesn't apply. }
  8249. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8250. begin
  8251. for LocalIndex := 0 to InstrMax do
  8252. begin
  8253. { If p_removed is true, then the original MOV/Z was removed
  8254. and removing the AND instruction may not be safe if it
  8255. appears first }
  8256. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8257. InternalError(2020112310);
  8258. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8259. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8260. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8261. InstrList[LocalIndex].opsize := TargetSize;
  8262. end;
  8263. Result := True;
  8264. end;
  8265. end;
  8266. begin
  8267. Result := False;
  8268. p_removed := False;
  8269. hp1_removed := False;
  8270. ThisReg := taicpu(p).oper[1]^.reg;
  8271. { Check for:
  8272. movs/z ###,%ecx (or %cx or %rcx)
  8273. ...
  8274. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8275. (dealloc %ecx)
  8276. Change to:
  8277. mov ###,%cl (if ### = %cl, then remove completely)
  8278. ...
  8279. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8280. }
  8281. if (getsupreg(ThisReg) = RS_ECX) and
  8282. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8283. (hp1.typ = ait_instruction) and
  8284. (
  8285. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8286. instruction that doesn't actually contain ECX }
  8287. (cs_opt_level3 in current_settings.optimizerswitches) or
  8288. RegInInstruction(NR_ECX, hp1) or
  8289. (
  8290. { It's common for the shift/rotate's read/write register to be
  8291. initialised in between, so under -O2 and under, search ahead
  8292. one more instruction
  8293. }
  8294. GetNextInstruction(hp1, hp1) and
  8295. (hp1.typ = ait_instruction) and
  8296. RegInInstruction(NR_ECX, hp1)
  8297. )
  8298. ) and
  8299. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8300. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8301. begin
  8302. TransferUsedRegs(TmpUsedRegs);
  8303. hp2 := p;
  8304. repeat
  8305. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8306. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8307. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8308. begin
  8309. case taicpu(p).opsize of
  8310. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8311. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8312. begin
  8313. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8314. RemoveCurrentP(p);
  8315. end
  8316. else
  8317. begin
  8318. taicpu(p).opcode := A_MOV;
  8319. taicpu(p).opsize := S_B;
  8320. taicpu(p).oper[1]^.reg := NR_CL;
  8321. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8322. end;
  8323. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8324. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8325. begin
  8326. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8327. RemoveCurrentP(p);
  8328. end
  8329. else
  8330. begin
  8331. taicpu(p).opcode := A_MOV;
  8332. taicpu(p).opsize := S_W;
  8333. taicpu(p).oper[1]^.reg := NR_CX;
  8334. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8335. end;
  8336. {$ifdef x86_64}
  8337. S_LQ:
  8338. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8339. begin
  8340. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8341. RemoveCurrentP(p);
  8342. end
  8343. else
  8344. begin
  8345. taicpu(p).opcode := A_MOV;
  8346. taicpu(p).opsize := S_L;
  8347. taicpu(p).oper[1]^.reg := NR_ECX;
  8348. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8349. end;
  8350. {$endif x86_64}
  8351. else
  8352. InternalError(2021120401);
  8353. end;
  8354. Result := True;
  8355. Exit;
  8356. end;
  8357. end;
  8358. { This is anything but quick! }
  8359. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8360. Exit;
  8361. SetLength(InstrList, 0);
  8362. InstrMax := -1;
  8363. case taicpu(p).opsize of
  8364. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8365. begin
  8366. {$if defined(i386) or defined(i8086)}
  8367. { If the target size is 8-bit, make sure we can actually encode it }
  8368. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8369. Exit;
  8370. {$endif i386 or i8086}
  8371. LowerLimit := $FF;
  8372. SignedLowerLimit := $7F;
  8373. SignedLowerLimitBottom := -128;
  8374. MinSize := S_B;
  8375. if taicpu(p).opsize = S_BW then
  8376. begin
  8377. MaxSize := S_W;
  8378. UpperLimit := $FFFF;
  8379. SignedUpperLimit := $7FFF;
  8380. SignedUpperLimitBottom := -32768;
  8381. end
  8382. else
  8383. begin
  8384. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8385. MaxSize := S_L;
  8386. UpperLimit := $FFFFFFFF;
  8387. SignedUpperLimit := $7FFFFFFF;
  8388. SignedUpperLimitBottom := -2147483648;
  8389. end;
  8390. end;
  8391. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8392. begin
  8393. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8394. LowerLimit := $FFFF;
  8395. SignedLowerLimit := $7FFF;
  8396. SignedLowerLimitBottom := -32768;
  8397. UpperLimit := $FFFFFFFF;
  8398. SignedUpperLimit := $7FFFFFFF;
  8399. SignedUpperLimitBottom := -2147483648;
  8400. MinSize := S_W;
  8401. MaxSize := S_L;
  8402. end;
  8403. {$ifdef x86_64}
  8404. S_LQ:
  8405. begin
  8406. { Both the lower and upper limits are set to 32-bit. If a limit
  8407. is breached, then optimisation is impossible }
  8408. LowerLimit := $FFFFFFFF;
  8409. SignedLowerLimit := $7FFFFFFF;
  8410. SignedLowerLimitBottom := -2147483648;
  8411. UpperLimit := $FFFFFFFF;
  8412. SignedUpperLimit := $7FFFFFFF;
  8413. SignedUpperLimitBottom := -2147483648;
  8414. MinSize := S_L;
  8415. MaxSize := S_L;
  8416. end;
  8417. {$endif x86_64}
  8418. else
  8419. InternalError(2020112301);
  8420. end;
  8421. TestValMin := 0;
  8422. TestValMax := LowerLimit;
  8423. TestValSignedMax := SignedLowerLimit;
  8424. TryShiftDownLimit := LowerLimit;
  8425. TryShiftDown := S_NO;
  8426. ShiftDownOverflow := False;
  8427. RegChanged := False;
  8428. BitwiseOnly := True;
  8429. OrXorUsed := False;
  8430. UpperSignedOverflow := False;
  8431. LowerSignedOverflow := False;
  8432. UpperUnsignedOverflow := False;
  8433. LowerUnsignedOverflow := False;
  8434. hp1 := p;
  8435. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8436. (hp1.typ = ait_instruction) and
  8437. (
  8438. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8439. instruction that doesn't actually contain ThisReg }
  8440. (cs_opt_level3 in current_settings.optimizerswitches) or
  8441. { This allows this Movx optimisation to work through the SETcc instructions
  8442. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8443. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8444. skip over these SETcc instructions). }
  8445. (taicpu(hp1).opcode = A_SETcc) or
  8446. RegInInstruction(ThisReg, hp1)
  8447. ) do
  8448. begin
  8449. case taicpu(hp1).opcode of
  8450. A_INC,A_DEC:
  8451. begin
  8452. { Has to be an exact match on the register }
  8453. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8454. Break;
  8455. if taicpu(hp1).opcode = A_INC then
  8456. begin
  8457. Inc(TestValMin);
  8458. Inc(TestValMax);
  8459. Inc(TestValSignedMax);
  8460. end
  8461. else
  8462. begin
  8463. Dec(TestValMin);
  8464. Dec(TestValMax);
  8465. Dec(TestValSignedMax);
  8466. end;
  8467. end;
  8468. A_TEST, A_CMP:
  8469. begin
  8470. if (
  8471. { Too high a risk of non-linear behaviour that breaks DFA
  8472. here, unless it's cmp $0,%reg, which is equivalent to
  8473. test %reg,%reg }
  8474. OrXorUsed and
  8475. (taicpu(hp1).opcode = A_CMP) and
  8476. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8477. ) or
  8478. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8479. { Has to be an exact match on the register }
  8480. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8481. (
  8482. { Permit "test %reg,%reg" }
  8483. (taicpu(hp1).opcode = A_TEST) and
  8484. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8485. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8486. ) or
  8487. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8488. { Make sure the comparison value is not smaller than the
  8489. smallest allowed signed value for the minimum size (e.g.
  8490. -128 for 8-bit) }
  8491. not (
  8492. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8493. { Is it in the negative range? }
  8494. (
  8495. (taicpu(hp1).oper[0]^.val < 0) and
  8496. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8497. )
  8498. ) then
  8499. Break;
  8500. { Check to see if the active register is used afterwards }
  8501. TransferUsedRegs(TmpUsedRegs);
  8502. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8503. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8504. begin
  8505. { Make sure the comparison or any previous instructions
  8506. hasn't pushed the test values outside of the range of
  8507. MinSize }
  8508. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8509. begin
  8510. { Exceeded lower bound but not upper bound }
  8511. Exit;
  8512. end
  8513. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8514. begin
  8515. { Size didn't exceed lower bound }
  8516. TargetSize := MinSize;
  8517. end
  8518. else
  8519. Break;
  8520. case TargetSize of
  8521. S_B:
  8522. TargetSubReg := R_SUBL;
  8523. S_W:
  8524. TargetSubReg := R_SUBW;
  8525. S_L:
  8526. TargetSubReg := R_SUBD;
  8527. else
  8528. InternalError(2021051002);
  8529. end;
  8530. if TargetSize <> MaxSize then
  8531. begin
  8532. { Update the register to its new size }
  8533. setsubreg(ThisReg, TargetSubReg);
  8534. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8535. taicpu(hp1).oper[1]^.reg := ThisReg;
  8536. taicpu(hp1).opsize := TargetSize;
  8537. { Convert the input MOVZX to a MOV if necessary }
  8538. AdjustInitialLoadAndSize;
  8539. if (InstrMax >= 0) then
  8540. begin
  8541. for Index := 0 to InstrMax do
  8542. begin
  8543. { If p_removed is true, then the original MOV/Z was removed
  8544. and removing the AND instruction may not be safe if it
  8545. appears first }
  8546. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8547. InternalError(2020112311);
  8548. if InstrList[Index].oper[0]^.typ = top_reg then
  8549. InstrList[Index].oper[0]^.reg := ThisReg;
  8550. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8551. InstrList[Index].opsize := MinSize;
  8552. end;
  8553. end;
  8554. Result := True;
  8555. end;
  8556. Exit;
  8557. end;
  8558. end;
  8559. A_SETcc:
  8560. begin
  8561. { This allows this Movx optimisation to work through the SETcc instructions
  8562. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8563. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8564. skip over these SETcc instructions). }
  8565. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8566. { Of course, break out if the current register is used }
  8567. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8568. Break
  8569. else
  8570. { We must use Continue so the instruction doesn't get added
  8571. to InstrList }
  8572. Continue;
  8573. end;
  8574. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8575. begin
  8576. if
  8577. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8578. { Has to be an exact match on the register }
  8579. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8580. (
  8581. (
  8582. (taicpu(hp1).oper[0]^.typ = top_const) and
  8583. (
  8584. (
  8585. (taicpu(hp1).opcode = A_SHL) and
  8586. (
  8587. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8588. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8589. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8590. )
  8591. ) or (
  8592. (taicpu(hp1).opcode <> A_SHL) and
  8593. (
  8594. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8595. { Is it in the negative range? }
  8596. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8597. )
  8598. )
  8599. )
  8600. ) or (
  8601. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8602. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8603. )
  8604. ) then
  8605. Break;
  8606. { Only process OR and XOR if there are only bitwise operations,
  8607. since otherwise they can too easily fool the data flow
  8608. analysis (they can cause non-linear behaviour) }
  8609. case taicpu(hp1).opcode of
  8610. A_ADD:
  8611. begin
  8612. if OrXorUsed then
  8613. { Too high a risk of non-linear behaviour that breaks DFA here }
  8614. Break
  8615. else
  8616. BitwiseOnly := False;
  8617. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8618. begin
  8619. TestValMin := TestValMin * 2;
  8620. TestValMax := TestValMax * 2;
  8621. TestValSignedMax := TestValSignedMax * 2;
  8622. end
  8623. else
  8624. begin
  8625. WorkingValue := taicpu(hp1).oper[0]^.val;
  8626. TestValMin := TestValMin + WorkingValue;
  8627. TestValMax := TestValMax + WorkingValue;
  8628. TestValSignedMax := TestValSignedMax + WorkingValue;
  8629. end;
  8630. end;
  8631. A_SUB:
  8632. begin
  8633. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8634. begin
  8635. TestValMin := 0;
  8636. TestValMax := 0;
  8637. TestValSignedMax := 0;
  8638. end
  8639. else
  8640. begin
  8641. if OrXorUsed then
  8642. { Too high a risk of non-linear behaviour that breaks DFA here }
  8643. Break
  8644. else
  8645. BitwiseOnly := False;
  8646. WorkingValue := taicpu(hp1).oper[0]^.val;
  8647. TestValMin := TestValMin - WorkingValue;
  8648. TestValMax := TestValMax - WorkingValue;
  8649. TestValSignedMax := TestValSignedMax - WorkingValue;
  8650. end;
  8651. end;
  8652. A_AND:
  8653. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8654. begin
  8655. { we might be able to go smaller if AND appears first }
  8656. if InstrMax = -1 then
  8657. case MinSize of
  8658. S_B:
  8659. ;
  8660. S_W:
  8661. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8662. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8663. begin
  8664. TryShiftDown := S_B;
  8665. TryShiftDownLimit := $FF;
  8666. end;
  8667. S_L:
  8668. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8669. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8670. begin
  8671. TryShiftDown := S_B;
  8672. TryShiftDownLimit := $FF;
  8673. end
  8674. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8675. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8676. begin
  8677. TryShiftDown := S_W;
  8678. TryShiftDownLimit := $FFFF;
  8679. end;
  8680. else
  8681. InternalError(2020112320);
  8682. end;
  8683. WorkingValue := taicpu(hp1).oper[0]^.val;
  8684. TestValMin := TestValMin and WorkingValue;
  8685. TestValMax := TestValMax and WorkingValue;
  8686. TestValSignedMax := TestValSignedMax and WorkingValue;
  8687. end;
  8688. A_OR:
  8689. begin
  8690. if not BitwiseOnly then
  8691. Break;
  8692. OrXorUsed := True;
  8693. WorkingValue := taicpu(hp1).oper[0]^.val;
  8694. TestValMin := TestValMin or WorkingValue;
  8695. TestValMax := TestValMax or WorkingValue;
  8696. TestValSignedMax := TestValSignedMax or WorkingValue;
  8697. end;
  8698. A_XOR:
  8699. begin
  8700. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8701. begin
  8702. TestValMin := 0;
  8703. TestValMax := 0;
  8704. TestValSignedMax := 0;
  8705. end
  8706. else
  8707. begin
  8708. if not BitwiseOnly then
  8709. Break;
  8710. OrXorUsed := True;
  8711. WorkingValue := taicpu(hp1).oper[0]^.val;
  8712. TestValMin := TestValMin xor WorkingValue;
  8713. TestValMax := TestValMax xor WorkingValue;
  8714. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8715. end;
  8716. end;
  8717. A_SHL:
  8718. begin
  8719. BitwiseOnly := False;
  8720. WorkingValue := taicpu(hp1).oper[0]^.val;
  8721. TestValMin := TestValMin shl WorkingValue;
  8722. TestValMax := TestValMax shl WorkingValue;
  8723. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8724. end;
  8725. A_SHR,
  8726. { The first instruction was MOVZX, so the value won't be negative }
  8727. A_SAR:
  8728. begin
  8729. if InstrMax <> -1 then
  8730. BitwiseOnly := False
  8731. else
  8732. { we might be able to go smaller if SHR appears first }
  8733. case MinSize of
  8734. S_B:
  8735. ;
  8736. S_W:
  8737. if (taicpu(hp1).oper[0]^.val >= 8) then
  8738. begin
  8739. TryShiftDown := S_B;
  8740. TryShiftDownLimit := $FF;
  8741. TryShiftDownSignedLimit := $7F;
  8742. TryShiftDownSignedLimitLower := -128;
  8743. end;
  8744. S_L:
  8745. if (taicpu(hp1).oper[0]^.val >= 24) then
  8746. begin
  8747. TryShiftDown := S_B;
  8748. TryShiftDownLimit := $FF;
  8749. TryShiftDownSignedLimit := $7F;
  8750. TryShiftDownSignedLimitLower := -128;
  8751. end
  8752. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8753. begin
  8754. TryShiftDown := S_W;
  8755. TryShiftDownLimit := $FFFF;
  8756. TryShiftDownSignedLimit := $7FFF;
  8757. TryShiftDownSignedLimitLower := -32768;
  8758. end;
  8759. else
  8760. InternalError(2020112321);
  8761. end;
  8762. WorkingValue := taicpu(hp1).oper[0]^.val;
  8763. if taicpu(hp1).opcode = A_SAR then
  8764. begin
  8765. TestValMin := SarInt64(TestValMin, WorkingValue);
  8766. TestValMax := SarInt64(TestValMax, WorkingValue);
  8767. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8768. end
  8769. else
  8770. begin
  8771. TestValMin := TestValMin shr WorkingValue;
  8772. TestValMax := TestValMax shr WorkingValue;
  8773. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8774. end;
  8775. end;
  8776. else
  8777. InternalError(2020112303);
  8778. end;
  8779. end;
  8780. (*
  8781. A_IMUL:
  8782. case taicpu(hp1).ops of
  8783. 2:
  8784. begin
  8785. if not MatchOpType(hp1, top_reg, top_reg) or
  8786. { Has to be an exact match on the register }
  8787. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8788. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8789. Break;
  8790. TestValMin := TestValMin * TestValMin;
  8791. TestValMax := TestValMax * TestValMax;
  8792. TestValSignedMax := TestValSignedMax * TestValMax;
  8793. end;
  8794. 3:
  8795. begin
  8796. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8797. { Has to be an exact match on the register }
  8798. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8799. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8800. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8801. { Is it in the negative range? }
  8802. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8803. Break;
  8804. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8805. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8806. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8807. end;
  8808. else
  8809. Break;
  8810. end;
  8811. A_IDIV:
  8812. case taicpu(hp1).ops of
  8813. 3:
  8814. begin
  8815. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8816. { Has to be an exact match on the register }
  8817. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8818. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8819. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8820. { Is it in the negative range? }
  8821. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8822. Break;
  8823. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8824. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8825. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8826. end;
  8827. else
  8828. Break;
  8829. end;
  8830. *)
  8831. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8832. begin
  8833. { If there are no instructions in between, then we might be able to make a saving }
  8834. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8835. Break;
  8836. { We have something like:
  8837. movzbw %dl,%dx
  8838. ...
  8839. movswl %dx,%edx
  8840. Change the latter to a zero-extension then enter the
  8841. A_MOVZX case branch.
  8842. }
  8843. {$ifdef x86_64}
  8844. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8845. begin
  8846. { this becomes a zero extension from 32-bit to 64-bit, but
  8847. the upper 32 bits are already zero, so just delete the
  8848. instruction }
  8849. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8850. RemoveInstruction(hp1);
  8851. Result := True;
  8852. Exit;
  8853. end
  8854. else
  8855. {$endif x86_64}
  8856. begin
  8857. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8858. taicpu(hp1).opcode := A_MOVZX;
  8859. {$ifdef x86_64}
  8860. case taicpu(hp1).opsize of
  8861. S_BQ:
  8862. begin
  8863. taicpu(hp1).opsize := S_BL;
  8864. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8865. end;
  8866. S_WQ:
  8867. begin
  8868. taicpu(hp1).opsize := S_WL;
  8869. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8870. end;
  8871. S_LQ:
  8872. begin
  8873. taicpu(hp1).opcode := A_MOV;
  8874. taicpu(hp1).opsize := S_L;
  8875. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8876. { In this instance, we need to break out because the
  8877. instruction is no longer MOVZX or MOVSXD }
  8878. Result := True;
  8879. Exit;
  8880. end;
  8881. else
  8882. ;
  8883. end;
  8884. {$endif x86_64}
  8885. Result := CompressInstructions;
  8886. Exit;
  8887. end;
  8888. end;
  8889. A_MOVZX:
  8890. begin
  8891. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8892. Break;
  8893. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8894. begin
  8895. if (InstrMax = -1) and
  8896. { Will return false if the second parameter isn't ThisReg
  8897. (can happen on -O2 and under) }
  8898. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8899. begin
  8900. { The two MOVZX instructions are adjacent, so remove the first one }
  8901. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8902. RemoveCurrentP(p);
  8903. Result := True;
  8904. Exit;
  8905. end;
  8906. Break;
  8907. end;
  8908. Result := CompressInstructions;
  8909. Exit;
  8910. end;
  8911. else
  8912. { This includes ADC, SBB and IDIV }
  8913. Break;
  8914. end;
  8915. if not CheckOverflowConditions then
  8916. Break;
  8917. { Contains highest index (so instruction count - 1) }
  8918. Inc(InstrMax);
  8919. if InstrMax > High(InstrList) then
  8920. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8921. InstrList[InstrMax] := taicpu(hp1);
  8922. end;
  8923. end;
  8924. {$pop}
  8925. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8926. var
  8927. hp1 : tai;
  8928. begin
  8929. Result:=false;
  8930. if (taicpu(p).ops >= 2) and
  8931. ((taicpu(p).oper[0]^.typ = top_const) or
  8932. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8933. (taicpu(p).oper[1]^.typ = top_reg) and
  8934. ((taicpu(p).ops = 2) or
  8935. ((taicpu(p).oper[2]^.typ = top_reg) and
  8936. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8937. GetLastInstruction(p,hp1) and
  8938. MatchInstruction(hp1,A_MOV,[]) and
  8939. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8940. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8941. begin
  8942. TransferUsedRegs(TmpUsedRegs);
  8943. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8944. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8945. { change
  8946. mov reg1,reg2
  8947. imul y,reg2 to imul y,reg1,reg2 }
  8948. begin
  8949. taicpu(p).ops := 3;
  8950. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8951. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8952. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8953. RemoveInstruction(hp1);
  8954. result:=true;
  8955. end;
  8956. end;
  8957. end;
  8958. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8959. var
  8960. ThisLabel: TAsmLabel;
  8961. begin
  8962. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8963. ThisLabel.decrefs;
  8964. taicpu(p).opcode := A_RET;
  8965. taicpu(p).is_jmp := false;
  8966. taicpu(p).ops := taicpu(ret_p).ops;
  8967. case taicpu(ret_p).ops of
  8968. 0:
  8969. taicpu(p).clearop(0);
  8970. 1:
  8971. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8972. else
  8973. internalerror(2016041301);
  8974. end;
  8975. { If the original label is now dead, it might turn out that the label
  8976. immediately follows p. As a result, everything beyond it, which will
  8977. be just some final register configuration and a RET instruction, is
  8978. now dead code. [Kit] }
  8979. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8980. running RemoveDeadCodeAfterJump for each RET instruction, because
  8981. this optimisation rarely happens and most RETs appear at the end of
  8982. routines where there is nothing that can be stripped. [Kit] }
  8983. if not ThisLabel.is_used then
  8984. RemoveDeadCodeAfterJump(p);
  8985. end;
  8986. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8987. var
  8988. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8989. Unconditional, PotentialModified: Boolean;
  8990. OperPtr: POper;
  8991. NewRef: TReference;
  8992. InstrList: array of taicpu;
  8993. InstrMax, Index: Integer;
  8994. const
  8995. {$ifdef DEBUG_AOPTCPU}
  8996. SNoFlags: shortstring = ' so the flags aren''t modified';
  8997. {$else DEBUG_AOPTCPU}
  8998. SNoFlags = '';
  8999. {$endif DEBUG_AOPTCPU}
  9000. begin
  9001. Result:=false;
  9002. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9003. begin
  9004. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9005. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9006. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9007. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9008. GetNextInstruction(hp1, hp2) and
  9009. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9010. { Change from: To:
  9011. set(C) %reg j(~C) label
  9012. test %reg,%reg/cmp $0,%reg
  9013. je label
  9014. set(C) %reg j(C) label
  9015. test %reg,%reg/cmp $0,%reg
  9016. jne label
  9017. (Also do something similar with sete/setne instead of je/jne)
  9018. }
  9019. begin
  9020. { Before we do anything else, we need to check the instructions
  9021. in between SETcc and TEST to make sure they don't modify the
  9022. FLAGS register - if -O2 or under, there won't be any
  9023. instructions between SET and TEST }
  9024. TransferUsedRegs(TmpUsedRegs);
  9025. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9026. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9027. begin
  9028. next := p;
  9029. SetLength(InstrList, 0);
  9030. InstrMax := -1;
  9031. PotentialModified := False;
  9032. { Make a note of every instruction that modifies the FLAGS
  9033. register }
  9034. while GetNextInstruction(next, next) and (next <> hp1) do
  9035. begin
  9036. if next.typ <> ait_instruction then
  9037. { GetNextInstructionUsingReg should have returned False }
  9038. InternalError(2021051701);
  9039. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9040. begin
  9041. case taicpu(next).opcode of
  9042. A_SETcc,
  9043. A_CMOVcc,
  9044. A_Jcc:
  9045. begin
  9046. if PotentialModified then
  9047. { Not safe because the flags were modified earlier }
  9048. Exit
  9049. else
  9050. { Condition is the same as the initial SETcc, so this is safe
  9051. (don't add to instruction list though) }
  9052. Continue;
  9053. end;
  9054. A_ADD:
  9055. begin
  9056. if (taicpu(next).opsize = S_B) or
  9057. { LEA doesn't support 8-bit operands }
  9058. (taicpu(next).oper[1]^.typ <> top_reg) or
  9059. { Must write to a register }
  9060. (taicpu(next).oper[0]^.typ = top_ref) then
  9061. { Require a constant or a register }
  9062. Exit;
  9063. PotentialModified := True;
  9064. end;
  9065. A_SUB:
  9066. begin
  9067. if (taicpu(next).opsize = S_B) or
  9068. { LEA doesn't support 8-bit operands }
  9069. (taicpu(next).oper[1]^.typ <> top_reg) or
  9070. { Must write to a register }
  9071. (taicpu(next).oper[0]^.typ <> top_const) or
  9072. (taicpu(next).oper[0]^.val = $80000000) then
  9073. { Can't subtract a register with LEA - also
  9074. check that the value isn't -2^31, as this
  9075. can't be negated }
  9076. Exit;
  9077. PotentialModified := True;
  9078. end;
  9079. A_SAL,
  9080. A_SHL:
  9081. begin
  9082. if (taicpu(next).opsize = S_B) or
  9083. { LEA doesn't support 8-bit operands }
  9084. (taicpu(next).oper[1]^.typ <> top_reg) or
  9085. { Must write to a register }
  9086. (taicpu(next).oper[0]^.typ <> top_const) or
  9087. (taicpu(next).oper[0]^.val < 0) or
  9088. (taicpu(next).oper[0]^.val > 3) then
  9089. Exit;
  9090. PotentialModified := True;
  9091. end;
  9092. A_IMUL:
  9093. begin
  9094. if (taicpu(next).ops <> 3) or
  9095. (taicpu(next).oper[1]^.typ <> top_reg) or
  9096. { Must write to a register }
  9097. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9098. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9099. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9100. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9101. Exit
  9102. else
  9103. PotentialModified := True;
  9104. end;
  9105. else
  9106. { Don't know how to change this, so abort }
  9107. Exit;
  9108. end;
  9109. { Contains highest index (so instruction count - 1) }
  9110. Inc(InstrMax);
  9111. if InstrMax > High(InstrList) then
  9112. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9113. InstrList[InstrMax] := taicpu(next);
  9114. end;
  9115. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9116. end;
  9117. if not Assigned(next) or (next <> hp1) then
  9118. { It should be equal to hp1 }
  9119. InternalError(2021051702);
  9120. { Cycle through each instruction and check to see if we can
  9121. change them to versions that don't modify the flags }
  9122. if (InstrMax >= 0) then
  9123. begin
  9124. for Index := 0 to InstrMax do
  9125. case InstrList[Index].opcode of
  9126. A_ADD:
  9127. begin
  9128. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9129. InstrList[Index].opcode := A_LEA;
  9130. reference_reset(NewRef, 1, []);
  9131. NewRef.base := InstrList[Index].oper[1]^.reg;
  9132. if InstrList[Index].oper[0]^.typ = top_reg then
  9133. begin
  9134. NewRef.index := InstrList[Index].oper[0]^.reg;
  9135. NewRef.scalefactor := 1;
  9136. end
  9137. else
  9138. NewRef.offset := InstrList[Index].oper[0]^.val;
  9139. InstrList[Index].loadref(0, NewRef);
  9140. end;
  9141. A_SUB:
  9142. begin
  9143. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9144. InstrList[Index].opcode := A_LEA;
  9145. reference_reset(NewRef, 1, []);
  9146. NewRef.base := InstrList[Index].oper[1]^.reg;
  9147. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9148. InstrList[Index].loadref(0, NewRef);
  9149. end;
  9150. A_SHL,
  9151. A_SAL:
  9152. begin
  9153. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9154. InstrList[Index].opcode := A_LEA;
  9155. reference_reset(NewRef, 1, []);
  9156. NewRef.index := InstrList[Index].oper[1]^.reg;
  9157. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9158. InstrList[Index].loadref(0, NewRef);
  9159. end;
  9160. A_IMUL:
  9161. begin
  9162. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9163. InstrList[Index].opcode := A_LEA;
  9164. reference_reset(NewRef, 1, []);
  9165. NewRef.index := InstrList[Index].oper[1]^.reg;
  9166. case InstrList[Index].oper[0]^.val of
  9167. 2, 4, 8:
  9168. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9169. else {3, 5 and 9}
  9170. begin
  9171. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9172. NewRef.base := InstrList[Index].oper[1]^.reg;
  9173. end;
  9174. end;
  9175. InstrList[Index].loadref(0, NewRef);
  9176. end;
  9177. else
  9178. InternalError(2021051710);
  9179. end;
  9180. end;
  9181. { Mark the FLAGS register as used across this whole block }
  9182. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9183. end;
  9184. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9185. JumpC := taicpu(hp2).condition;
  9186. Unconditional := False;
  9187. if conditions_equal(JumpC, C_E) then
  9188. SetC := inverse_cond(taicpu(p).condition)
  9189. else if conditions_equal(JumpC, C_NE) then
  9190. SetC := taicpu(p).condition
  9191. else
  9192. { We've got something weird here (and inefficent) }
  9193. begin
  9194. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9195. SetC := C_NONE;
  9196. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9197. if condition_in(C_AE, JumpC) then
  9198. Unconditional := True
  9199. else
  9200. { Not sure what to do with this jump - drop out }
  9201. Exit;
  9202. end;
  9203. RemoveInstruction(hp1);
  9204. if Unconditional then
  9205. MakeUnconditional(taicpu(hp2))
  9206. else
  9207. begin
  9208. if SetC = C_NONE then
  9209. InternalError(2018061402);
  9210. taicpu(hp2).SetCondition(SetC);
  9211. end;
  9212. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9213. TmpUsedRegs }
  9214. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9215. begin
  9216. RemoveCurrentp(p, hp2);
  9217. if taicpu(hp2).opcode = A_SETcc then
  9218. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9219. else
  9220. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9221. end
  9222. else
  9223. if taicpu(hp2).opcode = A_SETcc then
  9224. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9225. else
  9226. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9227. Result := True;
  9228. end
  9229. else if
  9230. { Make sure the instructions are adjacent }
  9231. (
  9232. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9233. GetNextInstruction(p, hp1)
  9234. ) and
  9235. MatchInstruction(hp1, A_MOV, [S_B]) and
  9236. { Writing to memory is allowed }
  9237. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9238. begin
  9239. {
  9240. Watch out for sequences such as:
  9241. set(c)b %regb
  9242. movb %regb,(ref)
  9243. movb $0,1(ref)
  9244. movb $0,2(ref)
  9245. movb $0,3(ref)
  9246. Much more efficient to turn it into:
  9247. movl $0,%regl
  9248. set(c)b %regb
  9249. movl %regl,(ref)
  9250. Or:
  9251. set(c)b %regb
  9252. movzbl %regb,%regl
  9253. movl %regl,(ref)
  9254. }
  9255. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9256. GetNextInstruction(hp1, hp2) and
  9257. MatchInstruction(hp2, A_MOV, [S_B]) and
  9258. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9259. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9260. begin
  9261. { Don't do anything else except set Result to True }
  9262. end
  9263. else
  9264. begin
  9265. if taicpu(p).oper[0]^.typ = top_reg then
  9266. begin
  9267. TransferUsedRegs(TmpUsedRegs);
  9268. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9269. end;
  9270. { If it's not a register, it's a memory address }
  9271. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9272. begin
  9273. { Even if the register is still in use, we can minimise the
  9274. pipeline stall by changing the MOV into another SETcc. }
  9275. taicpu(hp1).opcode := A_SETcc;
  9276. taicpu(hp1).condition := taicpu(p).condition;
  9277. if taicpu(hp1).oper[1]^.typ = top_ref then
  9278. begin
  9279. { Swapping the operand pointers like this is probably a
  9280. bit naughty, but it is far faster than using loadoper
  9281. to transfer the reference from oper[1] to oper[0] if
  9282. you take into account the extra procedure calls and
  9283. the memory allocation and deallocation required }
  9284. OperPtr := taicpu(hp1).oper[1];
  9285. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9286. taicpu(hp1).oper[0] := OperPtr;
  9287. end
  9288. else
  9289. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9290. taicpu(hp1).clearop(1);
  9291. taicpu(hp1).ops := 1;
  9292. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9293. end
  9294. else
  9295. begin
  9296. if taicpu(hp1).oper[1]^.typ = top_reg then
  9297. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9298. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9299. RemoveInstruction(hp1);
  9300. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9301. end
  9302. end;
  9303. Result := True;
  9304. end;
  9305. end;
  9306. end;
  9307. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9308. var
  9309. hp1: tai;
  9310. Count: Integer;
  9311. OrigLabel: TAsmLabel;
  9312. begin
  9313. result := False;
  9314. { Sometimes, the optimisations below can permit this }
  9315. RemoveDeadCodeAfterJump(p);
  9316. 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
  9317. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9318. begin
  9319. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9320. { Also a side-effect of optimisations }
  9321. if CollapseZeroDistJump(p, OrigLabel) then
  9322. begin
  9323. Result := True;
  9324. Exit;
  9325. end;
  9326. hp1 := GetLabelWithSym(OrigLabel);
  9327. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9328. begin
  9329. case taicpu(hp1).opcode of
  9330. A_RET:
  9331. {
  9332. change
  9333. jmp .L1
  9334. ...
  9335. .L1:
  9336. ret
  9337. into
  9338. ret
  9339. }
  9340. begin
  9341. ConvertJumpToRET(p, hp1);
  9342. result:=true;
  9343. end;
  9344. { Check any kind of direct assignment instruction }
  9345. A_MOV,
  9346. A_MOVD,
  9347. A_MOVQ,
  9348. A_MOVSX,
  9349. {$ifdef x86_64}
  9350. A_MOVSXD,
  9351. {$endif x86_64}
  9352. A_MOVZX,
  9353. A_MOVAPS,
  9354. A_MOVUPS,
  9355. A_MOVSD,
  9356. A_MOVAPD,
  9357. A_MOVUPD,
  9358. A_MOVDQA,
  9359. A_MOVDQU,
  9360. A_VMOVSS,
  9361. A_VMOVAPS,
  9362. A_VMOVUPS,
  9363. A_VMOVSD,
  9364. A_VMOVAPD,
  9365. A_VMOVUPD,
  9366. A_VMOVDQA,
  9367. A_VMOVDQU:
  9368. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9369. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9370. begin
  9371. Result := True;
  9372. Exit;
  9373. end;
  9374. else
  9375. ;
  9376. end;
  9377. end;
  9378. end;
  9379. end;
  9380. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9381. begin
  9382. CanBeCMOV:=assigned(p) and
  9383. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9384. { we can't use cmov ref,reg because
  9385. ref could be nil and cmov still throws an exception
  9386. if ref=nil but the mov isn't done (FK)
  9387. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9388. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9389. }
  9390. (taicpu(p).oper[1]^.typ = top_reg) and
  9391. (
  9392. (taicpu(p).oper[0]^.typ = top_reg) or
  9393. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9394. it is not expected that this can cause a seg. violation }
  9395. (
  9396. (taicpu(p).oper[0]^.typ = top_ref) and
  9397. IsRefSafe(taicpu(p).oper[0]^.ref)
  9398. )
  9399. );
  9400. end;
  9401. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9402. var
  9403. hp1,hp2: tai;
  9404. {$ifndef i8086}
  9405. hp3,hp4,hpmov2, hp5: tai;
  9406. l : Longint;
  9407. condition : TAsmCond;
  9408. {$endif i8086}
  9409. carryadd_opcode : TAsmOp;
  9410. symbol: TAsmSymbol;
  9411. increg, tmpreg: TRegister;
  9412. begin
  9413. result:=false;
  9414. if GetNextInstruction(p,hp1) then
  9415. begin
  9416. if (hp1.typ=ait_label) then
  9417. begin
  9418. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9419. Exit;
  9420. end
  9421. else if (hp1.typ<>ait_instruction) then
  9422. Exit;
  9423. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9424. if (
  9425. (
  9426. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9427. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9428. (Taicpu(hp1).oper[0]^.val=1)
  9429. ) or
  9430. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9431. ) and
  9432. GetNextInstruction(hp1,hp2) and
  9433. SkipAligns(hp2, hp2) and
  9434. (hp2.typ = ait_label) and
  9435. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9436. { jb @@1 cmc
  9437. inc/dec operand --> adc/sbb operand,0
  9438. @@1:
  9439. ... and ...
  9440. jnb @@1
  9441. inc/dec operand --> adc/sbb operand,0
  9442. @@1: }
  9443. begin
  9444. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9445. begin
  9446. case taicpu(hp1).opcode of
  9447. A_INC,
  9448. A_ADD:
  9449. carryadd_opcode:=A_ADC;
  9450. A_DEC,
  9451. A_SUB:
  9452. carryadd_opcode:=A_SBB;
  9453. else
  9454. InternalError(2021011001);
  9455. end;
  9456. Taicpu(p).clearop(0);
  9457. Taicpu(p).ops:=0;
  9458. Taicpu(p).is_jmp:=false;
  9459. Taicpu(p).opcode:=A_CMC;
  9460. Taicpu(p).condition:=C_NONE;
  9461. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9462. Taicpu(hp1).ops:=2;
  9463. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9464. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9465. else
  9466. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9467. Taicpu(hp1).loadconst(0,0);
  9468. Taicpu(hp1).opcode:=carryadd_opcode;
  9469. result:=true;
  9470. exit;
  9471. end
  9472. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9473. begin
  9474. case taicpu(hp1).opcode of
  9475. A_INC,
  9476. A_ADD:
  9477. carryadd_opcode:=A_ADC;
  9478. A_DEC,
  9479. A_SUB:
  9480. carryadd_opcode:=A_SBB;
  9481. else
  9482. InternalError(2021011002);
  9483. end;
  9484. Taicpu(hp1).ops:=2;
  9485. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9486. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9487. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9488. else
  9489. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9490. Taicpu(hp1).loadconst(0,0);
  9491. Taicpu(hp1).opcode:=carryadd_opcode;
  9492. RemoveCurrentP(p, hp1);
  9493. result:=true;
  9494. exit;
  9495. end
  9496. {
  9497. jcc @@1 setcc tmpreg
  9498. inc/dec/add/sub operand -> (movzx tmpreg)
  9499. @@1: add/sub tmpreg,operand
  9500. While this increases code size slightly, it makes the code much faster if the
  9501. jump is unpredictable
  9502. }
  9503. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9504. begin
  9505. { search for an available register which is volatile }
  9506. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9507. if increg <> NR_NO then
  9508. begin
  9509. { We don't need to check if tmpreg is in hp1 or not, because
  9510. it will be marked as in use at p (if not, this is
  9511. indictive of a compiler bug). }
  9512. TAsmLabel(symbol).decrefs;
  9513. Taicpu(p).clearop(0);
  9514. Taicpu(p).ops:=1;
  9515. Taicpu(p).is_jmp:=false;
  9516. Taicpu(p).opcode:=A_SETcc;
  9517. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9518. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9519. Taicpu(p).loadreg(0,increg);
  9520. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9521. begin
  9522. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9523. R_SUBW:
  9524. begin
  9525. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9526. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9527. end;
  9528. R_SUBD:
  9529. begin
  9530. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9531. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9532. end;
  9533. {$ifdef x86_64}
  9534. R_SUBQ:
  9535. begin
  9536. { MOVZX doesn't have a 64-bit variant, because
  9537. the 32-bit version implicitly zeroes the
  9538. upper 32-bits of the destination register }
  9539. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9540. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9541. setsubreg(tmpreg, R_SUBQ);
  9542. end;
  9543. {$endif x86_64}
  9544. else
  9545. Internalerror(2020030601);
  9546. end;
  9547. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9548. asml.InsertAfter(hp2,p);
  9549. end
  9550. else
  9551. tmpreg := increg;
  9552. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9553. begin
  9554. Taicpu(hp1).ops:=2;
  9555. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9556. end;
  9557. Taicpu(hp1).loadreg(0,tmpreg);
  9558. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9559. Result := True;
  9560. { p is no longer a Jcc instruction, so exit }
  9561. Exit;
  9562. end;
  9563. end;
  9564. end;
  9565. { Detect the following:
  9566. jmp<cond> @Lbl1
  9567. jmp @Lbl2
  9568. ...
  9569. @Lbl1:
  9570. ret
  9571. Change to:
  9572. jmp<inv_cond> @Lbl2
  9573. ret
  9574. }
  9575. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9576. begin
  9577. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9578. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9579. MatchInstruction(hp2,A_RET,[S_NO]) then
  9580. begin
  9581. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9582. { Change label address to that of the unconditional jump }
  9583. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9584. TAsmLabel(symbol).DecRefs;
  9585. taicpu(hp1).opcode := A_RET;
  9586. taicpu(hp1).is_jmp := false;
  9587. taicpu(hp1).ops := taicpu(hp2).ops;
  9588. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9589. case taicpu(hp2).ops of
  9590. 0:
  9591. taicpu(hp1).clearop(0);
  9592. 1:
  9593. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9594. else
  9595. internalerror(2016041302);
  9596. end;
  9597. end;
  9598. {$ifndef i8086}
  9599. end
  9600. {
  9601. convert
  9602. j<c> .L1
  9603. mov 1,reg
  9604. jmp .L2
  9605. .L1
  9606. mov 0,reg
  9607. .L2
  9608. into
  9609. mov 0,reg
  9610. set<not(c)> reg
  9611. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9612. would destroy the flag contents
  9613. }
  9614. else if MatchInstruction(hp1,A_MOV,[]) and
  9615. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9616. {$ifdef i386}
  9617. (
  9618. { Under i386, ESI, EDI, EBP and ESP
  9619. don't have an 8-bit representation }
  9620. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9621. ) and
  9622. {$endif i386}
  9623. (taicpu(hp1).oper[0]^.val=1) and
  9624. GetNextInstruction(hp1,hp2) and
  9625. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9626. GetNextInstruction(hp2,hp3) and
  9627. { skip align }
  9628. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9629. (hp3.typ=ait_label) and
  9630. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9631. (tai_label(hp3).labsym.getrefs=1) and
  9632. GetNextInstruction(hp3,hp4) and
  9633. MatchInstruction(hp4,A_MOV,[]) and
  9634. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9635. (taicpu(hp4).oper[0]^.val=0) and
  9636. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9637. GetNextInstruction(hp4,hp5) and
  9638. (hp5.typ=ait_label) and
  9639. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9640. (tai_label(hp5).labsym.getrefs=1) then
  9641. begin
  9642. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9643. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9644. { remove last label }
  9645. RemoveInstruction(hp5);
  9646. { remove second label }
  9647. RemoveInstruction(hp3);
  9648. { if align is present remove it }
  9649. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9650. RemoveInstruction(hp3);
  9651. { remove jmp }
  9652. RemoveInstruction(hp2);
  9653. if taicpu(hp1).opsize=S_B then
  9654. RemoveInstruction(hp1)
  9655. else
  9656. taicpu(hp1).loadconst(0,0);
  9657. taicpu(hp4).opcode:=A_SETcc;
  9658. taicpu(hp4).opsize:=S_B;
  9659. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9660. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9661. taicpu(hp4).opercnt:=1;
  9662. taicpu(hp4).ops:=1;
  9663. taicpu(hp4).freeop(1);
  9664. RemoveCurrentP(p);
  9665. Result:=true;
  9666. exit;
  9667. end
  9668. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9669. begin
  9670. { check for
  9671. jCC xxx
  9672. <several movs>
  9673. xxx:
  9674. Also spot:
  9675. Jcc xxx
  9676. <several movs>
  9677. jmp xxx
  9678. Change to:
  9679. <several cmovs with inverted condition>
  9680. jmp xxx
  9681. }
  9682. l:=0;
  9683. while assigned(hp1) and
  9684. CanBeCMOV(hp1) and
  9685. { stop on labels }
  9686. not(hp1.typ=ait_label) do
  9687. begin
  9688. inc(l);
  9689. hp5 := hp1;
  9690. GetNextInstruction(hp1,hp1);
  9691. end;
  9692. if assigned(hp1) then
  9693. begin
  9694. TransferUsedRegs(TmpUsedRegs);
  9695. if (
  9696. MatchInstruction(hp1, A_JMP, []) and
  9697. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9698. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9699. ) or
  9700. FindLabel(tasmlabel(symbol),hp1) then
  9701. begin
  9702. if (l<=4) and (l>0) then
  9703. begin
  9704. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9705. condition:=inverse_cond(taicpu(p).condition);
  9706. UpdateUsedRegs(tai(p.next));
  9707. GetNextInstruction(p,hp1);
  9708. repeat
  9709. if not Assigned(hp1) then
  9710. InternalError(2018062900);
  9711. taicpu(hp1).opcode:=A_CMOVcc;
  9712. taicpu(hp1).condition:=condition;
  9713. UpdateUsedRegs(tai(hp1.next));
  9714. GetNextInstruction(hp1,hp1);
  9715. until not(CanBeCMOV(hp1));
  9716. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9717. hp2 := hp1;
  9718. repeat
  9719. if not Assigned(hp2) then
  9720. InternalError(2018062910);
  9721. case hp2.typ of
  9722. ait_label:
  9723. { What we expected - break out of the loop (it won't be a dead label at the top of
  9724. a cluster because that was optimised at an earlier stage) }
  9725. Break;
  9726. ait_align:
  9727. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9728. begin
  9729. hp2 := tai(hp2.Next);
  9730. Continue;
  9731. end;
  9732. ait_instruction:
  9733. begin
  9734. if taicpu(hp2).opcode<>A_JMP then
  9735. InternalError(2018062912);
  9736. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9737. Break;
  9738. end
  9739. else
  9740. begin
  9741. { Might be a comment or temporary allocation entry }
  9742. if not (hp2.typ in SkipInstr) then
  9743. InternalError(2018062911);
  9744. hp2 := tai(hp2.Next);
  9745. Continue;
  9746. end;
  9747. end;
  9748. until False;
  9749. { Now we can safely decrement the reference count }
  9750. tasmlabel(symbol).decrefs;
  9751. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9752. { Remove the original jump }
  9753. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9754. if hp2.typ=ait_instruction then
  9755. begin
  9756. p:=hp2;
  9757. Result:=True;
  9758. end
  9759. else
  9760. begin
  9761. UpdateUsedRegs(tai(hp2.next));
  9762. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9763. { Remove the label if this is its final reference }
  9764. if (tasmlabel(symbol).getrefs=0) then
  9765. StripLabelFast(hp1);
  9766. end;
  9767. exit;
  9768. end;
  9769. end
  9770. else
  9771. begin
  9772. { check further for
  9773. jCC xxx
  9774. <several movs 1>
  9775. jmp yyy
  9776. xxx:
  9777. <several movs 2>
  9778. yyy:
  9779. }
  9780. { hp2 points to jmp yyy }
  9781. hp2:=hp1;
  9782. { skip hp1 to xxx (or an align right before it) }
  9783. GetNextInstruction(hp1, hp1);
  9784. if assigned(hp2) and
  9785. assigned(hp1) and
  9786. (l<=3) and
  9787. (hp2.typ=ait_instruction) and
  9788. (taicpu(hp2).is_jmp) and
  9789. (taicpu(hp2).condition=C_None) and
  9790. { real label and jump, no further references to the
  9791. label are allowed }
  9792. (tasmlabel(symbol).getrefs=1) and
  9793. FindLabel(tasmlabel(symbol),hp1) then
  9794. begin
  9795. l:=0;
  9796. { skip hp1 to <several moves 2> }
  9797. if (hp1.typ = ait_align) then
  9798. GetNextInstruction(hp1, hp1);
  9799. GetNextInstruction(hp1, hpmov2);
  9800. hp1 := hpmov2;
  9801. while assigned(hp1) and
  9802. CanBeCMOV(hp1) do
  9803. begin
  9804. inc(l);
  9805. hp5 := hp1;
  9806. GetNextInstruction(hp1, hp1);
  9807. end;
  9808. { hp1 points to yyy (or an align right before it) }
  9809. hp3 := hp1;
  9810. if assigned(hp1) and
  9811. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9812. begin
  9813. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9814. condition:=inverse_cond(taicpu(p).condition);
  9815. UpdateUsedRegs(tai(p.next));
  9816. GetNextInstruction(p,hp1);
  9817. repeat
  9818. taicpu(hp1).opcode:=A_CMOVcc;
  9819. taicpu(hp1).condition:=condition;
  9820. UpdateUsedRegs(tai(hp1.next));
  9821. GetNextInstruction(hp1,hp1);
  9822. until not(assigned(hp1)) or
  9823. not(CanBeCMOV(hp1));
  9824. condition:=inverse_cond(condition);
  9825. if GetLastInstruction(hpmov2,hp1) then
  9826. UpdateUsedRegs(tai(hp1.next));
  9827. hp1 := hpmov2;
  9828. { hp1 is now at <several movs 2> }
  9829. while Assigned(hp1) and CanBeCMOV(hp1) do
  9830. begin
  9831. taicpu(hp1).opcode:=A_CMOVcc;
  9832. taicpu(hp1).condition:=condition;
  9833. UpdateUsedRegs(tai(hp1.next));
  9834. GetNextInstruction(hp1,hp1);
  9835. end;
  9836. hp1 := p;
  9837. { Get first instruction after label }
  9838. UpdateUsedRegs(tai(hp3.next));
  9839. GetNextInstruction(hp3, p);
  9840. if assigned(p) and (hp3.typ = ait_align) then
  9841. GetNextInstruction(p, p);
  9842. { Don't dereference yet, as doing so will cause
  9843. GetNextInstruction to skip the label and
  9844. optional align marker. [Kit] }
  9845. GetNextInstruction(hp2, hp4);
  9846. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9847. { remove jCC }
  9848. RemoveInstruction(hp1);
  9849. { Now we can safely decrement it }
  9850. tasmlabel(symbol).decrefs;
  9851. { Remove label xxx (it will have a ref of zero due to the initial check }
  9852. StripLabelFast(hp4);
  9853. { remove jmp }
  9854. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9855. RemoveInstruction(hp2);
  9856. { As before, now we can safely decrement it }
  9857. tasmlabel(symbol).decrefs;
  9858. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9859. if tasmlabel(symbol).getrefs = 0 then
  9860. StripLabelFast(hp3);
  9861. if Assigned(p) then
  9862. result:=true;
  9863. exit;
  9864. end;
  9865. end;
  9866. end;
  9867. end;
  9868. {$endif i8086}
  9869. end;
  9870. end;
  9871. end;
  9872. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9873. var
  9874. hp1,hp2,hp3: tai;
  9875. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9876. NewSize: TOpSize;
  9877. NewRegSize: TSubRegister;
  9878. Limit: TCgInt;
  9879. SwapOper: POper;
  9880. begin
  9881. result:=false;
  9882. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9883. GetNextInstruction(p,hp1) and
  9884. (hp1.typ = ait_instruction);
  9885. if reg_and_hp1_is_instr and
  9886. (
  9887. (taicpu(hp1).opcode <> A_LEA) or
  9888. { If the LEA instruction can be converted into an arithmetic instruction,
  9889. it may be possible to then fold it. }
  9890. (
  9891. { If the flags register is in use, don't change the instruction
  9892. to an ADD otherwise this will scramble the flags. [Kit] }
  9893. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9894. ConvertLEA(taicpu(hp1))
  9895. )
  9896. ) and
  9897. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9898. GetNextInstruction(hp1,hp2) and
  9899. MatchInstruction(hp2,A_MOV,[]) and
  9900. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9901. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9902. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9903. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9904. {$ifdef i386}
  9905. { not all registers have byte size sub registers on i386 }
  9906. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9907. {$endif i386}
  9908. (((taicpu(hp1).ops=2) and
  9909. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9910. ((taicpu(hp1).ops=1) and
  9911. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9912. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9913. begin
  9914. { change movsX/movzX reg/ref, reg2
  9915. add/sub/or/... reg3/$const, reg2
  9916. mov reg2 reg/ref
  9917. to add/sub/or/... reg3/$const, reg/ref }
  9918. { by example:
  9919. movswl %si,%eax movswl %si,%eax p
  9920. decl %eax addl %edx,%eax hp1
  9921. movw %ax,%si movw %ax,%si hp2
  9922. ->
  9923. movswl %si,%eax movswl %si,%eax p
  9924. decw %eax addw %edx,%eax hp1
  9925. movw %ax,%si movw %ax,%si hp2
  9926. }
  9927. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9928. {
  9929. ->
  9930. movswl %si,%eax movswl %si,%eax p
  9931. decw %si addw %dx,%si hp1
  9932. movw %ax,%si movw %ax,%si hp2
  9933. }
  9934. case taicpu(hp1).ops of
  9935. 1:
  9936. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9937. 2:
  9938. begin
  9939. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9940. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9941. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9942. end;
  9943. else
  9944. internalerror(2008042702);
  9945. end;
  9946. {
  9947. ->
  9948. decw %si addw %dx,%si p
  9949. }
  9950. DebugMsg(SPeepholeOptimization + 'var3',p);
  9951. RemoveCurrentP(p, hp1);
  9952. RemoveInstruction(hp2);
  9953. Result := True;
  9954. Exit;
  9955. end;
  9956. if reg_and_hp1_is_instr and
  9957. (taicpu(hp1).opcode = A_MOV) and
  9958. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9959. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9960. {$ifdef x86_64}
  9961. { check for implicit extension to 64 bit }
  9962. or
  9963. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9964. (taicpu(hp1).opsize=S_Q) and
  9965. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9966. )
  9967. {$endif x86_64}
  9968. )
  9969. then
  9970. begin
  9971. { change
  9972. movx %reg1,%reg2
  9973. mov %reg2,%reg3
  9974. dealloc %reg2
  9975. into
  9976. movx %reg,%reg3
  9977. }
  9978. TransferUsedRegs(TmpUsedRegs);
  9979. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9980. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9981. begin
  9982. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9983. {$ifdef x86_64}
  9984. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9985. (taicpu(hp1).opsize=S_Q) then
  9986. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9987. else
  9988. {$endif x86_64}
  9989. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9990. RemoveInstruction(hp1);
  9991. Result := True;
  9992. Exit;
  9993. end;
  9994. end;
  9995. if reg_and_hp1_is_instr and
  9996. ((taicpu(hp1).opcode=A_MOV) or
  9997. (taicpu(hp1).opcode=A_ADD) or
  9998. (taicpu(hp1).opcode=A_SUB) or
  9999. (taicpu(hp1).opcode=A_CMP) or
  10000. (taicpu(hp1).opcode=A_OR) or
  10001. (taicpu(hp1).opcode=A_XOR) or
  10002. (taicpu(hp1).opcode=A_AND)
  10003. ) and
  10004. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10005. begin
  10006. AndTest := (taicpu(hp1).opcode=A_AND) and
  10007. GetNextInstruction(hp1, hp2) and
  10008. (hp2.typ = ait_instruction) and
  10009. (
  10010. (
  10011. (taicpu(hp2).opcode=A_TEST) and
  10012. (
  10013. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10014. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10015. (
  10016. { If the AND and TEST instructions share a constant, this is also valid }
  10017. (taicpu(hp1).oper[0]^.typ = top_const) and
  10018. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10019. )
  10020. ) and
  10021. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10022. ) or
  10023. (
  10024. (taicpu(hp2).opcode=A_CMP) and
  10025. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10026. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10027. )
  10028. );
  10029. { change
  10030. movx (oper),%reg2
  10031. and $x,%reg2
  10032. test %reg2,%reg2
  10033. dealloc %reg2
  10034. into
  10035. op %reg1,%reg3
  10036. if the second op accesses only the bits stored in reg1
  10037. }
  10038. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10039. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10040. (taicpu(hp1).oper[0]^.typ = top_const) and
  10041. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10042. AndTest then
  10043. begin
  10044. { Check if the AND constant is in range }
  10045. case taicpu(p).opsize of
  10046. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10047. begin
  10048. NewSize := S_B;
  10049. Limit := $FF;
  10050. end;
  10051. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10052. begin
  10053. NewSize := S_W;
  10054. Limit := $FFFF;
  10055. end;
  10056. {$ifdef x86_64}
  10057. S_LQ:
  10058. begin
  10059. NewSize := S_L;
  10060. Limit := $FFFFFFFF;
  10061. end;
  10062. {$endif x86_64}
  10063. else
  10064. InternalError(2021120303);
  10065. end;
  10066. if (
  10067. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10068. { Check for negative operands }
  10069. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10070. ) and
  10071. GetNextInstruction(hp2,hp3) and
  10072. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10073. (taicpu(hp3).condition in [C_E,C_NE]) then
  10074. begin
  10075. TransferUsedRegs(TmpUsedRegs);
  10076. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10077. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10078. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10079. begin
  10080. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10081. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10082. taicpu(hp1).opcode := A_TEST;
  10083. taicpu(hp1).opsize := NewSize;
  10084. RemoveInstruction(hp2);
  10085. RemoveCurrentP(p, hp1);
  10086. Result:=true;
  10087. exit;
  10088. end;
  10089. end;
  10090. end;
  10091. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10092. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10093. (taicpu(hp1).opsize=S_B)) or
  10094. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10095. (taicpu(hp1).opsize=S_W))
  10096. {$ifdef x86_64}
  10097. or ((taicpu(p).opsize=S_LQ) and
  10098. (taicpu(hp1).opsize=S_L))
  10099. {$endif x86_64}
  10100. ) and
  10101. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10102. begin
  10103. { change
  10104. movx %reg1,%reg2
  10105. op %reg2,%reg3
  10106. dealloc %reg2
  10107. into
  10108. op %reg1,%reg3
  10109. if the second op accesses only the bits stored in reg1
  10110. }
  10111. TransferUsedRegs(TmpUsedRegs);
  10112. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10113. if AndTest then
  10114. begin
  10115. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10116. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10117. end
  10118. else
  10119. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10120. if not RegUsed then
  10121. begin
  10122. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10123. if taicpu(p).oper[0]^.typ=top_reg then
  10124. begin
  10125. case taicpu(hp1).opsize of
  10126. S_B:
  10127. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10128. S_W:
  10129. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10130. S_L:
  10131. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10132. else
  10133. Internalerror(2020102301);
  10134. end;
  10135. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10136. end
  10137. else
  10138. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10139. RemoveCurrentP(p);
  10140. if AndTest then
  10141. RemoveInstruction(hp2);
  10142. result:=true;
  10143. exit;
  10144. end;
  10145. end
  10146. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10147. (
  10148. { Bitwise operations only }
  10149. (taicpu(hp1).opcode=A_AND) or
  10150. (taicpu(hp1).opcode=A_TEST) or
  10151. (
  10152. (taicpu(hp1).oper[0]^.typ = top_const) and
  10153. (
  10154. (taicpu(hp1).opcode=A_OR) or
  10155. (taicpu(hp1).opcode=A_XOR)
  10156. )
  10157. )
  10158. ) and
  10159. (
  10160. (taicpu(hp1).oper[0]^.typ = top_const) or
  10161. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10162. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10163. ) then
  10164. begin
  10165. { change
  10166. movx %reg2,%reg2
  10167. op const,%reg2
  10168. into
  10169. op const,%reg2 (smaller version)
  10170. movx %reg2,%reg2
  10171. also change
  10172. movx %reg1,%reg2
  10173. and/test (oper),%reg2
  10174. dealloc %reg2
  10175. into
  10176. and/test (oper),%reg1
  10177. }
  10178. case taicpu(p).opsize of
  10179. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10180. begin
  10181. NewSize := S_B;
  10182. NewRegSize := R_SUBL;
  10183. Limit := $FF;
  10184. end;
  10185. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10186. begin
  10187. NewSize := S_W;
  10188. NewRegSize := R_SUBW;
  10189. Limit := $FFFF;
  10190. end;
  10191. {$ifdef x86_64}
  10192. S_LQ:
  10193. begin
  10194. NewSize := S_L;
  10195. NewRegSize := R_SUBD;
  10196. Limit := $FFFFFFFF;
  10197. end;
  10198. {$endif x86_64}
  10199. else
  10200. Internalerror(2021120302);
  10201. end;
  10202. TransferUsedRegs(TmpUsedRegs);
  10203. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10204. if AndTest then
  10205. begin
  10206. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10207. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10208. end
  10209. else
  10210. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10211. if
  10212. (
  10213. (taicpu(p).opcode = A_MOVZX) and
  10214. (
  10215. (taicpu(hp1).opcode=A_AND) or
  10216. (taicpu(hp1).opcode=A_TEST)
  10217. ) and
  10218. not (
  10219. { If both are references, then the final instruction will have
  10220. both operands as references, which is not allowed }
  10221. (taicpu(p).oper[0]^.typ = top_ref) and
  10222. (taicpu(hp1).oper[0]^.typ = top_ref)
  10223. ) and
  10224. not RegUsed
  10225. ) or
  10226. (
  10227. (
  10228. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10229. not RegUsed
  10230. ) and
  10231. (taicpu(p).oper[0]^.typ = top_reg) and
  10232. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10233. (taicpu(hp1).oper[0]^.typ = top_const) and
  10234. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10235. ) then
  10236. begin
  10237. {$if defined(i386) or defined(i8086)}
  10238. { If the target size is 8-bit, make sure we can actually encode it }
  10239. 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
  10240. Exit;
  10241. {$endif i386 or i8086}
  10242. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10243. taicpu(hp1).opsize := NewSize;
  10244. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10245. if AndTest then
  10246. begin
  10247. RemoveInstruction(hp2);
  10248. if not RegUsed then
  10249. begin
  10250. taicpu(hp1).opcode := A_TEST;
  10251. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10252. begin
  10253. { Make sure the reference is the second operand }
  10254. SwapOper := taicpu(hp1).oper[0];
  10255. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10256. taicpu(hp1).oper[1] := SwapOper;
  10257. end;
  10258. end;
  10259. end;
  10260. case taicpu(hp1).oper[0]^.typ of
  10261. top_reg:
  10262. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10263. top_const:
  10264. { For the AND/TEST case }
  10265. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10266. else
  10267. ;
  10268. end;
  10269. if RegUsed then
  10270. begin
  10271. AsmL.Remove(p);
  10272. AsmL.InsertAfter(p, hp1);
  10273. p := hp1;
  10274. end
  10275. else
  10276. RemoveCurrentP(p, hp1);
  10277. result:=true;
  10278. exit;
  10279. end;
  10280. end;
  10281. end;
  10282. if reg_and_hp1_is_instr and
  10283. (taicpu(p).oper[0]^.typ = top_reg) and
  10284. (
  10285. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10286. ) and
  10287. (taicpu(hp1).oper[0]^.typ = top_const) and
  10288. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10289. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10290. { Minimum shift value allowed is the bit difference between the sizes }
  10291. (taicpu(hp1).oper[0]^.val >=
  10292. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10293. 8 * (
  10294. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10295. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10296. )
  10297. ) then
  10298. begin
  10299. { For:
  10300. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10301. shl/sal ##, %reg1
  10302. Remove the movsx/movzx instruction if the shift overwrites the
  10303. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10304. }
  10305. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10306. RemoveCurrentP(p, hp1);
  10307. Result := True;
  10308. Exit;
  10309. end
  10310. else if reg_and_hp1_is_instr and
  10311. (taicpu(p).oper[0]^.typ = top_reg) and
  10312. (
  10313. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10314. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10315. ) and
  10316. (taicpu(hp1).oper[0]^.typ = top_const) and
  10317. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10318. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10319. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10320. (taicpu(hp1).oper[0]^.val <
  10321. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10322. 8 * (
  10323. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10324. )
  10325. ) then
  10326. begin
  10327. { For:
  10328. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10329. sar ##, %reg1 shr ##, %reg1
  10330. Move the shift to before the movx instruction if the shift value
  10331. is not too large.
  10332. }
  10333. asml.Remove(hp1);
  10334. asml.InsertBefore(hp1, p);
  10335. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10336. case taicpu(p).opsize of
  10337. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10338. taicpu(hp1).opsize := S_B;
  10339. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10340. taicpu(hp1).opsize := S_W;
  10341. {$ifdef x86_64}
  10342. S_LQ:
  10343. taicpu(hp1).opsize := S_L;
  10344. {$endif}
  10345. else
  10346. InternalError(2020112401);
  10347. end;
  10348. if (taicpu(hp1).opcode = A_SHR) then
  10349. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10350. else
  10351. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10352. Result := True;
  10353. end;
  10354. if reg_and_hp1_is_instr and
  10355. (taicpu(p).oper[0]^.typ = top_reg) and
  10356. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10357. (
  10358. (taicpu(hp1).opcode = taicpu(p).opcode)
  10359. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10360. {$ifdef x86_64}
  10361. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10362. {$endif x86_64}
  10363. ) then
  10364. begin
  10365. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10366. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10367. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10368. begin
  10369. {
  10370. For example:
  10371. movzbw %al,%ax
  10372. movzwl %ax,%eax
  10373. Compress into:
  10374. movzbl %al,%eax
  10375. }
  10376. RegUsed := False;
  10377. case taicpu(p).opsize of
  10378. S_BW:
  10379. case taicpu(hp1).opsize of
  10380. S_WL:
  10381. begin
  10382. taicpu(p).opsize := S_BL;
  10383. RegUsed := True;
  10384. end;
  10385. {$ifdef x86_64}
  10386. S_WQ:
  10387. begin
  10388. if taicpu(p).opcode = A_MOVZX then
  10389. begin
  10390. taicpu(p).opsize := S_BL;
  10391. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10392. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10393. end
  10394. else
  10395. taicpu(p).opsize := S_BQ;
  10396. RegUsed := True;
  10397. end;
  10398. {$endif x86_64}
  10399. else
  10400. ;
  10401. end;
  10402. {$ifdef x86_64}
  10403. S_BL:
  10404. case taicpu(hp1).opsize of
  10405. S_LQ:
  10406. begin
  10407. if taicpu(p).opcode = A_MOVZX then
  10408. begin
  10409. taicpu(p).opsize := S_BL;
  10410. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10411. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10412. end
  10413. else
  10414. taicpu(p).opsize := S_BQ;
  10415. RegUsed := True;
  10416. end;
  10417. else
  10418. ;
  10419. end;
  10420. S_WL:
  10421. case taicpu(hp1).opsize of
  10422. S_LQ:
  10423. begin
  10424. if taicpu(p).opcode = A_MOVZX then
  10425. begin
  10426. taicpu(p).opsize := S_WL;
  10427. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10428. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10429. end
  10430. else
  10431. taicpu(p).opsize := S_WQ;
  10432. RegUsed := True;
  10433. end;
  10434. else
  10435. ;
  10436. end;
  10437. {$endif x86_64}
  10438. else
  10439. ;
  10440. end;
  10441. if RegUsed then
  10442. begin
  10443. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10444. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10445. RemoveInstruction(hp1);
  10446. Result := True;
  10447. Exit;
  10448. end;
  10449. end;
  10450. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10451. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10452. GetNextInstruction(hp1, hp2) and
  10453. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10454. (
  10455. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10456. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10457. {$ifdef x86_64}
  10458. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10459. {$endif x86_64}
  10460. ) and
  10461. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10462. (
  10463. (
  10464. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10465. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10466. ) or
  10467. (
  10468. { Only allow the operands in reverse order for TEST instructions }
  10469. (taicpu(hp2).opcode = A_TEST) and
  10470. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10471. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10472. )
  10473. ) then
  10474. begin
  10475. {
  10476. For example:
  10477. movzbl %al,%eax
  10478. movzbl (ref),%edx
  10479. andl %edx,%eax
  10480. (%edx deallocated)
  10481. Change to:
  10482. andb (ref),%al
  10483. movzbl %al,%eax
  10484. Rules are:
  10485. - First two instructions have the same opcode and opsize
  10486. - First instruction's operands are the same super-register
  10487. - Second instruction operates on a different register
  10488. - Third instruction is AND, OR, XOR or TEST
  10489. - Third instruction's operands are the destination registers of the first two instructions
  10490. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10491. - Second instruction's destination register is deallocated afterwards
  10492. }
  10493. TransferUsedRegs(TmpUsedRegs);
  10494. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10495. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10496. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10497. begin
  10498. case taicpu(p).opsize of
  10499. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10500. NewSize := S_B;
  10501. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10502. NewSize := S_W;
  10503. {$ifdef x86_64}
  10504. S_LQ:
  10505. NewSize := S_L;
  10506. {$endif x86_64}
  10507. else
  10508. InternalError(2021120301);
  10509. end;
  10510. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10511. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10512. taicpu(hp2).opsize := NewSize;
  10513. RemoveInstruction(hp1);
  10514. { With TEST, it's best to keep the MOVX instruction at the top }
  10515. if (taicpu(hp2).opcode <> A_TEST) then
  10516. begin
  10517. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10518. asml.Remove(p);
  10519. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10520. asml.InsertAfter(p, hp2);
  10521. p := hp2;
  10522. end
  10523. else
  10524. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10525. Result := True;
  10526. Exit;
  10527. end;
  10528. end;
  10529. end;
  10530. if taicpu(p).opcode=A_MOVZX then
  10531. begin
  10532. { removes superfluous And's after movzx's }
  10533. if reg_and_hp1_is_instr and
  10534. (taicpu(hp1).opcode = A_AND) and
  10535. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10536. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10537. {$ifdef x86_64}
  10538. { check for implicit extension to 64 bit }
  10539. or
  10540. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10541. (taicpu(hp1).opsize=S_Q) and
  10542. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10543. )
  10544. {$endif x86_64}
  10545. )
  10546. then
  10547. begin
  10548. case taicpu(p).opsize Of
  10549. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10550. if (taicpu(hp1).oper[0]^.val = $ff) then
  10551. begin
  10552. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10553. RemoveInstruction(hp1);
  10554. Result:=true;
  10555. exit;
  10556. end;
  10557. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10558. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10559. begin
  10560. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10561. RemoveInstruction(hp1);
  10562. Result:=true;
  10563. exit;
  10564. end;
  10565. {$ifdef x86_64}
  10566. S_LQ:
  10567. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10568. begin
  10569. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10570. RemoveInstruction(hp1);
  10571. Result:=true;
  10572. exit;
  10573. end;
  10574. {$endif x86_64}
  10575. else
  10576. ;
  10577. end;
  10578. { we cannot get rid of the and, but can we get rid of the movz ?}
  10579. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10580. begin
  10581. case taicpu(p).opsize Of
  10582. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10583. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10584. begin
  10585. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10586. RemoveCurrentP(p,hp1);
  10587. Result:=true;
  10588. exit;
  10589. end;
  10590. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10591. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10592. begin
  10593. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10594. RemoveCurrentP(p,hp1);
  10595. Result:=true;
  10596. exit;
  10597. end;
  10598. {$ifdef x86_64}
  10599. S_LQ:
  10600. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10601. begin
  10602. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10603. RemoveCurrentP(p,hp1);
  10604. Result:=true;
  10605. exit;
  10606. end;
  10607. {$endif x86_64}
  10608. else
  10609. ;
  10610. end;
  10611. end;
  10612. end;
  10613. { changes some movzx constructs to faster synonyms (all examples
  10614. are given with eax/ax, but are also valid for other registers)}
  10615. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10616. begin
  10617. case taicpu(p).opsize of
  10618. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10619. (the machine code is equivalent to movzbl %al,%eax), but the
  10620. code generator still generates that assembler instruction and
  10621. it is silently converted. This should probably be checked.
  10622. [Kit] }
  10623. S_BW:
  10624. begin
  10625. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10626. (
  10627. not IsMOVZXAcceptable
  10628. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10629. or (
  10630. (cs_opt_size in current_settings.optimizerswitches) and
  10631. (taicpu(p).oper[1]^.reg = NR_AX)
  10632. )
  10633. ) then
  10634. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10635. begin
  10636. DebugMsg(SPeepholeOptimization + 'var7',p);
  10637. taicpu(p).opcode := A_AND;
  10638. taicpu(p).changeopsize(S_W);
  10639. taicpu(p).loadConst(0,$ff);
  10640. Result := True;
  10641. end
  10642. else if not IsMOVZXAcceptable and
  10643. GetNextInstruction(p, hp1) and
  10644. (tai(hp1).typ = ait_instruction) and
  10645. (taicpu(hp1).opcode = A_AND) and
  10646. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10647. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10648. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10649. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10650. begin
  10651. DebugMsg(SPeepholeOptimization + 'var8',p);
  10652. taicpu(p).opcode := A_MOV;
  10653. taicpu(p).changeopsize(S_W);
  10654. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10655. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10656. Result := True;
  10657. end;
  10658. end;
  10659. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10660. S_BL:
  10661. begin
  10662. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10663. (
  10664. not IsMOVZXAcceptable
  10665. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10666. or (
  10667. (cs_opt_size in current_settings.optimizerswitches) and
  10668. (taicpu(p).oper[1]^.reg = NR_EAX)
  10669. )
  10670. ) then
  10671. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10672. begin
  10673. DebugMsg(SPeepholeOptimization + 'var9',p);
  10674. taicpu(p).opcode := A_AND;
  10675. taicpu(p).changeopsize(S_L);
  10676. taicpu(p).loadConst(0,$ff);
  10677. Result := True;
  10678. end
  10679. else if not IsMOVZXAcceptable and
  10680. GetNextInstruction(p, hp1) and
  10681. (tai(hp1).typ = ait_instruction) and
  10682. (taicpu(hp1).opcode = A_AND) and
  10683. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10684. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10685. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10686. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10687. begin
  10688. DebugMsg(SPeepholeOptimization + 'var10',p);
  10689. taicpu(p).opcode := A_MOV;
  10690. taicpu(p).changeopsize(S_L);
  10691. { do not use R_SUBWHOLE
  10692. as movl %rdx,%eax
  10693. is invalid in assembler PM }
  10694. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10695. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10696. Result := True;
  10697. end;
  10698. end;
  10699. {$endif i8086}
  10700. S_WL:
  10701. if not IsMOVZXAcceptable then
  10702. begin
  10703. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10704. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10705. begin
  10706. DebugMsg(SPeepholeOptimization + 'var11',p);
  10707. taicpu(p).opcode := A_AND;
  10708. taicpu(p).changeopsize(S_L);
  10709. taicpu(p).loadConst(0,$ffff);
  10710. Result := True;
  10711. end
  10712. else if GetNextInstruction(p, hp1) and
  10713. (tai(hp1).typ = ait_instruction) and
  10714. (taicpu(hp1).opcode = A_AND) and
  10715. (taicpu(hp1).oper[0]^.typ = top_const) and
  10716. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10717. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10718. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10719. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10720. begin
  10721. DebugMsg(SPeepholeOptimization + 'var12',p);
  10722. taicpu(p).opcode := A_MOV;
  10723. taicpu(p).changeopsize(S_L);
  10724. { do not use R_SUBWHOLE
  10725. as movl %rdx,%eax
  10726. is invalid in assembler PM }
  10727. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10728. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10729. Result := True;
  10730. end;
  10731. end;
  10732. else
  10733. InternalError(2017050705);
  10734. end;
  10735. end
  10736. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10737. begin
  10738. if GetNextInstruction(p, hp1) and
  10739. (tai(hp1).typ = ait_instruction) and
  10740. (taicpu(hp1).opcode = A_AND) and
  10741. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10742. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10743. begin
  10744. //taicpu(p).opcode := A_MOV;
  10745. case taicpu(p).opsize Of
  10746. S_BL:
  10747. begin
  10748. DebugMsg(SPeepholeOptimization + 'var13',p);
  10749. taicpu(hp1).changeopsize(S_L);
  10750. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10751. end;
  10752. S_WL:
  10753. begin
  10754. DebugMsg(SPeepholeOptimization + 'var14',p);
  10755. taicpu(hp1).changeopsize(S_L);
  10756. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10757. end;
  10758. S_BW:
  10759. begin
  10760. DebugMsg(SPeepholeOptimization + 'var15',p);
  10761. taicpu(hp1).changeopsize(S_W);
  10762. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10763. end;
  10764. else
  10765. Internalerror(2017050704)
  10766. end;
  10767. Result := True;
  10768. end;
  10769. end;
  10770. end;
  10771. end;
  10772. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10773. var
  10774. hp1, hp2 : tai;
  10775. MaskLength : Cardinal;
  10776. MaskedBits : TCgInt;
  10777. ActiveReg : TRegister;
  10778. begin
  10779. Result:=false;
  10780. { There are no optimisations for reference targets }
  10781. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10782. Exit;
  10783. while GetNextInstruction(p, hp1) and
  10784. (hp1.typ = ait_instruction) do
  10785. begin
  10786. if (taicpu(p).oper[0]^.typ = top_const) then
  10787. begin
  10788. case taicpu(hp1).opcode of
  10789. A_AND:
  10790. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10791. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10792. { the second register must contain the first one, so compare their subreg types }
  10793. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10794. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10795. { change
  10796. and const1, reg
  10797. and const2, reg
  10798. to
  10799. and (const1 and const2), reg
  10800. }
  10801. begin
  10802. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10803. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10804. RemoveCurrentP(p, hp1);
  10805. Result:=true;
  10806. exit;
  10807. end;
  10808. A_CMP:
  10809. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10810. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10811. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10812. { Just check that the condition on the next instruction is compatible }
  10813. GetNextInstruction(hp1, hp2) and
  10814. (hp2.typ = ait_instruction) and
  10815. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10816. then
  10817. { change
  10818. and 2^n, reg
  10819. cmp 2^n, reg
  10820. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10821. to
  10822. and 2^n, reg
  10823. test reg, reg
  10824. j(~c) / set(~c) / cmov(~c)
  10825. }
  10826. begin
  10827. { Keep TEST instruction in, rather than remove it, because
  10828. it may trigger other optimisations such as MovAndTest2Test }
  10829. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10830. taicpu(hp1).opcode := A_TEST;
  10831. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10832. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10833. Result := True;
  10834. Exit;
  10835. end;
  10836. A_MOVZX:
  10837. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10838. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10839. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10840. (
  10841. (
  10842. (taicpu(p).opsize=S_W) and
  10843. (taicpu(hp1).opsize=S_BW)
  10844. ) or
  10845. (
  10846. (taicpu(p).opsize=S_L) and
  10847. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10848. )
  10849. {$ifdef x86_64}
  10850. or
  10851. (
  10852. (taicpu(p).opsize=S_Q) and
  10853. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10854. )
  10855. {$endif x86_64}
  10856. ) then
  10857. begin
  10858. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10859. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10860. ) or
  10861. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10862. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10863. then
  10864. begin
  10865. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10866. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10867. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10868. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10869. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10870. }
  10871. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10872. RemoveInstruction(hp1);
  10873. { See if there are other optimisations possible }
  10874. Continue;
  10875. end;
  10876. end;
  10877. A_SHL:
  10878. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10879. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10880. begin
  10881. {$ifopt R+}
  10882. {$define RANGE_WAS_ON}
  10883. {$R-}
  10884. {$endif}
  10885. { get length of potential and mask }
  10886. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10887. { really a mask? }
  10888. {$ifdef RANGE_WAS_ON}
  10889. {$R+}
  10890. {$endif}
  10891. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10892. { unmasked part shifted out? }
  10893. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10894. begin
  10895. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10896. RemoveCurrentP(p, hp1);
  10897. Result:=true;
  10898. exit;
  10899. end;
  10900. end;
  10901. A_SHR:
  10902. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10903. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10904. (taicpu(hp1).oper[0]^.val <= 63) then
  10905. begin
  10906. { Does SHR combined with the AND cover all the bits?
  10907. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10908. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10909. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10910. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10911. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10912. begin
  10913. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10914. RemoveCurrentP(p, hp1);
  10915. Result := True;
  10916. Exit;
  10917. end;
  10918. end;
  10919. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10920. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10921. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10922. begin
  10923. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10924. (
  10925. (
  10926. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10927. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10928. ) or (
  10929. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10930. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10931. {$ifdef x86_64}
  10932. ) or (
  10933. (taicpu(hp1).opsize = S_LQ) and
  10934. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10935. {$endif x86_64}
  10936. )
  10937. ) then
  10938. begin
  10939. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10940. begin
  10941. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10942. RemoveInstruction(hp1);
  10943. { See if there are other optimisations possible }
  10944. Continue;
  10945. end;
  10946. { The super-registers are the same though.
  10947. Note that this change by itself doesn't improve
  10948. code speed, but it opens up other optimisations. }
  10949. {$ifdef x86_64}
  10950. { Convert 64-bit register to 32-bit }
  10951. case taicpu(hp1).opsize of
  10952. S_BQ:
  10953. begin
  10954. taicpu(hp1).opsize := S_BL;
  10955. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10956. end;
  10957. S_WQ:
  10958. begin
  10959. taicpu(hp1).opsize := S_WL;
  10960. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10961. end
  10962. else
  10963. ;
  10964. end;
  10965. {$endif x86_64}
  10966. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10967. taicpu(hp1).opcode := A_MOVZX;
  10968. { See if there are other optimisations possible }
  10969. Continue;
  10970. end;
  10971. end;
  10972. else
  10973. ;
  10974. end;
  10975. end
  10976. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10977. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10978. begin
  10979. {$ifdef x86_64}
  10980. if (taicpu(p).opsize = S_Q) then
  10981. begin
  10982. { Never necessary }
  10983. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10984. RemoveCurrentP(p, hp1);
  10985. Result := True;
  10986. Exit;
  10987. end;
  10988. {$endif x86_64}
  10989. { Forward check to determine necessity of and %reg,%reg }
  10990. TransferUsedRegs(TmpUsedRegs);
  10991. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10992. { Saves on a bunch of dereferences }
  10993. ActiveReg := taicpu(p).oper[1]^.reg;
  10994. case taicpu(hp1).opcode of
  10995. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10996. if (
  10997. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10998. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10999. ) and
  11000. (
  11001. (taicpu(hp1).opcode <> A_MOV) or
  11002. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11003. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11004. ) and
  11005. not (
  11006. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11007. (taicpu(hp1).opcode = A_MOV) and
  11008. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11009. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11010. ) and
  11011. (
  11012. (
  11013. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11014. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11015. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11016. ) or
  11017. (
  11018. {$ifdef x86_64}
  11019. (
  11020. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11021. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11022. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11023. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11024. ) and
  11025. {$endif x86_64}
  11026. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11027. )
  11028. ) then
  11029. begin
  11030. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11031. RemoveCurrentP(p, hp1);
  11032. Result := True;
  11033. Exit;
  11034. end;
  11035. A_ADD,
  11036. A_AND,
  11037. A_BSF,
  11038. A_BSR,
  11039. A_BTC,
  11040. A_BTR,
  11041. A_BTS,
  11042. A_OR,
  11043. A_SUB,
  11044. A_XOR:
  11045. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11046. if (
  11047. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11048. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11049. ) and
  11050. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11051. begin
  11052. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11053. RemoveCurrentP(p, hp1);
  11054. Result := True;
  11055. Exit;
  11056. end;
  11057. A_CMP,
  11058. A_TEST:
  11059. if (
  11060. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11061. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11062. ) and
  11063. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11064. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11065. begin
  11066. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11067. RemoveCurrentP(p, hp1);
  11068. Result := True;
  11069. Exit;
  11070. end;
  11071. A_BSWAP,
  11072. A_NEG,
  11073. A_NOT:
  11074. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11075. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11076. begin
  11077. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11078. RemoveCurrentP(p, hp1);
  11079. Result := True;
  11080. Exit;
  11081. end;
  11082. else
  11083. ;
  11084. end;
  11085. end;
  11086. if (taicpu(hp1).is_jmp) and
  11087. (taicpu(hp1).opcode<>A_JMP) and
  11088. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11089. begin
  11090. { change
  11091. and x, reg
  11092. jxx
  11093. to
  11094. test x, reg
  11095. jxx
  11096. if reg is deallocated before the
  11097. jump, but only if it's a conditional jump (PFV)
  11098. }
  11099. taicpu(p).opcode := A_TEST;
  11100. Exit;
  11101. end;
  11102. Break;
  11103. end;
  11104. { Lone AND tests }
  11105. if (taicpu(p).oper[0]^.typ = top_const) then
  11106. begin
  11107. {
  11108. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11109. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11110. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11111. }
  11112. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11113. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11114. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11115. begin
  11116. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11117. if taicpu(p).opsize = S_L then
  11118. begin
  11119. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11120. Result := True;
  11121. end;
  11122. end;
  11123. end;
  11124. { Backward check to determine necessity of and %reg,%reg }
  11125. if (taicpu(p).oper[0]^.typ = top_reg) and
  11126. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11127. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11128. GetLastInstruction(p, hp2) and
  11129. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11130. { Check size of adjacent instruction to determine if the AND is
  11131. effectively a null operation }
  11132. (
  11133. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11134. { Note: Don't include S_Q }
  11135. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11136. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11137. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11138. ) then
  11139. begin
  11140. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11141. { If GetNextInstruction returned False, hp1 will be nil }
  11142. RemoveCurrentP(p, hp1);
  11143. Result := True;
  11144. Exit;
  11145. end;
  11146. end;
  11147. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11148. var
  11149. hp1: tai; NewRef: TReference;
  11150. { This entire nested function is used in an if-statement below, but we
  11151. want to avoid all the used reg transfers and GetNextInstruction calls
  11152. until we really have to check }
  11153. function MemRegisterNotUsedLater: Boolean; inline;
  11154. var
  11155. hp2: tai;
  11156. begin
  11157. TransferUsedRegs(TmpUsedRegs);
  11158. hp2 := p;
  11159. repeat
  11160. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11161. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11162. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11163. end;
  11164. begin
  11165. Result := False;
  11166. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11167. Exit;
  11168. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11169. begin
  11170. { Change:
  11171. add %reg2,%reg1
  11172. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11173. To:
  11174. mov/s/z #(%reg1,%reg2),%reg1
  11175. }
  11176. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11177. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11178. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11179. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11180. (
  11181. (
  11182. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11183. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11184. { r/esp cannot be an index }
  11185. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11186. ) or (
  11187. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11188. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11189. )
  11190. ) and (
  11191. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11192. (
  11193. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11194. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11195. MemRegisterNotUsedLater
  11196. )
  11197. ) then
  11198. begin
  11199. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11200. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11201. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11202. RemoveCurrentp(p, hp1);
  11203. Result := True;
  11204. Exit;
  11205. end;
  11206. { Change:
  11207. addl/q $x,%reg1
  11208. movl/q %reg1,%reg2
  11209. To:
  11210. leal/q $x(%reg1),%reg2
  11211. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11212. Breaks the dependency chain.
  11213. }
  11214. if MatchOpType(taicpu(p),top_const,top_reg) and
  11215. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11216. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11217. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11218. (
  11219. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11220. not (cs_opt_size in current_settings.optimizerswitches) or
  11221. (
  11222. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11223. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11224. )
  11225. ) then
  11226. begin
  11227. { Change the MOV instruction to a LEA instruction, and update the
  11228. first operand }
  11229. reference_reset(NewRef, 1, []);
  11230. NewRef.base := taicpu(p).oper[1]^.reg;
  11231. NewRef.scalefactor := 1;
  11232. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11233. taicpu(hp1).opcode := A_LEA;
  11234. taicpu(hp1).loadref(0, NewRef);
  11235. TransferUsedRegs(TmpUsedRegs);
  11236. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11237. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11238. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11239. begin
  11240. { Move what is now the LEA instruction to before the SUB instruction }
  11241. Asml.Remove(hp1);
  11242. Asml.InsertBefore(hp1, p);
  11243. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11244. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11245. p := hp1;
  11246. end
  11247. else
  11248. begin
  11249. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11250. RemoveCurrentP(p, hp1);
  11251. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11252. end;
  11253. Result := True;
  11254. end;
  11255. end;
  11256. end;
  11257. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11258. var
  11259. SubReg: TSubRegister;
  11260. begin
  11261. Result:=false;
  11262. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11263. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11264. with taicpu(p).oper[0]^.ref^ do
  11265. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11266. begin
  11267. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11268. begin
  11269. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11270. taicpu(p).opcode := A_ADD;
  11271. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11272. Result := True;
  11273. end
  11274. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11275. begin
  11276. if (base <> NR_NO) then
  11277. begin
  11278. if (scalefactor <= 1) then
  11279. begin
  11280. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11281. taicpu(p).opcode := A_ADD;
  11282. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11283. Result := True;
  11284. end;
  11285. end
  11286. else
  11287. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11288. if (scalefactor in [2, 4, 8]) then
  11289. begin
  11290. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11291. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11292. taicpu(p).opcode := A_SHL;
  11293. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11294. Result := True;
  11295. end;
  11296. end;
  11297. end;
  11298. end;
  11299. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11300. var
  11301. hp1: tai; NewRef: TReference;
  11302. begin
  11303. { Change:
  11304. subl/q $x,%reg1
  11305. movl/q %reg1,%reg2
  11306. To:
  11307. leal/q $-x(%reg1),%reg2
  11308. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11309. Breaks the dependency chain and potentially permits the removal of
  11310. a CMP instruction if one follows.
  11311. }
  11312. Result := False;
  11313. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11314. MatchOpType(taicpu(p),top_const,top_reg) and
  11315. GetNextInstruction(p, hp1) and
  11316. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11317. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11318. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11319. (
  11320. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11321. not (cs_opt_size in current_settings.optimizerswitches) or
  11322. (
  11323. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11324. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11325. )
  11326. ) then
  11327. begin
  11328. { Change the MOV instruction to a LEA instruction, and update the
  11329. first operand }
  11330. reference_reset(NewRef, 1, []);
  11331. NewRef.base := taicpu(p).oper[1]^.reg;
  11332. NewRef.scalefactor := 1;
  11333. NewRef.offset := -taicpu(p).oper[0]^.val;
  11334. taicpu(hp1).opcode := A_LEA;
  11335. taicpu(hp1).loadref(0, NewRef);
  11336. TransferUsedRegs(TmpUsedRegs);
  11337. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11338. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11339. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11340. begin
  11341. { Move what is now the LEA instruction to before the SUB instruction }
  11342. Asml.Remove(hp1);
  11343. Asml.InsertBefore(hp1, p);
  11344. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11345. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11346. p := hp1;
  11347. end
  11348. else
  11349. begin
  11350. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11351. RemoveCurrentP(p, hp1);
  11352. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11353. end;
  11354. Result := True;
  11355. end;
  11356. end;
  11357. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11358. begin
  11359. { we can skip all instructions not messing with the stack pointer }
  11360. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11361. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11362. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11363. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11364. ({(taicpu(hp1).ops=0) or }
  11365. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11366. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11367. ) and }
  11368. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11369. )
  11370. ) do
  11371. GetNextInstruction(hp1,hp1);
  11372. Result:=assigned(hp1);
  11373. end;
  11374. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11375. var
  11376. hp1, hp2, hp3, hp4, hp5: tai;
  11377. begin
  11378. Result:=false;
  11379. hp5:=nil;
  11380. { replace
  11381. leal(q) x(<stackpointer>),<stackpointer>
  11382. call procname
  11383. leal(q) -x(<stackpointer>),<stackpointer>
  11384. ret
  11385. by
  11386. jmp procname
  11387. but do it only on level 4 because it destroys stack back traces
  11388. }
  11389. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11390. MatchOpType(taicpu(p),top_ref,top_reg) and
  11391. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11392. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11393. { the -8 or -24 are not required, but bail out early if possible,
  11394. higher values are unlikely }
  11395. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11396. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11397. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11398. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11399. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11400. GetNextInstruction(p, hp1) and
  11401. { Take a copy of hp1 }
  11402. SetAndTest(hp1, hp4) and
  11403. { trick to skip label }
  11404. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11405. SkipSimpleInstructions(hp1) and
  11406. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11407. GetNextInstruction(hp1, hp2) and
  11408. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11409. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11410. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11411. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11412. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11413. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11414. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11415. { Segment register will be NR_NO }
  11416. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11417. GetNextInstruction(hp2, hp3) and
  11418. { trick to skip label }
  11419. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11420. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11421. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11422. SetAndTest(hp3,hp5) and
  11423. GetNextInstruction(hp3,hp3) and
  11424. MatchInstruction(hp3,A_RET,[S_NO])
  11425. )
  11426. ) and
  11427. (taicpu(hp3).ops=0) then
  11428. begin
  11429. taicpu(hp1).opcode := A_JMP;
  11430. taicpu(hp1).is_jmp := true;
  11431. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11432. RemoveCurrentP(p, hp4);
  11433. RemoveInstruction(hp2);
  11434. RemoveInstruction(hp3);
  11435. if Assigned(hp5) then
  11436. begin
  11437. AsmL.Remove(hp5);
  11438. ASmL.InsertBefore(hp5,hp1)
  11439. end;
  11440. Result:=true;
  11441. end;
  11442. end;
  11443. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11444. {$ifdef x86_64}
  11445. var
  11446. hp1, hp2, hp3, hp4, hp5: tai;
  11447. {$endif x86_64}
  11448. begin
  11449. Result:=false;
  11450. {$ifdef x86_64}
  11451. hp5:=nil;
  11452. { replace
  11453. push %rax
  11454. call procname
  11455. pop %rcx
  11456. ret
  11457. by
  11458. jmp procname
  11459. but do it only on level 4 because it destroys stack back traces
  11460. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11461. for all supported calling conventions
  11462. }
  11463. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11464. MatchOpType(taicpu(p),top_reg) and
  11465. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11466. GetNextInstruction(p, hp1) and
  11467. { Take a copy of hp1 }
  11468. SetAndTest(hp1, hp4) and
  11469. { trick to skip label }
  11470. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11471. SkipSimpleInstructions(hp1) and
  11472. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11473. GetNextInstruction(hp1, hp2) and
  11474. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11475. MatchOpType(taicpu(hp2),top_reg) and
  11476. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11477. GetNextInstruction(hp2, hp3) and
  11478. { trick to skip label }
  11479. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11480. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11481. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11482. SetAndTest(hp3,hp5) and
  11483. GetNextInstruction(hp3,hp3) and
  11484. MatchInstruction(hp3,A_RET,[S_NO])
  11485. )
  11486. ) and
  11487. (taicpu(hp3).ops=0) then
  11488. begin
  11489. taicpu(hp1).opcode := A_JMP;
  11490. taicpu(hp1).is_jmp := true;
  11491. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11492. RemoveCurrentP(p, hp4);
  11493. RemoveInstruction(hp2);
  11494. RemoveInstruction(hp3);
  11495. if Assigned(hp5) then
  11496. begin
  11497. AsmL.Remove(hp5);
  11498. ASmL.InsertBefore(hp5,hp1)
  11499. end;
  11500. Result:=true;
  11501. end;
  11502. {$endif x86_64}
  11503. end;
  11504. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11505. var
  11506. Value, RegName: string;
  11507. begin
  11508. Result:=false;
  11509. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11510. begin
  11511. case taicpu(p).oper[0]^.val of
  11512. 0:
  11513. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11514. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11515. begin
  11516. { change "mov $0,%reg" into "xor %reg,%reg" }
  11517. taicpu(p).opcode := A_XOR;
  11518. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11519. Result := True;
  11520. {$ifdef x86_64}
  11521. end
  11522. else if (taicpu(p).opsize = S_Q) then
  11523. begin
  11524. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11525. { The actual optimization }
  11526. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11527. taicpu(p).changeopsize(S_L);
  11528. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11529. Result := True;
  11530. end;
  11531. $1..$FFFFFFFF:
  11532. begin
  11533. { Code size reduction by J. Gareth "Kit" Moreton }
  11534. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11535. case taicpu(p).opsize of
  11536. S_Q:
  11537. begin
  11538. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11539. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11540. { The actual optimization }
  11541. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11542. taicpu(p).changeopsize(S_L);
  11543. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11544. Result := True;
  11545. end;
  11546. else
  11547. { Do nothing };
  11548. end;
  11549. {$endif x86_64}
  11550. end;
  11551. -1:
  11552. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11553. if (cs_opt_size in current_settings.optimizerswitches) and
  11554. (taicpu(p).opsize <> S_B) and
  11555. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11556. begin
  11557. { change "mov $-1,%reg" into "or $-1,%reg" }
  11558. { NOTES:
  11559. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11560. - This operation creates a false dependency on the register, so only do it when optimising for size
  11561. - 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
  11562. }
  11563. taicpu(p).opcode := A_OR;
  11564. Result := True;
  11565. end;
  11566. else
  11567. { Do nothing };
  11568. end;
  11569. end;
  11570. end;
  11571. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11572. var
  11573. hp1: tai;
  11574. begin
  11575. { Detect:
  11576. andw x, %ax (0 <= x < $8000)
  11577. ...
  11578. movzwl %ax,%eax
  11579. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11580. }
  11581. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11582. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11583. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11584. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11585. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11586. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11587. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11588. begin
  11589. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11590. taicpu(hp1).opcode := A_CWDE;
  11591. taicpu(hp1).clearop(0);
  11592. taicpu(hp1).clearop(1);
  11593. taicpu(hp1).ops := 0;
  11594. { A change was made, but not with p, so move forward 1 }
  11595. p := tai(p.Next);
  11596. Result := True;
  11597. end;
  11598. end;
  11599. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11600. begin
  11601. Result := False;
  11602. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11603. Exit;
  11604. { Convert:
  11605. movswl %ax,%eax -> cwtl
  11606. movslq %eax,%rax -> cdqe
  11607. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11608. refer to the same opcode and depends only on the assembler's
  11609. current operand-size attribute. [Kit]
  11610. }
  11611. with taicpu(p) do
  11612. case opsize of
  11613. S_WL:
  11614. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11615. begin
  11616. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11617. opcode := A_CWDE;
  11618. clearop(0);
  11619. clearop(1);
  11620. ops := 0;
  11621. Result := True;
  11622. end;
  11623. {$ifdef x86_64}
  11624. S_LQ:
  11625. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11626. begin
  11627. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11628. opcode := A_CDQE;
  11629. clearop(0);
  11630. clearop(1);
  11631. ops := 0;
  11632. Result := True;
  11633. end;
  11634. {$endif x86_64}
  11635. else
  11636. ;
  11637. end;
  11638. end;
  11639. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11640. var
  11641. hp1: tai;
  11642. begin
  11643. { Detect:
  11644. shr x, %ax (x > 0)
  11645. ...
  11646. movzwl %ax,%eax
  11647. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11648. }
  11649. Result := False;
  11650. if MatchOpType(taicpu(p), top_const, top_reg) and
  11651. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11652. (taicpu(p).oper[0]^.val > 0) and
  11653. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11654. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11655. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11656. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11657. begin
  11658. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11659. taicpu(hp1).opcode := A_CWDE;
  11660. taicpu(hp1).clearop(0);
  11661. taicpu(hp1).clearop(1);
  11662. taicpu(hp1).ops := 0;
  11663. { A change was made, but not with p, so move forward 1 }
  11664. p := tai(p.Next);
  11665. Result := True;
  11666. end;
  11667. end;
  11668. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11669. var
  11670. hp1, hp2: tai;
  11671. Opposite, SecondOpposite: TAsmOp;
  11672. NewCond: TAsmCond;
  11673. begin
  11674. Result := False;
  11675. { Change:
  11676. add/sub 128,(dest)
  11677. To:
  11678. sub/add -128,(dest)
  11679. This generaally takes fewer bytes to encode because -128 can be stored
  11680. in a signed byte, whereas +128 cannot.
  11681. }
  11682. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11683. begin
  11684. if taicpu(p).opcode = A_ADD then
  11685. Opposite := A_SUB
  11686. else
  11687. Opposite := A_ADD;
  11688. { Be careful if the flags are in use, because the CF flag inverts
  11689. when changing from ADD to SUB and vice versa }
  11690. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11691. GetNextInstruction(p, hp1) then
  11692. begin
  11693. TransferUsedRegs(TmpUsedRegs);
  11694. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11695. hp2 := hp1;
  11696. { Scan ahead to check if everything's safe }
  11697. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11698. begin
  11699. if (hp1.typ <> ait_instruction) then
  11700. { Probably unsafe since the flags are still in use }
  11701. Exit;
  11702. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11703. { Stop searching at an unconditional jump }
  11704. Break;
  11705. if not
  11706. (
  11707. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11708. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11709. ) and
  11710. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11711. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11712. Exit;
  11713. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11714. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11715. { Move to the next instruction }
  11716. GetNextInstruction(hp1, hp1);
  11717. end;
  11718. while Assigned(hp2) and (hp2 <> hp1) do
  11719. begin
  11720. NewCond := C_None;
  11721. case taicpu(hp2).condition of
  11722. C_A, C_NBE:
  11723. NewCond := C_BE;
  11724. C_B, C_C, C_NAE:
  11725. NewCond := C_AE;
  11726. C_AE, C_NB, C_NC:
  11727. NewCond := C_B;
  11728. C_BE, C_NA:
  11729. NewCond := C_A;
  11730. else
  11731. { No change needed };
  11732. end;
  11733. if NewCond <> C_None then
  11734. begin
  11735. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11736. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11737. taicpu(hp2).condition := NewCond;
  11738. end
  11739. else
  11740. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11741. begin
  11742. { Because of the flipping of the carry bit, to ensure
  11743. the operation remains equivalent, ADC becomes SBB
  11744. and vice versa, and the constant is not-inverted.
  11745. If multiple ADCs or SBBs appear in a row, each one
  11746. changed causes the carry bit to invert, so they all
  11747. need to be flipped }
  11748. if taicpu(hp2).opcode = A_ADC then
  11749. SecondOpposite := A_SBB
  11750. else
  11751. SecondOpposite := A_ADC;
  11752. if taicpu(hp2).oper[0]^.typ <> top_const then
  11753. { Should have broken out of this optimisation already }
  11754. InternalError(2021112901);
  11755. 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]^) + ' -> ' +
  11756. 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);
  11757. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11758. taicpu(hp2).opcode := SecondOpposite;
  11759. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11760. end;
  11761. { Move to the next instruction }
  11762. GetNextInstruction(hp2, hp2);
  11763. end;
  11764. if (hp2 <> hp1) then
  11765. InternalError(2021111501);
  11766. end;
  11767. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11768. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11769. taicpu(p).opcode := Opposite;
  11770. taicpu(p).oper[0]^.val := -128;
  11771. { No further optimisations can be made on this instruction, so move
  11772. onto the next one to save time }
  11773. p := tai(p.Next);
  11774. UpdateUsedRegs(p);
  11775. Result := True;
  11776. Exit;
  11777. end;
  11778. { Detect:
  11779. add/sub %reg2,(dest)
  11780. add/sub x, (dest)
  11781. (dest can be a register or a reference)
  11782. Swap the instructions to minimise a pipeline stall. This reverses the
  11783. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11784. optimisations could be made.
  11785. }
  11786. if (taicpu(p).oper[0]^.typ = top_reg) and
  11787. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11788. (
  11789. (
  11790. (taicpu(p).oper[1]^.typ = top_reg) and
  11791. { We can try searching further ahead if we're writing to a register }
  11792. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11793. ) or
  11794. (
  11795. (taicpu(p).oper[1]^.typ = top_ref) and
  11796. GetNextInstruction(p, hp1)
  11797. )
  11798. ) and
  11799. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11800. (taicpu(hp1).oper[0]^.typ = top_const) and
  11801. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11802. begin
  11803. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11804. TransferUsedRegs(TmpUsedRegs);
  11805. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11806. hp2 := p;
  11807. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11808. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11809. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11810. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11811. begin
  11812. asml.remove(hp1);
  11813. asml.InsertBefore(hp1, p);
  11814. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11815. Result := True;
  11816. end;
  11817. end;
  11818. end;
  11819. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11820. begin
  11821. Result:=false;
  11822. { change "cmp $0, %reg" to "test %reg, %reg" }
  11823. if MatchOpType(taicpu(p),top_const,top_reg) and
  11824. (taicpu(p).oper[0]^.val = 0) then
  11825. begin
  11826. taicpu(p).opcode := A_TEST;
  11827. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11828. Result:=true;
  11829. end;
  11830. end;
  11831. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11832. var
  11833. IsTestConstX : Boolean;
  11834. hp1,hp2 : tai;
  11835. begin
  11836. Result:=false;
  11837. { removes the line marked with (x) from the sequence
  11838. and/or/xor/add/sub/... $x, %y
  11839. test/or %y, %y | test $-1, %y (x)
  11840. j(n)z _Label
  11841. as the first instruction already adjusts the ZF
  11842. %y operand may also be a reference }
  11843. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11844. MatchOperand(taicpu(p).oper[0]^,-1);
  11845. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11846. GetLastInstruction(p, hp1) and
  11847. (tai(hp1).typ = ait_instruction) and
  11848. GetNextInstruction(p,hp2) and
  11849. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11850. case taicpu(hp1).opcode Of
  11851. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11852. { These two instructions set the zero flag if the result is zero }
  11853. A_POPCNT, A_LZCNT:
  11854. begin
  11855. if (
  11856. { With POPCNT, an input of zero will set the zero flag
  11857. because the population count of zero is zero }
  11858. (taicpu(hp1).opcode = A_POPCNT) and
  11859. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11860. (
  11861. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11862. { Faster than going through the second half of the 'or'
  11863. condition below }
  11864. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11865. )
  11866. ) or (
  11867. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11868. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11869. { and in case of carry for A(E)/B(E)/C/NC }
  11870. (
  11871. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11872. (
  11873. (taicpu(hp1).opcode <> A_ADD) and
  11874. (taicpu(hp1).opcode <> A_SUB) and
  11875. (taicpu(hp1).opcode <> A_LZCNT)
  11876. )
  11877. )
  11878. ) then
  11879. begin
  11880. RemoveCurrentP(p, hp2);
  11881. Result:=true;
  11882. Exit;
  11883. end;
  11884. end;
  11885. A_SHL, A_SAL, A_SHR, A_SAR:
  11886. begin
  11887. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11888. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11889. { therefore, it's only safe to do this optimization for }
  11890. { shifts by a (nonzero) constant }
  11891. (taicpu(hp1).oper[0]^.typ = top_const) and
  11892. (taicpu(hp1).oper[0]^.val <> 0) and
  11893. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11894. { and in case of carry for A(E)/B(E)/C/NC }
  11895. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11896. begin
  11897. RemoveCurrentP(p, hp2);
  11898. Result:=true;
  11899. Exit;
  11900. end;
  11901. end;
  11902. A_DEC, A_INC, A_NEG:
  11903. begin
  11904. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11905. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11906. { and in case of carry for A(E)/B(E)/C/NC }
  11907. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11908. begin
  11909. RemoveCurrentP(p, hp2);
  11910. Result:=true;
  11911. Exit;
  11912. end;
  11913. end
  11914. else
  11915. ;
  11916. end; { case }
  11917. { change "test $-1,%reg" into "test %reg,%reg" }
  11918. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11919. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11920. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11921. if MatchInstruction(p, A_OR, []) and
  11922. { Can only match if they're both registers }
  11923. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11924. begin
  11925. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11926. taicpu(p).opcode := A_TEST;
  11927. { No need to set Result to True, as we've done all the optimisations we can }
  11928. end;
  11929. end;
  11930. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11931. var
  11932. hp1,hp3 : tai;
  11933. {$ifndef x86_64}
  11934. hp2 : taicpu;
  11935. {$endif x86_64}
  11936. begin
  11937. Result:=false;
  11938. hp3:=nil;
  11939. {$ifndef x86_64}
  11940. { don't do this on modern CPUs, this really hurts them due to
  11941. broken call/ret pairing }
  11942. if (current_settings.optimizecputype < cpu_Pentium2) and
  11943. not(cs_create_pic in current_settings.moduleswitches) and
  11944. GetNextInstruction(p, hp1) and
  11945. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11946. MatchOpType(taicpu(hp1),top_ref) and
  11947. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11948. begin
  11949. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11950. InsertLLItem(p.previous, p, hp2);
  11951. taicpu(p).opcode := A_JMP;
  11952. taicpu(p).is_jmp := true;
  11953. RemoveInstruction(hp1);
  11954. Result:=true;
  11955. end
  11956. else
  11957. {$endif x86_64}
  11958. { replace
  11959. call procname
  11960. ret
  11961. by
  11962. jmp procname
  11963. but do it only on level 4 because it destroys stack back traces
  11964. else if the subroutine is marked as no return, remove the ret
  11965. }
  11966. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11967. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11968. GetNextInstruction(p, hp1) and
  11969. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11970. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11971. SetAndTest(hp1,hp3) and
  11972. GetNextInstruction(hp1,hp1) and
  11973. MatchInstruction(hp1,A_RET,[S_NO])
  11974. )
  11975. ) and
  11976. (taicpu(hp1).ops=0) then
  11977. begin
  11978. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11979. { we might destroy stack alignment here if we do not do a call }
  11980. (target_info.stackalign<=sizeof(SizeUInt)) then
  11981. begin
  11982. taicpu(p).opcode := A_JMP;
  11983. taicpu(p).is_jmp := true;
  11984. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11985. end
  11986. else
  11987. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11988. RemoveInstruction(hp1);
  11989. if Assigned(hp3) then
  11990. begin
  11991. AsmL.Remove(hp3);
  11992. AsmL.InsertBefore(hp3,p)
  11993. end;
  11994. Result:=true;
  11995. end;
  11996. end;
  11997. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11998. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11999. begin
  12000. case OpSize of
  12001. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12002. Result := (Val <= $FF) and (Val >= -128);
  12003. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12004. Result := (Val <= $FFFF) and (Val >= -32768);
  12005. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12006. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12007. else
  12008. Result := True;
  12009. end;
  12010. end;
  12011. var
  12012. hp1, hp2 : tai;
  12013. SizeChange: Boolean;
  12014. PreMessage: string;
  12015. begin
  12016. Result := False;
  12017. if (taicpu(p).oper[0]^.typ = top_reg) and
  12018. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12019. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12020. begin
  12021. { Change (using movzbl %al,%eax as an example):
  12022. movzbl %al, %eax movzbl %al, %eax
  12023. cmpl x, %eax testl %eax,%eax
  12024. To:
  12025. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12026. movzbl %al, %eax movzbl %al, %eax
  12027. Smaller instruction and minimises pipeline stall as the CPU
  12028. doesn't have to wait for the register to get zero-extended. [Kit]
  12029. Also allow if the smaller of the two registers is being checked,
  12030. as this still removes the false dependency.
  12031. }
  12032. if
  12033. (
  12034. (
  12035. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12036. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12037. ) or (
  12038. { If MatchOperand returns True, they must both be registers }
  12039. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12040. )
  12041. ) and
  12042. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12043. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12044. begin
  12045. 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);
  12046. asml.Remove(hp1);
  12047. asml.InsertBefore(hp1, p);
  12048. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12049. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12050. begin
  12051. taicpu(hp1).opcode := A_TEST;
  12052. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12053. end;
  12054. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12055. case taicpu(p).opsize of
  12056. S_BW, S_BL:
  12057. begin
  12058. SizeChange := taicpu(hp1).opsize <> S_B;
  12059. taicpu(hp1).changeopsize(S_B);
  12060. end;
  12061. S_WL:
  12062. begin
  12063. SizeChange := taicpu(hp1).opsize <> S_W;
  12064. taicpu(hp1).changeopsize(S_W);
  12065. end
  12066. else
  12067. InternalError(2020112701);
  12068. end;
  12069. UpdateUsedRegs(tai(p.Next));
  12070. { Check if the register is used aferwards - if not, we can
  12071. remove the movzx instruction completely }
  12072. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12073. begin
  12074. { Hp1 is a better position than p for debugging purposes }
  12075. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12076. RemoveCurrentp(p, hp1);
  12077. Result := True;
  12078. end;
  12079. if SizeChange then
  12080. DebugMsg(SPeepholeOptimization + PreMessage +
  12081. 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)
  12082. else
  12083. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12084. Exit;
  12085. end;
  12086. { Change (using movzwl %ax,%eax as an example):
  12087. movzwl %ax, %eax
  12088. movb %al, (dest) (Register is smaller than read register in movz)
  12089. To:
  12090. movb %al, (dest) (Move one back to avoid a false dependency)
  12091. movzwl %ax, %eax
  12092. }
  12093. if (taicpu(hp1).opcode = A_MOV) and
  12094. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12095. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12096. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12097. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12098. begin
  12099. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12100. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12101. asml.Remove(hp1);
  12102. asml.InsertBefore(hp1, p);
  12103. if taicpu(hp1).oper[1]^.typ = top_reg then
  12104. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12105. { Check if the register is used aferwards - if not, we can
  12106. remove the movzx instruction completely }
  12107. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12108. begin
  12109. { Hp1 is a better position than p for debugging purposes }
  12110. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12111. RemoveCurrentp(p, hp1);
  12112. Result := True;
  12113. end;
  12114. Exit;
  12115. end;
  12116. end;
  12117. end;
  12118. {$ifdef x86_64}
  12119. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12120. var
  12121. PreMessage, RegName: string;
  12122. begin
  12123. { Code size reduction by J. Gareth "Kit" Moreton }
  12124. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12125. as this removes the REX prefix }
  12126. Result := False;
  12127. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12128. Exit;
  12129. if taicpu(p).oper[0]^.typ <> top_reg then
  12130. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12131. InternalError(2018011500);
  12132. case taicpu(p).opsize of
  12133. S_Q:
  12134. begin
  12135. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12136. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12137. { The actual optimization }
  12138. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12139. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12140. taicpu(p).changeopsize(S_L);
  12141. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12142. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12143. end;
  12144. else
  12145. ;
  12146. end;
  12147. end;
  12148. {$endif}
  12149. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12150. var
  12151. XReg: TRegister;
  12152. begin
  12153. Result := False;
  12154. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12155. Smaller encoding and slightly faster on some platforms (also works for
  12156. ZMM-sized registers) }
  12157. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12158. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12159. begin
  12160. XReg := taicpu(p).oper[0]^.reg;
  12161. if (taicpu(p).oper[1]^.reg = XReg) then
  12162. begin
  12163. taicpu(p).changeopsize(S_XMM);
  12164. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12165. if (cs_opt_size in current_settings.optimizerswitches) then
  12166. begin
  12167. { Change input registers to %xmm0 to reduce size. Note that
  12168. there's a risk of a false dependency doing this, so only
  12169. optimise for size here }
  12170. XReg := NR_XMM0;
  12171. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12172. end
  12173. else
  12174. begin
  12175. setsubreg(XReg, R_SUBMMX);
  12176. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12177. end;
  12178. taicpu(p).oper[0]^.reg := XReg;
  12179. taicpu(p).oper[1]^.reg := XReg;
  12180. Result := True;
  12181. end;
  12182. end;
  12183. end;
  12184. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12185. var
  12186. OperIdx: Integer;
  12187. begin
  12188. for OperIdx := 0 to p.ops - 1 do
  12189. if p.oper[OperIdx]^.typ = top_ref then
  12190. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12191. end;
  12192. end.