2
0

aoptx86.pas 752 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562
  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. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  181. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  182. function TrySwapMovOp(var p, hp1: tai): Boolean;
  183. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  184. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  185. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  186. { Processor-dependent reference optimisation }
  187. class procedure OptimizeRefs(var p: taicpu); static;
  188. end;
  189. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  190. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  193. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  194. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  195. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  196. {$if max_operands>2}
  197. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  198. {$endif max_operands>2}
  199. function RefsEqual(const r1, r2: treference): boolean;
  200. { Like RefsEqual, but doesn't compare the offsets }
  201. function RefsAlmostEqual(const r1, r2: treference): boolean;
  202. { Note that Result is set to True if the references COULD overlap but the
  203. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  204. might still overlap because %reg2 could be equal to %reg1-4 }
  205. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  206. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  207. { returns true, if ref is a reference using only the registers passed as base and index
  208. and having an offset }
  209. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  210. implementation
  211. uses
  212. cutils,verbose,
  213. systems,
  214. globals,
  215. cpuinfo,
  216. procinfo,
  217. paramgr,
  218. aasmbase,
  219. aoptbase,aoptutils,
  220. symconst,symsym,
  221. cgx86,
  222. itcpugas;
  223. {$ifndef 8086}
  224. const
  225. MAX_CMOV_INSTRUCTIONS = 4;
  226. MAX_CMOV_REGISTERS = 8;
  227. type
  228. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  229. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  230. tsProcessed);
  231. { For OptPass2Jcc }
  232. TCMOVTracking = object
  233. private
  234. CMOVScore, ConstCount: LongInt;
  235. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  236. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  237. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  238. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  239. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  240. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  241. fOptimizer: TX86AsmOptimizer;
  242. fLabel: TAsmSymbol;
  243. fInsertionPoint,
  244. fCondition,
  245. fInitialJump,
  246. fFirstMovBlock,
  247. fFirstMovBlockStop,
  248. fSecondJump,
  249. fThirdJump,
  250. fSecondMovBlock,
  251. fSecondMovBlockStop,
  252. fMidLabel,
  253. fEndLabel,
  254. fAllocationRange: tai;
  255. fState: TCMovTrackingState;
  256. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  257. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  258. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  259. public
  260. RegisterTracking: TAllUsedRegs;
  261. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  262. destructor Done;
  263. procedure Process(out new_p: tai);
  264. property State: TCMovTrackingState read fState;
  265. end;
  266. PCMOVTracking = ^TCMOVTracking;
  267. {$endif 8086}
  268. {$ifdef DEBUG_AOPTCPU}
  269. const
  270. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  271. {$else DEBUG_AOPTCPU}
  272. { Empty strings help the optimizer to remove string concatenations that won't
  273. ever appear to the user on release builds. [Kit] }
  274. const
  275. SPeepholeOptimization = '';
  276. {$endif DEBUG_AOPTCPU}
  277. LIST_STEP_SIZE = 4;
  278. type
  279. TJumpTrackingItem = class(TLinkedListItem)
  280. private
  281. FSymbol: TAsmSymbol;
  282. FRefs: LongInt;
  283. public
  284. constructor Create(ASymbol: TAsmSymbol);
  285. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. property Symbol: TAsmSymbol read FSymbol;
  287. property Refs: LongInt read FRefs;
  288. end;
  289. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  290. begin
  291. inherited Create;
  292. FSymbol := ASymbol;
  293. FRefs := 0;
  294. end;
  295. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  296. begin
  297. Inc(FRefs);
  298. end;
  299. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  300. begin
  301. result :=
  302. (instr.typ = ait_instruction) and
  303. (taicpu(instr).opcode = op) and
  304. ((opsize = []) or (taicpu(instr).opsize in opsize));
  305. end;
  306. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  307. begin
  308. result :=
  309. (instr.typ = ait_instruction) and
  310. ((taicpu(instr).opcode = op1) or
  311. (taicpu(instr).opcode = op2)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  316. begin
  317. result :=
  318. (instr.typ = ait_instruction) and
  319. ((taicpu(instr).opcode = op1) or
  320. (taicpu(instr).opcode = op2) or
  321. (taicpu(instr).opcode = op3)
  322. ) and
  323. ((opsize = []) or (taicpu(instr).opsize in opsize));
  324. end;
  325. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  326. const opsize : topsizes) : boolean;
  327. var
  328. op : TAsmOp;
  329. begin
  330. result:=false;
  331. if (instr.typ <> ait_instruction) or
  332. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  333. exit;
  334. for op in ops do
  335. begin
  336. if taicpu(instr).opcode = op then
  337. begin
  338. result:=true;
  339. exit;
  340. end;
  341. end;
  342. end;
  343. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  344. begin
  345. result := (oper.typ = top_reg) and (oper.reg = reg);
  346. end;
  347. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  348. begin
  349. result := (oper.typ = top_const) and (oper.val = a);
  350. end;
  351. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  352. begin
  353. result := oper1.typ = oper2.typ;
  354. if result then
  355. case oper1.typ of
  356. top_const:
  357. Result:=oper1.val = oper2.val;
  358. top_reg:
  359. Result:=oper1.reg = oper2.reg;
  360. top_ref:
  361. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  362. else
  363. internalerror(2013102801);
  364. end
  365. end;
  366. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  367. begin
  368. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  369. if result then
  370. case oper1.typ of
  371. top_const:
  372. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  373. top_reg:
  374. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  375. top_ref:
  376. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  377. else
  378. internalerror(2020052401);
  379. end
  380. end;
  381. function RefsEqual(const r1, r2: treference): boolean;
  382. begin
  383. RefsEqual :=
  384. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  385. (r1.relsymbol = r2.relsymbol) and
  386. (r1.segment = r2.segment) and (r1.base = r2.base) and
  387. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  388. (r1.offset = r2.offset) and
  389. (r1.volatility + r2.volatility = []);
  390. end;
  391. function RefsAlmostEqual(const r1, r2: treference): boolean;
  392. begin
  393. RefsAlmostEqual :=
  394. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  395. (r1.relsymbol = r2.relsymbol) and
  396. (r1.segment = r2.segment) and (r1.base = r2.base) and
  397. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  398. { Don't compare the offsets }
  399. (r1.volatility + r2.volatility = []);
  400. end;
  401. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  402. begin
  403. if (r1.symbol<>r2.symbol) then
  404. { If the index registers are different, there's a chance one could
  405. be set so it equals the other symbol }
  406. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  407. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. (r1.volatility + r2.volatility = []) then
  412. { In this case, it all depends on the offsets }
  413. Exit(abs(r1.offset - r2.offset) < Range);
  414. { There's a chance things MIGHT overlap, so take no chances }
  415. Result := True;
  416. end;
  417. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  418. begin
  419. Result:=(ref.offset=0) and
  420. (ref.scalefactor in [0,1]) and
  421. (ref.segment=NR_NO) and
  422. (ref.symbol=nil) and
  423. (ref.relsymbol=nil) and
  424. ((base=NR_INVALID) or
  425. (ref.base=base)) and
  426. ((index=NR_INVALID) or
  427. (ref.index=index)) and
  428. (ref.volatility=[]);
  429. end;
  430. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.scalefactor in [0,1]) and
  433. (ref.segment=NR_NO) and
  434. (ref.symbol=nil) and
  435. (ref.relsymbol=nil) and
  436. ((base=NR_INVALID) or
  437. (ref.base=base)) and
  438. ((index=NR_INVALID) or
  439. (ref.index=index)) and
  440. (ref.volatility=[]);
  441. end;
  442. function InstrReadsFlags(p: tai): boolean;
  443. begin
  444. InstrReadsFlags := true;
  445. case p.typ of
  446. ait_instruction:
  447. if InsProp[taicpu(p).opcode].Ch*
  448. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  449. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  450. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  451. exit;
  452. ait_label:
  453. exit;
  454. else
  455. ;
  456. end;
  457. InstrReadsFlags := false;
  458. end;
  459. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  460. begin
  461. Next:=Current;
  462. repeat
  463. Result:=GetNextInstruction(Next,Next);
  464. until not (Result) or
  465. not(cs_opt_level3 in current_settings.optimizerswitches) or
  466. (Next.typ<>ait_instruction) or
  467. RegInInstruction(reg,Next) or
  468. is_calljmp(taicpu(Next).opcode);
  469. end;
  470. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  471. var
  472. GetNextResult: Boolean;
  473. begin
  474. Result:=0;
  475. Next:=Current;
  476. repeat
  477. GetNextResult := GetNextInstruction(Next,Next);
  478. if GetNextResult then
  479. Inc(Result)
  480. else
  481. { Must return zero upon hitting the end of the linked list without a match }
  482. Result := 0;
  483. until not (GetNextResult) or
  484. not(cs_opt_level3 in current_settings.optimizerswitches) or
  485. (Next.typ<>ait_instruction) or
  486. RegInInstruction(reg,Next) or
  487. is_calljmp(taicpu(Next).opcode);
  488. end;
  489. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  490. procedure TrackJump(Symbol: TAsmSymbol);
  491. var
  492. Search: TJumpTrackingItem;
  493. begin
  494. { See if an entry already exists in our jump tracking list
  495. (faster to search backwards due to the higher chance of
  496. matching destinations) }
  497. Search := TJumpTrackingItem(JumpTracking.Last);
  498. while Assigned(Search) do
  499. begin
  500. if Search.Symbol = Symbol then
  501. begin
  502. { Found it - remove it so it can be pushed to the front }
  503. JumpTracking.Remove(Search);
  504. Break;
  505. end;
  506. Search := TJumpTrackingItem(Search.Previous);
  507. end;
  508. if not Assigned(Search) then
  509. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  510. JumpTracking.Concat(Search);
  511. Search.IncRefs;
  512. end;
  513. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  514. var
  515. Search: TJumpTrackingItem;
  516. begin
  517. Result := False;
  518. { See if this label appears in the tracking list }
  519. Search := TJumpTrackingItem(JumpTracking.Last);
  520. while Assigned(Search) do
  521. begin
  522. if Search.Symbol = Symbol then
  523. begin
  524. { Found it - let's see what we can discover }
  525. if Search.Symbol.getrefs = Search.Refs then
  526. begin
  527. { Success - all the references are accounted for }
  528. JumpTracking.Remove(Search);
  529. Search.Free;
  530. { It is logically impossible for CrossJump to be false here
  531. because we must have run into a conditional jump for
  532. this label at some point }
  533. if not CrossJump then
  534. InternalError(2022041710);
  535. if JumpTracking.First = nil then
  536. { Tracking list is now empty - no more cross jumps }
  537. CrossJump := False;
  538. Result := True;
  539. Exit;
  540. end;
  541. { If the references don't match, it's possible to enter
  542. this label through other means, so drop out }
  543. Exit;
  544. end;
  545. Search := TJumpTrackingItem(Search.Previous);
  546. end;
  547. end;
  548. var
  549. Next_Label: tai;
  550. begin
  551. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  552. Next := Current;
  553. repeat
  554. Result := GetNextInstruction(Next,Next);
  555. if not Result then
  556. Break;
  557. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  558. if is_calljmpuncondret(taicpu(Next).opcode) then
  559. begin
  560. if (taicpu(Next).opcode = A_JMP) and
  561. { Remove dead code now to save time }
  562. RemoveDeadCodeAfterJump(taicpu(Next)) then
  563. { A jump was removed, but not the current instruction, and
  564. Result doesn't necessarily translate into an optimisation
  565. routine's Result, so use the "Force New Iteration" flag so
  566. mark a new pass }
  567. Include(OptsToCheck, aoc_ForceNewIteration);
  568. if not Assigned(JumpTracking) then
  569. begin
  570. { Cross-label optimisations often causes other optimisations
  571. to perform worse because they're not given the chance to
  572. optimise locally. In this case, don't do the cross-label
  573. optimisations yet, but flag them as a potential possibility
  574. for the next iteration of Pass 1 }
  575. if not NotFirstIteration then
  576. Include(OptsToCheck, aoc_ForceNewIteration);
  577. end
  578. else if IsJumpToLabel(taicpu(Next)) and
  579. GetNextInstruction(Next, Next_Label) then
  580. begin
  581. { If we have JMP .lbl, and the label after it has all of its
  582. references tracked, then this is probably an if-else style of
  583. block and we can keep tracking. If the label for this jump
  584. then appears later and is fully tracked, then it's the end
  585. of the if-else blocks and the code paths converge (thus
  586. marking the end of the cross-jump) }
  587. if (Next_Label.typ = ait_label) then
  588. begin
  589. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  590. begin
  591. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  592. Next := Next_Label;
  593. { CrossJump gets set to false by LabelAccountedFor if the
  594. list is completely emptied (as it indicates that all
  595. code paths have converged). We could avoid this nuance
  596. by moving the TrackJump call to before the
  597. LabelAccountedFor call, but this is slower in situations
  598. where LabelAccountedFor would return False due to the
  599. creation of a new object that is not used and destroyed
  600. soon after. }
  601. CrossJump := True;
  602. Continue;
  603. end;
  604. end
  605. else if (Next_Label.typ <> ait_marker) then
  606. { We just did a RemoveDeadCodeAfterJump, so either we find
  607. a label, the end of the procedure or some kind of marker}
  608. InternalError(2022041720);
  609. end;
  610. Result := False;
  611. Exit;
  612. end
  613. else
  614. begin
  615. if not Assigned(JumpTracking) then
  616. begin
  617. { Cross-label optimisations often causes other optimisations
  618. to perform worse because they're not given the chance to
  619. optimise locally. In this case, don't do the cross-label
  620. optimisations yet, but flag them as a potential possibility
  621. for the next iteration of Pass 1 }
  622. if not NotFirstIteration then
  623. Include(OptsToCheck, aoc_ForceNewIteration);
  624. end
  625. else if IsJumpToLabel(taicpu(Next)) then
  626. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  627. else
  628. { Conditional jumps should always be a jump to label }
  629. InternalError(2022041701);
  630. CrossJump := True;
  631. Continue;
  632. end;
  633. if Next.typ = ait_label then
  634. begin
  635. if not Assigned(JumpTracking) then
  636. begin
  637. { Cross-label optimisations often causes other optimisations
  638. to perform worse because they're not given the chance to
  639. optimise locally. In this case, don't do the cross-label
  640. optimisations yet, but flag them as a potential possibility
  641. for the next iteration of Pass 1 }
  642. if not NotFirstIteration then
  643. Include(OptsToCheck, aoc_ForceNewIteration);
  644. end
  645. else if LabelAccountedFor(tai_label(Next).labsym) then
  646. Continue;
  647. { If we reach here, we're at a label that hasn't been seen before
  648. (or JumpTracking was nil) }
  649. Break;
  650. end;
  651. until not Result or
  652. not (cs_opt_level3 in current_settings.optimizerswitches) or
  653. not (Next.typ in [ait_label, ait_instruction]) or
  654. RegInInstruction(reg,Next);
  655. end;
  656. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  657. begin
  658. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  659. begin
  660. Result:=GetNextInstruction(Current,Next);
  661. exit;
  662. end;
  663. Next:=tai(Current.Next);
  664. Result:=false;
  665. while assigned(Next) do
  666. begin
  667. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  668. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  669. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  670. exit
  671. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  672. begin
  673. Result:=true;
  674. exit;
  675. end;
  676. Next:=tai(Next.Next);
  677. end;
  678. end;
  679. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  680. begin
  681. Result:=RegReadByInstruction(reg,hp);
  682. end;
  683. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  684. var
  685. p: taicpu;
  686. opcount: longint;
  687. begin
  688. RegReadByInstruction := false;
  689. if hp.typ <> ait_instruction then
  690. exit;
  691. p := taicpu(hp);
  692. case p.opcode of
  693. A_CALL:
  694. regreadbyinstruction := true;
  695. A_IMUL:
  696. case p.ops of
  697. 1:
  698. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  699. (
  700. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  701. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  702. );
  703. 2,3:
  704. regReadByInstruction :=
  705. reginop(reg,p.oper[0]^) or
  706. reginop(reg,p.oper[1]^);
  707. else
  708. InternalError(2019112801);
  709. end;
  710. A_MUL:
  711. begin
  712. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  713. (
  714. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  715. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  716. );
  717. end;
  718. A_IDIV,A_DIV:
  719. begin
  720. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  721. (
  722. (getregtype(reg)=R_INTREGISTER) and
  723. (
  724. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  725. )
  726. );
  727. end;
  728. else
  729. begin
  730. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  731. begin
  732. RegReadByInstruction := false;
  733. exit;
  734. end;
  735. for opcount := 0 to p.ops-1 do
  736. if (p.oper[opCount]^.typ = top_ref) and
  737. RegInRef(reg,p.oper[opcount]^.ref^) then
  738. begin
  739. RegReadByInstruction := true;
  740. exit
  741. end;
  742. { special handling for SSE MOVSD }
  743. if (p.opcode=A_MOVSD) and (p.ops>0) then
  744. begin
  745. if p.ops<>2 then
  746. internalerror(2017042702);
  747. regReadByInstruction := reginop(reg,p.oper[0]^) or
  748. (
  749. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  750. );
  751. exit;
  752. end;
  753. with insprop[p.opcode] do
  754. begin
  755. case getregtype(reg) of
  756. R_INTREGISTER:
  757. begin
  758. case getsupreg(reg) of
  759. RS_EAX:
  760. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ECX:
  766. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EDX:
  772. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_EBX:
  778. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_ESP:
  784. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. RS_EBP:
  790. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  791. begin
  792. RegReadByInstruction := true;
  793. exit
  794. end;
  795. RS_ESI:
  796. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  797. begin
  798. RegReadByInstruction := true;
  799. exit
  800. end;
  801. RS_EDI:
  802. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. end;
  808. end;
  809. R_MMREGISTER:
  810. begin
  811. case getsupreg(reg) of
  812. RS_XMM0:
  813. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  814. begin
  815. RegReadByInstruction := true;
  816. exit
  817. end;
  818. end;
  819. end;
  820. else
  821. ;
  822. end;
  823. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  824. begin
  825. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  826. begin
  827. case p.condition of
  828. C_A,C_NBE, { CF=0 and ZF=0 }
  829. C_BE,C_NA: { CF=1 or ZF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  831. C_AE,C_NB,C_NC, { CF=0 }
  832. C_B,C_NAE,C_C: { CF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  834. C_NE,C_NZ, { ZF=0 }
  835. C_E,C_Z: { ZF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  837. C_G,C_NLE, { ZF=0 and SF=OF }
  838. C_LE,C_NG: { ZF=1 or SF<>OF }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  840. C_GE,C_NL, { SF=OF }
  841. C_L,C_NGE: { SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_NO, { OF=0 }
  844. C_O: { OF=1 }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  846. C_NP,C_PO, { PF=0 }
  847. C_P,C_PE: { PF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  849. C_NS, { SF=0 }
  850. C_S: { SF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  852. else
  853. internalerror(2017042701);
  854. end;
  855. if RegReadByInstruction then
  856. exit;
  857. end;
  858. case getsubreg(reg) of
  859. R_SUBW,R_SUBD,R_SUBQ:
  860. RegReadByInstruction :=
  861. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  862. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  863. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  864. R_SUBFLAGCARRY:
  865. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  866. R_SUBFLAGPARITY:
  867. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGAUXILIARY:
  869. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGZERO:
  871. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGSIGN:
  873. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGOVERFLOW:
  875. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGINTERRUPT:
  877. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGDIRECTION:
  879. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. else
  881. internalerror(2017042601);
  882. end;
  883. exit;
  884. end;
  885. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  886. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  887. (p.oper[0]^.reg=p.oper[1]^.reg) then
  888. exit;
  889. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  890. begin
  891. RegReadByInstruction := true;
  892. exit
  893. end;
  894. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  895. begin
  896. RegReadByInstruction := true;
  897. exit
  898. end;
  899. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  900. begin
  901. RegReadByInstruction := true;
  902. exit
  903. end;
  904. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  905. begin
  906. RegReadByInstruction := true;
  907. exit
  908. end;
  909. end;
  910. end;
  911. end;
  912. end;
  913. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  914. begin
  915. result:=false;
  916. if p1.typ<>ait_instruction then
  917. exit;
  918. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  919. exit(true);
  920. if (getregtype(reg)=R_INTREGISTER) and
  921. { change information for xmm movsd are not correct }
  922. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  923. begin
  924. { Handle instructions that behave differently depending on the size and operand count }
  925. case taicpu(p1).opcode of
  926. A_MUL, A_DIV, A_IDIV:
  927. if taicpu(p1).opsize = S_B then
  928. Result := (getsupreg(Reg) = RS_EAX)
  929. else
  930. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  931. A_IMUL:
  932. if taicpu(p1).ops = 1 then
  933. begin
  934. if taicpu(p1).opsize = S_B then
  935. Result := (getsupreg(Reg) = RS_EAX)
  936. else
  937. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  938. end;
  939. { If ops are greater than 1, call inherited method }
  940. else
  941. case getsupreg(reg) of
  942. { RS_EAX = RS_RAX on x86-64 }
  943. RS_EAX:
  944. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. RS_ECX:
  946. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_EDX:
  948. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EBX:
  950. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_ESP:
  952. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_EBP:
  954. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_ESI:
  956. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_EDI:
  958. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. else
  960. ;
  961. end;
  962. end;
  963. if result then
  964. exit;
  965. end
  966. else if getregtype(reg)=R_MMREGISTER then
  967. begin
  968. case getsupreg(reg) of
  969. RS_XMM0:
  970. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  971. else
  972. ;
  973. end;
  974. if result then
  975. exit;
  976. end
  977. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  978. begin
  979. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  980. exit(true);
  981. case getsubreg(reg) of
  982. R_SUBFLAGCARRY:
  983. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. R_SUBFLAGPARITY:
  985. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGAUXILIARY:
  987. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGZERO:
  989. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGSIGN:
  991. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGOVERFLOW:
  993. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGINTERRUPT:
  995. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGDIRECTION:
  997. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBW,R_SUBD,R_SUBQ:
  999. { Everything except the direction bits }
  1000. Result:=
  1001. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1002. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1003. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1004. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1005. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1006. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1007. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1008. else
  1009. ;
  1010. end;
  1011. if result then
  1012. exit;
  1013. end
  1014. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1015. exit(true);
  1016. Result:=inherited RegInInstruction(Reg, p1);
  1017. end;
  1018. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1019. const
  1020. WriteOps: array[0..3] of set of TInsChange =
  1021. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1022. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1023. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1024. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1025. var
  1026. OperIdx: Integer;
  1027. begin
  1028. Result := False;
  1029. if p1.typ <> ait_instruction then
  1030. exit;
  1031. with insprop[taicpu(p1).opcode] do
  1032. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1033. begin
  1034. case getsubreg(reg) of
  1035. R_SUBW,R_SUBD,R_SUBQ:
  1036. Result :=
  1037. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1038. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1039. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1040. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1041. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1042. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. R_SUBFLAGCARRY:
  1044. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGPARITY:
  1046. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGAUXILIARY:
  1048. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGZERO:
  1050. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGSIGN:
  1052. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGOVERFLOW:
  1054. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGINTERRUPT:
  1056. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGDIRECTION:
  1058. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. else
  1060. internalerror(2017042602);
  1061. end;
  1062. exit;
  1063. end;
  1064. case taicpu(p1).opcode of
  1065. A_CALL:
  1066. { We could potentially set Result to False if the register in
  1067. question is non-volatile for the subroutine's calling convention,
  1068. but this would require detecting the calling convention in use and
  1069. also assuming that the routine doesn't contain malformed assembly
  1070. language, for example... so it could only be done under -O4 as it
  1071. would be considered a side-effect. [Kit] }
  1072. Result := True;
  1073. A_MOVSD:
  1074. { special handling for SSE MOVSD }
  1075. if (taicpu(p1).ops>0) then
  1076. begin
  1077. if taicpu(p1).ops<>2 then
  1078. internalerror(2017042703);
  1079. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1080. end;
  1081. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1082. so fix it here (FK)
  1083. }
  1084. A_VMOVSS,
  1085. A_VMOVSD:
  1086. begin
  1087. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1088. exit;
  1089. end;
  1090. A_MUL, A_DIV, A_IDIV:
  1091. begin
  1092. if taicpu(p1).opsize = S_B then
  1093. Result := (getsupreg(Reg) = RS_EAX)
  1094. else
  1095. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1096. end;
  1097. A_IMUL:
  1098. begin
  1099. if taicpu(p1).ops = 1 then
  1100. begin
  1101. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1102. end
  1103. else
  1104. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1105. Exit;
  1106. end;
  1107. else
  1108. ;
  1109. end;
  1110. if Result then
  1111. exit;
  1112. with insprop[taicpu(p1).opcode] do
  1113. begin
  1114. if getregtype(reg)=R_INTREGISTER then
  1115. begin
  1116. case getsupreg(reg) of
  1117. RS_EAX:
  1118. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ECX:
  1124. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EDX:
  1130. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_EBX:
  1136. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_ESP:
  1142. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. RS_EBP:
  1148. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1149. begin
  1150. Result := True;
  1151. exit
  1152. end;
  1153. RS_ESI:
  1154. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1155. begin
  1156. Result := True;
  1157. exit
  1158. end;
  1159. RS_EDI:
  1160. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1161. begin
  1162. Result := True;
  1163. exit
  1164. end;
  1165. end;
  1166. end;
  1167. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1168. if (WriteOps[OperIdx]*Ch<>[]) and
  1169. { The register doesn't get modified inside a reference }
  1170. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1171. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1172. begin
  1173. Result := true;
  1174. exit
  1175. end;
  1176. end;
  1177. end;
  1178. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1179. const
  1180. WriteOps: array[0..3] of set of TInsChange =
  1181. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1182. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1183. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1184. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1185. var
  1186. X: Integer;
  1187. CurrentP1Size: asizeint;
  1188. begin
  1189. Result := (
  1190. (Ref.base <> NR_NO) and
  1191. {$ifdef x86_64}
  1192. (Ref.base <> NR_RIP) and
  1193. {$endif x86_64}
  1194. RegModifiedBetween(Ref.base, p1, p2)
  1195. ) or
  1196. (
  1197. (Ref.index <> NR_NO) and
  1198. (Ref.index <> Ref.base) and
  1199. RegModifiedBetween(Ref.index, p1, p2)
  1200. );
  1201. { Now check to see if the memory itself is written to }
  1202. if not Result then
  1203. begin
  1204. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1205. if p1.typ = ait_instruction then
  1206. begin
  1207. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1208. with insprop[taicpu(p1).opcode] do
  1209. for X := 0 to taicpu(p1).ops - 1 do
  1210. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1211. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1212. { Catch any potential overlaps }
  1213. (
  1214. (RefSize = 0) or
  1215. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1216. ) and
  1217. (
  1218. (CurrentP1Size = 0) or
  1219. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1220. ) and
  1221. { Reference is used, but does the instruction write to it? }
  1222. (
  1223. (Ch_All in Ch) or
  1224. ((WriteOps[X] * Ch) <> [])
  1225. ) then
  1226. begin
  1227. Result := True;
  1228. Break;
  1229. end;
  1230. end;
  1231. end;
  1232. end;
  1233. {$ifdef DEBUG_AOPTCPU}
  1234. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1235. begin
  1236. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1237. end;
  1238. function debug_tostr(i: tcgint): string; inline;
  1239. begin
  1240. Result := tostr(i);
  1241. end;
  1242. function debug_hexstr(i: tcgint): string;
  1243. begin
  1244. Result := '0x';
  1245. case i of
  1246. 0..$FF:
  1247. Result := Result + hexstr(i, 2);
  1248. $100..$FFFF:
  1249. Result := Result + hexstr(i, 4);
  1250. $10000..$FFFFFF:
  1251. Result := Result + hexstr(i, 6);
  1252. $1000000..$FFFFFFFF:
  1253. Result := Result + hexstr(i, 8);
  1254. else
  1255. Result := Result + hexstr(i, 16);
  1256. end;
  1257. end;
  1258. function debug_regname(r: TRegister): string; inline;
  1259. begin
  1260. Result := '%' + std_regname(r);
  1261. end;
  1262. { Debug output function - creates a string representation of an operator }
  1263. function debug_operstr(oper: TOper): string;
  1264. begin
  1265. case oper.typ of
  1266. top_const:
  1267. Result := '$' + debug_tostr(oper.val);
  1268. top_reg:
  1269. Result := debug_regname(oper.reg);
  1270. top_ref:
  1271. begin
  1272. if oper.ref^.offset <> 0 then
  1273. Result := debug_tostr(oper.ref^.offset) + '('
  1274. else
  1275. Result := '(';
  1276. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1277. begin
  1278. Result := Result + debug_regname(oper.ref^.base);
  1279. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1280. Result := Result + ',' + debug_regname(oper.ref^.index);
  1281. end
  1282. else
  1283. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1284. Result := Result + debug_regname(oper.ref^.index);
  1285. if (oper.ref^.scalefactor > 1) then
  1286. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1287. else
  1288. Result := Result + ')';
  1289. end;
  1290. else
  1291. Result := '[UNKNOWN]';
  1292. end;
  1293. end;
  1294. function debug_op2str(opcode: tasmop): string; inline;
  1295. begin
  1296. Result := std_op2str[opcode];
  1297. end;
  1298. function debug_opsize2str(opsize: topsize): string; inline;
  1299. begin
  1300. Result := gas_opsize2str[opsize];
  1301. end;
  1302. {$else DEBUG_AOPTCPU}
  1303. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1304. begin
  1305. end;
  1306. function debug_tostr(i: tcgint): string; inline;
  1307. begin
  1308. Result := '';
  1309. end;
  1310. function debug_hexstr(i: tcgint): string; inline;
  1311. begin
  1312. Result := '';
  1313. end;
  1314. function debug_regname(r: TRegister): string; inline;
  1315. begin
  1316. Result := '';
  1317. end;
  1318. function debug_operstr(oper: TOper): string; inline;
  1319. begin
  1320. Result := '';
  1321. end;
  1322. function debug_op2str(opcode: tasmop): string; inline;
  1323. begin
  1324. Result := '';
  1325. end;
  1326. function debug_opsize2str(opsize: topsize): string; inline;
  1327. begin
  1328. Result := '';
  1329. end;
  1330. {$endif DEBUG_AOPTCPU}
  1331. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1332. begin
  1333. {$ifdef x86_64}
  1334. { Always fine on x86-64 }
  1335. Result := True;
  1336. {$else x86_64}
  1337. Result :=
  1338. {$ifdef i8086}
  1339. (current_settings.cputype >= cpu_386) and
  1340. {$endif i8086}
  1341. (
  1342. { Always accept if optimising for size }
  1343. (cs_opt_size in current_settings.optimizerswitches) or
  1344. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1345. (current_settings.optimizecputype >= cpu_Pentium2)
  1346. );
  1347. {$endif x86_64}
  1348. end;
  1349. { Attempts to allocate a volatile integer register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_int;
  1364. (*
  1365. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1366. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1367. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1368. *)
  1369. for CurrentSuperReg in RegSet do
  1370. begin
  1371. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1372. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1373. {$if defined(i386) or defined(i8086)}
  1374. { If the target size is 8-bit, make sure we can actually encode it }
  1375. and (
  1376. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1377. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1378. )
  1379. {$endif i386 or i8086}
  1380. then
  1381. begin
  1382. Currentp := p;
  1383. Breakout := False;
  1384. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1385. begin
  1386. case Currentp.typ of
  1387. ait_instruction:
  1388. begin
  1389. if RegInInstruction(CurrentReg, Currentp) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. { Cannot allocate across an unconditional jump }
  1395. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1396. Exit;
  1397. end;
  1398. ait_marker:
  1399. { Don't try anything more if a marker is hit }
  1400. Exit;
  1401. ait_regalloc:
  1402. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. else
  1408. ;
  1409. end;
  1410. end;
  1411. if Breakout then
  1412. { Try the next register }
  1413. Continue;
  1414. { We have a free register available }
  1415. Result := CurrentReg;
  1416. if not DontAlloc then
  1417. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1418. Exit;
  1419. end;
  1420. end;
  1421. end;
  1422. { Attempts to allocate a volatile MM register for use between p and hp,
  1423. using AUsedRegs for the current register usage information. Returns NR_NO
  1424. if no free register could be found }
  1425. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1426. var
  1427. RegSet: TCPURegisterSet;
  1428. CurrentSuperReg: Integer;
  1429. CurrentReg: TRegister;
  1430. Currentp: tai;
  1431. Breakout: Boolean;
  1432. begin
  1433. Result := NR_NO;
  1434. RegSet :=
  1435. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1436. current_procinfo.saved_regs_mm;
  1437. for CurrentSuperReg in RegSet do
  1438. begin
  1439. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1440. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1441. begin
  1442. Currentp := p;
  1443. Breakout := False;
  1444. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1445. begin
  1446. case Currentp.typ of
  1447. ait_instruction:
  1448. begin
  1449. if RegInInstruction(CurrentReg, Currentp) then
  1450. begin
  1451. Breakout := True;
  1452. Break;
  1453. end;
  1454. { Cannot allocate across an unconditional jump }
  1455. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1456. Exit;
  1457. end;
  1458. ait_marker:
  1459. { Don't try anything more if a marker is hit }
  1460. Exit;
  1461. ait_regalloc:
  1462. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. else
  1468. ;
  1469. end;
  1470. end;
  1471. if Breakout then
  1472. { Try the next register }
  1473. Continue;
  1474. { We have a free register available }
  1475. Result := CurrentReg;
  1476. if not DontAlloc then
  1477. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1478. Exit;
  1479. end;
  1480. end;
  1481. end;
  1482. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1483. begin
  1484. if not SuperRegistersEqual(reg1,reg2) then
  1485. exit(false);
  1486. if getregtype(reg1)<>R_INTREGISTER then
  1487. exit(true); {because SuperRegisterEqual is true}
  1488. case getsubreg(reg1) of
  1489. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1490. higher, it preserves the high bits, so the new value depends on
  1491. reg2's previous value. In other words, it is equivalent to doing:
  1492. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1493. R_SUBL:
  1494. exit(getsubreg(reg2)=R_SUBL);
  1495. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1496. higher, it actually does a:
  1497. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1498. R_SUBH:
  1499. exit(getsubreg(reg2)=R_SUBH);
  1500. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1501. bits of reg2:
  1502. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1503. R_SUBW:
  1504. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1505. { a write to R_SUBD always overwrites every other subregister,
  1506. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1507. R_SUBD,
  1508. R_SUBQ:
  1509. exit(true);
  1510. else
  1511. internalerror(2017042801);
  1512. end;
  1513. end;
  1514. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1515. begin
  1516. if not SuperRegistersEqual(reg1,reg2) then
  1517. exit(false);
  1518. if getregtype(reg1)<>R_INTREGISTER then
  1519. exit(true); {because SuperRegisterEqual is true}
  1520. case getsubreg(reg1) of
  1521. R_SUBL:
  1522. exit(getsubreg(reg2)<>R_SUBH);
  1523. R_SUBH:
  1524. exit(getsubreg(reg2)<>R_SUBL);
  1525. R_SUBW,
  1526. R_SUBD,
  1527. R_SUBQ:
  1528. exit(true);
  1529. else
  1530. internalerror(2017042802);
  1531. end;
  1532. end;
  1533. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1534. var
  1535. hp1 : tai;
  1536. l : TCGInt;
  1537. begin
  1538. result:=false;
  1539. if not(GetNextInstruction(p, hp1)) then
  1540. exit;
  1541. { changes the code sequence
  1542. shr/sar const1, x
  1543. shl const2, x
  1544. to
  1545. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1546. if (taicpu(p).oper[0]^.typ = top_const) and
  1547. MatchInstruction(hp1,A_SHL,[]) and
  1548. (taicpu(hp1).oper[0]^.typ = top_const) and
  1549. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1550. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1551. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1552. begin
  1553. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1554. not(cs_opt_size in current_settings.optimizerswitches) then
  1555. begin
  1556. { shr/sar const1, %reg
  1557. shl const2, %reg
  1558. with const1 > const2 }
  1559. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1560. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1561. taicpu(hp1).opcode := A_AND;
  1562. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1563. case taicpu(p).opsize Of
  1564. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1565. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1566. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1567. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1568. else
  1569. Internalerror(2017050703)
  1570. end;
  1571. end
  1572. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) then
  1574. begin
  1575. { shr/sar const1, %reg
  1576. shl const2, %reg
  1577. with const1 < const2 }
  1578. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1579. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1580. taicpu(p).opcode := A_AND;
  1581. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1582. case taicpu(p).opsize Of
  1583. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1584. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1585. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1586. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1587. else
  1588. Internalerror(2017050702)
  1589. end;
  1590. end
  1591. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 = const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1597. taicpu(p).opcode := A_AND;
  1598. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1599. case taicpu(p).opsize Of
  1600. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1601. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1602. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1603. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1604. else
  1605. Internalerror(2017050701)
  1606. end;
  1607. RemoveInstruction(hp1);
  1608. end;
  1609. end;
  1610. end;
  1611. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1612. var
  1613. opsize : topsize;
  1614. hp1, hp2 : tai;
  1615. tmpref : treference;
  1616. ShiftValue : Cardinal;
  1617. BaseValue : TCGInt;
  1618. begin
  1619. result:=false;
  1620. opsize:=taicpu(p).opsize;
  1621. { changes certain "imul const, %reg"'s to lea sequences }
  1622. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1623. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1624. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1625. if (taicpu(p).oper[0]^.val = 1) then
  1626. if (taicpu(p).ops = 2) then
  1627. { remove "imul $1, reg" }
  1628. begin
  1629. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1630. Result := RemoveCurrentP(p);
  1631. end
  1632. else
  1633. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1634. begin
  1635. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1636. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1637. asml.InsertAfter(hp1, p);
  1638. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1639. RemoveCurrentP(p, hp1);
  1640. Result := True;
  1641. end
  1642. else if ((taicpu(p).ops <= 2) or
  1643. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1644. not(cs_opt_size in current_settings.optimizerswitches) and
  1645. (not(GetNextInstruction(p, hp1)) or
  1646. not((tai(hp1).typ = ait_instruction) and
  1647. ((taicpu(hp1).opcode=A_Jcc) and
  1648. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1649. begin
  1650. {
  1651. imul X, reg1, reg2 to
  1652. lea (reg1,reg1,Y), reg2
  1653. shl ZZ,reg2
  1654. imul XX, reg1 to
  1655. lea (reg1,reg1,YY), reg1
  1656. shl ZZ,reg2
  1657. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1658. it does not exist as a separate optimization target in FPC though.
  1659. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1660. at most two zeros
  1661. }
  1662. reference_reset(tmpref,1,[]);
  1663. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1664. begin
  1665. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1666. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1667. TmpRef.base := taicpu(p).oper[1]^.reg;
  1668. TmpRef.index := taicpu(p).oper[1]^.reg;
  1669. if not(BaseValue in [3,5,9]) then
  1670. Internalerror(2018110101);
  1671. TmpRef.ScaleFactor := BaseValue-1;
  1672. if (taicpu(p).ops = 2) then
  1673. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1674. else
  1675. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1676. AsmL.InsertAfter(hp1,p);
  1677. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1678. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1679. RemoveCurrentP(p, hp1);
  1680. if ShiftValue>0 then
  1681. begin
  1682. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1683. AsmL.InsertAfter(hp2,hp1);
  1684. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1685. end;
  1686. Result := True;
  1687. end;
  1688. end;
  1689. end;
  1690. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1691. begin
  1692. Result := False;
  1693. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1694. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1695. begin
  1696. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1697. taicpu(p).opcode := A_MOV;
  1698. Result := True;
  1699. end;
  1700. end;
  1701. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1702. var
  1703. p: taicpu absolute hp; { Implicit typecast }
  1704. i: Integer;
  1705. begin
  1706. Result := False;
  1707. if not assigned(hp) or
  1708. (hp.typ <> ait_instruction) then
  1709. Exit;
  1710. Prefetch(insprop[p.opcode]);
  1711. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1712. with insprop[p.opcode] do
  1713. begin
  1714. case getsubreg(reg) of
  1715. R_SUBW,R_SUBD,R_SUBQ:
  1716. Result:=
  1717. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1718. uncommon flags are checked first }
  1719. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1720. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1721. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1725. R_SUBFLAGCARRY:
  1726. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1727. R_SUBFLAGPARITY:
  1728. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1729. R_SUBFLAGAUXILIARY:
  1730. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1731. R_SUBFLAGZERO:
  1732. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1733. R_SUBFLAGSIGN:
  1734. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1735. R_SUBFLAGOVERFLOW:
  1736. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1737. R_SUBFLAGINTERRUPT:
  1738. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1739. R_SUBFLAGDIRECTION:
  1740. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1741. else
  1742. internalerror(2017050501);
  1743. end;
  1744. exit;
  1745. end;
  1746. { Handle special cases first }
  1747. case p.opcode of
  1748. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1749. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1750. begin
  1751. Result :=
  1752. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1753. (p.oper[1]^.typ = top_reg) and
  1754. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1755. (
  1756. (p.oper[0]^.typ = top_const) or
  1757. (
  1758. (p.oper[0]^.typ = top_reg) and
  1759. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1760. ) or (
  1761. (p.oper[0]^.typ = top_ref) and
  1762. not RegInRef(reg,p.oper[0]^.ref^)
  1763. )
  1764. );
  1765. end;
  1766. A_MUL, A_IMUL:
  1767. Result :=
  1768. (
  1769. (p.ops=3) and { IMUL only }
  1770. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1771. (
  1772. (
  1773. (p.oper[1]^.typ=top_reg) and
  1774. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1775. ) or (
  1776. (p.oper[1]^.typ=top_ref) and
  1777. not RegInRef(reg,p.oper[1]^.ref^)
  1778. )
  1779. )
  1780. ) or (
  1781. (
  1782. (p.ops=1) and
  1783. (
  1784. (
  1785. (
  1786. (p.oper[0]^.typ=top_reg) and
  1787. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1788. )
  1789. ) or (
  1790. (p.oper[0]^.typ=top_ref) and
  1791. not RegInRef(reg,p.oper[0]^.ref^)
  1792. )
  1793. ) and (
  1794. (
  1795. (p.opsize=S_B) and
  1796. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1797. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1798. ) or (
  1799. (p.opsize=S_W) and
  1800. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1801. ) or (
  1802. (p.opsize=S_L) and
  1803. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1804. {$ifdef x86_64}
  1805. ) or (
  1806. (p.opsize=S_Q) and
  1807. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1808. {$endif x86_64}
  1809. )
  1810. )
  1811. )
  1812. );
  1813. A_CBW:
  1814. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1815. {$ifndef x86_64}
  1816. A_LDS:
  1817. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1818. A_LES:
  1819. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1820. {$endif not x86_64}
  1821. A_LFS:
  1822. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1823. A_LGS:
  1824. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1825. A_LSS:
  1826. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1827. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1828. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1829. A_LODSB:
  1830. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1831. A_LODSW:
  1832. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1833. {$ifdef x86_64}
  1834. A_LODSQ:
  1835. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1836. {$endif x86_64}
  1837. A_LODSD:
  1838. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1839. A_FSTSW, A_FNSTSW:
  1840. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1841. else
  1842. begin
  1843. with insprop[p.opcode] do
  1844. begin
  1845. if (
  1846. { xor %reg,%reg etc. is classed as a new value }
  1847. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1848. MatchOpType(p, top_reg, top_reg) and
  1849. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1850. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1851. ) then
  1852. begin
  1853. Result := True;
  1854. Exit;
  1855. end;
  1856. { Make sure the entire register is overwritten }
  1857. if (getregtype(reg) = R_INTREGISTER) then
  1858. begin
  1859. if (p.ops > 0) then
  1860. begin
  1861. if RegInOp(reg, p.oper[0]^) then
  1862. begin
  1863. if (p.oper[0]^.typ = top_ref) then
  1864. begin
  1865. if RegInRef(reg, p.oper[0]^.ref^) then
  1866. begin
  1867. Result := False;
  1868. Exit;
  1869. end;
  1870. end
  1871. else if (p.oper[0]^.typ = top_reg) then
  1872. begin
  1873. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end
  1878. else if ([Ch_WOp1]*Ch<>[]) then
  1879. begin
  1880. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1881. Result := True
  1882. else
  1883. begin
  1884. Result := False;
  1885. Exit;
  1886. end;
  1887. end;
  1888. end;
  1889. end;
  1890. if (p.ops > 1) then
  1891. begin
  1892. if RegInOp(reg, p.oper[1]^) then
  1893. begin
  1894. if (p.oper[1]^.typ = top_ref) then
  1895. begin
  1896. if RegInRef(reg, p.oper[1]^.ref^) then
  1897. begin
  1898. Result := False;
  1899. Exit;
  1900. end;
  1901. end
  1902. else if (p.oper[1]^.typ = top_reg) then
  1903. begin
  1904. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1905. begin
  1906. Result := False;
  1907. Exit;
  1908. end
  1909. else if ([Ch_WOp2]*Ch<>[]) then
  1910. begin
  1911. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1912. Result := True
  1913. else
  1914. begin
  1915. Result := False;
  1916. Exit;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. if (p.ops > 2) then
  1922. begin
  1923. if RegInOp(reg, p.oper[2]^) then
  1924. begin
  1925. if (p.oper[2]^.typ = top_ref) then
  1926. begin
  1927. if RegInRef(reg, p.oper[2]^.ref^) then
  1928. begin
  1929. Result := False;
  1930. Exit;
  1931. end;
  1932. end
  1933. else if (p.oper[2]^.typ = top_reg) then
  1934. begin
  1935. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1936. begin
  1937. Result := False;
  1938. Exit;
  1939. end
  1940. else if ([Ch_WOp3]*Ch<>[]) then
  1941. begin
  1942. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1943. Result := True
  1944. else
  1945. begin
  1946. Result := False;
  1947. Exit;
  1948. end;
  1949. end;
  1950. end;
  1951. end;
  1952. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1953. begin
  1954. if (p.oper[3]^.typ = top_ref) then
  1955. begin
  1956. if RegInRef(reg, p.oper[3]^.ref^) then
  1957. begin
  1958. Result := False;
  1959. Exit;
  1960. end;
  1961. end
  1962. else if (p.oper[3]^.typ = top_reg) then
  1963. begin
  1964. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end
  1969. else if ([Ch_WOp4]*Ch<>[]) then
  1970. begin
  1971. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1972. Result := True
  1973. else
  1974. begin
  1975. Result := False;
  1976. Exit;
  1977. end;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1985. case getsupreg(reg) of
  1986. RS_EAX:
  1987. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1988. begin
  1989. Result := True;
  1990. Exit;
  1991. end;
  1992. RS_ECX:
  1993. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1994. begin
  1995. Result := True;
  1996. Exit;
  1997. end;
  1998. RS_EDX:
  1999. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2000. begin
  2001. Result := True;
  2002. Exit;
  2003. end;
  2004. RS_EBX:
  2005. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2006. begin
  2007. Result := True;
  2008. Exit;
  2009. end;
  2010. RS_ESP:
  2011. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2012. begin
  2013. Result := True;
  2014. Exit;
  2015. end;
  2016. RS_EBP:
  2017. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2018. begin
  2019. Result := True;
  2020. Exit;
  2021. end;
  2022. RS_ESI:
  2023. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2024. begin
  2025. Result := True;
  2026. Exit;
  2027. end;
  2028. RS_EDI:
  2029. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2030. begin
  2031. Result := True;
  2032. Exit;
  2033. end;
  2034. else
  2035. ;
  2036. end;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2043. var
  2044. hp2,hp3 : tai;
  2045. begin
  2046. { some x86-64 issue a NOP before the real exit code }
  2047. if MatchInstruction(p,A_NOP,[]) then
  2048. GetNextInstruction(p,p);
  2049. result:=assigned(p) and (p.typ=ait_instruction) and
  2050. ((taicpu(p).opcode = A_RET) or
  2051. ((taicpu(p).opcode=A_LEAVE) and
  2052. GetNextInstruction(p,hp2) and
  2053. MatchInstruction(hp2,A_RET,[S_NO])
  2054. ) or
  2055. (((taicpu(p).opcode=A_LEA) and
  2056. MatchOpType(taicpu(p),top_ref,top_reg) and
  2057. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2058. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2059. ) and
  2060. GetNextInstruction(p,hp2) and
  2061. MatchInstruction(hp2,A_RET,[S_NO])
  2062. ) or
  2063. ((((taicpu(p).opcode=A_MOV) and
  2064. MatchOpType(taicpu(p),top_reg,top_reg) and
  2065. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2066. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2067. ((taicpu(p).opcode=A_LEA) and
  2068. MatchOpType(taicpu(p),top_ref,top_reg) and
  2069. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2070. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2071. )
  2072. ) and
  2073. GetNextInstruction(p,hp2) and
  2074. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2075. MatchOpType(taicpu(hp2),top_reg) and
  2076. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2077. GetNextInstruction(hp2,hp3) and
  2078. MatchInstruction(hp3,A_RET,[S_NO])
  2079. )
  2080. );
  2081. end;
  2082. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2083. begin
  2084. isFoldableArithOp := False;
  2085. case hp1.opcode of
  2086. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2087. isFoldableArithOp :=
  2088. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2089. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2090. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2092. (taicpu(hp1).oper[1]^.reg = reg);
  2093. A_INC,A_DEC,A_NEG,A_NOT:
  2094. isFoldableArithOp :=
  2095. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2096. (taicpu(hp1).oper[0]^.reg = reg);
  2097. else
  2098. ;
  2099. end;
  2100. end;
  2101. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2102. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2103. var
  2104. hp2: tai;
  2105. begin
  2106. hp2 := p;
  2107. repeat
  2108. hp2 := tai(hp2.previous);
  2109. if assigned(hp2) and
  2110. (hp2.typ = ait_regalloc) and
  2111. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2112. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2113. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2114. begin
  2115. RemoveInstruction(hp2);
  2116. break;
  2117. end;
  2118. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2119. end;
  2120. begin
  2121. case current_procinfo.procdef.returndef.typ of
  2122. arraydef,recorddef,pointerdef,
  2123. stringdef,enumdef,procdef,objectdef,errordef,
  2124. filedef,setdef,procvardef,
  2125. classrefdef,forwarddef:
  2126. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2127. orddef:
  2128. if current_procinfo.procdef.returndef.size <> 0 then
  2129. begin
  2130. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2131. { for int64/qword }
  2132. if current_procinfo.procdef.returndef.size = 8 then
  2133. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2134. end;
  2135. else
  2136. ;
  2137. end;
  2138. end;
  2139. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2140. var
  2141. hp1: tai;
  2142. operswap: poper;
  2143. begin
  2144. Result := False;
  2145. { Optimise:
  2146. cmov(c) %reg1,%reg2
  2147. mov %reg2,%reg1
  2148. (%reg2 dealloc.)
  2149. To:
  2150. cmov(~c) %reg2,%reg1
  2151. }
  2152. if (taicpu(p).oper[0]^.typ = top_reg) then
  2153. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2154. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2156. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2160. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2163. { Save time by swapping the pointers (they're both registers, so
  2164. we don't need to worry about reference counts) }
  2165. operswap := taicpu(p).oper[0];
  2166. taicpu(p).oper[0] := taicpu(p).oper[1];
  2167. taicpu(p).oper[1] := operswap;
  2168. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2169. RemoveInstruction(hp1);
  2170. { It's still a CMOV, so we can look further ahead }
  2171. Include(OptsToCheck, aoc_ForceNewIteration);
  2172. { But first, let's see if this will get optimised again
  2173. (probably won't happen, but best to be sure) }
  2174. Continue;
  2175. end;
  2176. Break;
  2177. end;
  2178. end;
  2179. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2180. var
  2181. hp1,hp2 : tai;
  2182. begin
  2183. result:=false;
  2184. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2185. begin
  2186. { vmova* reg1,reg1
  2187. =>
  2188. <nop> }
  2189. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2190. begin
  2191. RemoveCurrentP(p);
  2192. result:=true;
  2193. exit;
  2194. end;
  2195. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2196. (hp1.typ = ait_instruction) and
  2197. (
  2198. { Under -O2 and below, the instructions are always adjacent }
  2199. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2200. (taicpu(hp1).ops <= 1) or
  2201. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2202. { If reg1 = reg3, reg1 must not be modified in between }
  2203. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2204. ) then
  2205. begin
  2206. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2207. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2208. begin
  2209. { vmova* reg1,reg2
  2210. ...
  2211. vmova* reg2,reg3
  2212. dealloc reg2
  2213. =>
  2214. vmova* reg1,reg3 }
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2217. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2218. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2219. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2220. begin
  2221. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2222. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2223. TransferUsedRegs(TmpUsedRegs);
  2224. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2225. RemoveInstruction(hp1);
  2226. result:=true;
  2227. exit;
  2228. end;
  2229. { special case:
  2230. vmova* reg1,<op>
  2231. ...
  2232. vmova* <op>,reg1
  2233. =>
  2234. vmova* reg1,<op> }
  2235. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2236. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2237. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2238. ) then
  2239. begin
  2240. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2241. RemoveInstruction(hp1);
  2242. result:=true;
  2243. exit;
  2244. end
  2245. end
  2246. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2247. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2248. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2249. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2250. ) and
  2251. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2252. begin
  2253. { vmova* reg1,reg2
  2254. ...
  2255. vmovs* reg2,<op>
  2256. dealloc reg2
  2257. =>
  2258. vmovs* reg1,<op> }
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2261. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2264. taicpu(p).opcode:=taicpu(hp1).opcode;
  2265. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2266. TransferUsedRegs(TmpUsedRegs);
  2267. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end;
  2273. if MatchInstruction(hp1,[A_VFMADDPD,
  2274. A_VFMADD132PD,
  2275. A_VFMADD132PS,
  2276. A_VFMADD132SD,
  2277. A_VFMADD132SS,
  2278. A_VFMADD213PD,
  2279. A_VFMADD213PS,
  2280. A_VFMADD213SD,
  2281. A_VFMADD213SS,
  2282. A_VFMADD231PD,
  2283. A_VFMADD231PS,
  2284. A_VFMADD231SD,
  2285. A_VFMADD231SS,
  2286. A_VFMADDSUB132PD,
  2287. A_VFMADDSUB132PS,
  2288. A_VFMADDSUB213PD,
  2289. A_VFMADDSUB213PS,
  2290. A_VFMADDSUB231PD,
  2291. A_VFMADDSUB231PS,
  2292. A_VFMSUB132PD,
  2293. A_VFMSUB132PS,
  2294. A_VFMSUB132SD,
  2295. A_VFMSUB132SS,
  2296. A_VFMSUB213PD,
  2297. A_VFMSUB213PS,
  2298. A_VFMSUB213SD,
  2299. A_VFMSUB213SS,
  2300. A_VFMSUB231PD,
  2301. A_VFMSUB231PS,
  2302. A_VFMSUB231SD,
  2303. A_VFMSUB231SS,
  2304. A_VFMSUBADD132PD,
  2305. A_VFMSUBADD132PS,
  2306. A_VFMSUBADD213PD,
  2307. A_VFMSUBADD213PS,
  2308. A_VFMSUBADD231PD,
  2309. A_VFMSUBADD231PS,
  2310. A_VFNMADD132PD,
  2311. A_VFNMADD132PS,
  2312. A_VFNMADD132SD,
  2313. A_VFNMADD132SS,
  2314. A_VFNMADD213PD,
  2315. A_VFNMADD213PS,
  2316. A_VFNMADD213SD,
  2317. A_VFNMADD213SS,
  2318. A_VFNMADD231PD,
  2319. A_VFNMADD231PS,
  2320. A_VFNMADD231SD,
  2321. A_VFNMADD231SS,
  2322. A_VFNMSUB132PD,
  2323. A_VFNMSUB132PS,
  2324. A_VFNMSUB132SD,
  2325. A_VFNMSUB132SS,
  2326. A_VFNMSUB213PD,
  2327. A_VFNMSUB213PS,
  2328. A_VFNMSUB213SD,
  2329. A_VFNMSUB213SS,
  2330. A_VFNMSUB231PD,
  2331. A_VFNMSUB231PS,
  2332. A_VFNMSUB231SD,
  2333. A_VFNMSUB231SS],[S_NO]) and
  2334. { we mix single and double opperations here because we assume that the compiler
  2335. generates vmovapd only after double operations and vmovaps only after single operations }
  2336. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2337. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2338. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2339. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2340. begin
  2341. TransferUsedRegs(TmpUsedRegs);
  2342. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2343. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2344. begin
  2345. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2346. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2347. RemoveCurrentP(p)
  2348. else
  2349. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2350. RemoveInstruction(hp2);
  2351. end;
  2352. end
  2353. else if (hp1.typ = ait_instruction) and
  2354. (((taicpu(p).opcode=A_MOVAPS) and
  2355. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2356. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2357. ((taicpu(p).opcode=A_MOVAPD) and
  2358. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2359. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2360. ) and
  2361. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2362. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2363. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2364. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2365. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2366. { change
  2367. movapX reg,reg2
  2368. addsX/subsX/... reg3, reg2
  2369. movapX reg2,reg
  2370. to
  2371. addsX/subsX/... reg3,reg
  2372. }
  2373. begin
  2374. TransferUsedRegs(TmpUsedRegs);
  2375. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2376. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2377. begin
  2378. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2379. debug_op2str(taicpu(p).opcode)+' '+
  2380. debug_op2str(taicpu(hp1).opcode)+' '+
  2381. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2382. { we cannot eliminate the first move if
  2383. the operations uses the same register for source and dest }
  2384. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2385. { Remember that hp1 is not necessarily the immediate
  2386. next instruction }
  2387. RemoveCurrentP(p);
  2388. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2389. RemoveInstruction(hp2);
  2390. result:=true;
  2391. end;
  2392. end
  2393. else if (hp1.typ = ait_instruction) and
  2394. (((taicpu(p).opcode=A_VMOVAPD) and
  2395. (taicpu(hp1).opcode=A_VCOMISD)) or
  2396. ((taicpu(p).opcode=A_VMOVAPS) and
  2397. ((taicpu(hp1).opcode=A_VCOMISS))
  2398. )
  2399. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2400. { change
  2401. movapX reg,reg1
  2402. vcomisX reg1,reg1
  2403. to
  2404. vcomisX reg,reg
  2405. }
  2406. begin
  2407. TransferUsedRegs(TmpUsedRegs);
  2408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2409. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2410. begin
  2411. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2412. debug_op2str(taicpu(p).opcode)+' '+
  2413. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2414. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2415. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2416. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2417. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2418. RemoveCurrentP(p);
  2419. result:=true;
  2420. exit;
  2421. end;
  2422. end
  2423. end;
  2424. end;
  2425. end;
  2426. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2427. var
  2428. hp1 : tai;
  2429. begin
  2430. result:=false;
  2431. { replace
  2432. V<Op>X %mreg1,%mreg2,%mreg3
  2433. VMovX %mreg3,%mreg4
  2434. dealloc %mreg3
  2435. by
  2436. V<Op>X %mreg1,%mreg2,%mreg4
  2437. ?
  2438. }
  2439. if GetNextInstruction(p,hp1) and
  2440. { we mix single and double operations here because we assume that the compiler
  2441. generates vmovapd only after double operations and vmovaps only after single operations }
  2442. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2443. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2444. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2445. begin
  2446. TransferUsedRegs(TmpUsedRegs);
  2447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2448. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2449. begin
  2450. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2451. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2452. RemoveInstruction(hp1);
  2453. result:=true;
  2454. end;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2459. begin
  2460. Result := False;
  2461. { For safety reasons, only check for exact register matches }
  2462. { Check base register }
  2463. if (ref.base = AOldReg) then
  2464. begin
  2465. ref.base := ANewReg;
  2466. Result := True;
  2467. end;
  2468. { Check index register }
  2469. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2470. begin
  2471. ref.index := ANewReg;
  2472. Result := True;
  2473. end;
  2474. end;
  2475. { Replaces all references to AOldReg in an operand to ANewReg }
  2476. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2477. var
  2478. OldSupReg, NewSupReg: TSuperRegister;
  2479. OldSubReg, NewSubReg: TSubRegister;
  2480. OldRegType: TRegisterType;
  2481. ThisOper: POper;
  2482. begin
  2483. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2484. Result := False;
  2485. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2486. InternalError(2020011801);
  2487. OldSupReg := getsupreg(AOldReg);
  2488. OldSubReg := getsubreg(AOldReg);
  2489. OldRegType := getregtype(AOldReg);
  2490. NewSupReg := getsupreg(ANewReg);
  2491. NewSubReg := getsubreg(ANewReg);
  2492. if OldRegType <> getregtype(ANewReg) then
  2493. InternalError(2020011802);
  2494. if OldSubReg <> NewSubReg then
  2495. InternalError(2020011803);
  2496. case ThisOper^.typ of
  2497. top_reg:
  2498. if (
  2499. (ThisOper^.reg = AOldReg) or
  2500. (
  2501. (OldRegType = R_INTREGISTER) and
  2502. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2503. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2504. (
  2505. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2506. {$ifndef x86_64}
  2507. and (
  2508. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2509. don't have an 8-bit representation }
  2510. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2511. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2512. )
  2513. {$endif x86_64}
  2514. )
  2515. )
  2516. ) then
  2517. begin
  2518. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2519. Result := True;
  2520. end;
  2521. top_ref:
  2522. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2523. Result := True;
  2524. else
  2525. ;
  2526. end;
  2527. end;
  2528. { Replaces all references to AOldReg in an instruction to ANewReg }
  2529. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2530. const
  2531. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2532. var
  2533. OperIdx: Integer;
  2534. begin
  2535. Result := False;
  2536. for OperIdx := 0 to p.ops - 1 do
  2537. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2538. begin
  2539. { The shift and rotate instructions can only use CL }
  2540. if not (
  2541. (OperIdx = 0) and
  2542. { This second condition just helps to avoid unnecessarily
  2543. calling MatchInstruction for 10 different opcodes }
  2544. (p.oper[0]^.reg = NR_CL) and
  2545. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2546. ) then
  2547. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2548. end
  2549. else if p.oper[OperIdx]^.typ = top_ref then
  2550. { It's okay to replace registers in references that get written to }
  2551. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2552. end;
  2553. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2554. begin
  2555. Result :=
  2556. (ref^.index = NR_NO) and
  2557. (
  2558. {$ifdef x86_64}
  2559. (
  2560. (ref^.base = NR_RIP) and
  2561. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2562. ) or
  2563. {$endif x86_64}
  2564. (ref^.refaddr = addr_full) or
  2565. (ref^.base = NR_STACK_POINTER_REG) or
  2566. (ref^.base = current_procinfo.framepointer)
  2567. );
  2568. end;
  2569. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2570. var
  2571. l: asizeint;
  2572. begin
  2573. Result := False;
  2574. { Should have been checked previously }
  2575. if p.opcode <> A_LEA then
  2576. InternalError(2020072501);
  2577. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2578. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2579. not(cs_opt_size in current_settings.optimizerswitches) then
  2580. exit;
  2581. with p.oper[0]^.ref^ do
  2582. begin
  2583. if (base <> p.oper[1]^.reg) or
  2584. (index <> NR_NO) or
  2585. assigned(symbol) then
  2586. exit;
  2587. l:=offset;
  2588. if (l=1) and UseIncDec then
  2589. begin
  2590. p.opcode:=A_INC;
  2591. p.loadreg(0,p.oper[1]^.reg);
  2592. p.ops:=1;
  2593. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2594. end
  2595. else if (l=-1) and UseIncDec then
  2596. begin
  2597. p.opcode:=A_DEC;
  2598. p.loadreg(0,p.oper[1]^.reg);
  2599. p.ops:=1;
  2600. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2601. end
  2602. else
  2603. begin
  2604. if (l<0) and (l<>-2147483648) then
  2605. begin
  2606. p.opcode:=A_SUB;
  2607. p.loadConst(0,-l);
  2608. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2609. end
  2610. else
  2611. begin
  2612. p.opcode:=A_ADD;
  2613. p.loadConst(0,l);
  2614. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2615. end;
  2616. end;
  2617. end;
  2618. Result := True;
  2619. end;
  2620. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2621. var
  2622. CurrentReg, ReplaceReg: TRegister;
  2623. begin
  2624. Result := False;
  2625. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2626. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2627. case hp.opcode of
  2628. A_FSTSW, A_FNSTSW,
  2629. A_IN, A_INS, A_OUT, A_OUTS,
  2630. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2631. { These routines have explicit operands, but they are restricted in
  2632. what they can be (e.g. IN and OUT can only read from AL, AX or
  2633. EAX. }
  2634. Exit;
  2635. A_IMUL:
  2636. begin
  2637. { The 1-operand version writes to implicit registers
  2638. The 2-operand version reads from the first operator, and reads
  2639. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2640. the 3-operand version reads from a register that it doesn't write to
  2641. }
  2642. case hp.ops of
  2643. 1:
  2644. if (
  2645. (
  2646. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2647. ) or
  2648. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2649. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2650. begin
  2651. Result := True;
  2652. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2653. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2654. end;
  2655. 2:
  2656. { Only modify the first parameter }
  2657. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2658. begin
  2659. Result := True;
  2660. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2661. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2662. end;
  2663. 3:
  2664. { Only modify the second parameter }
  2665. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2666. begin
  2667. Result := True;
  2668. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2669. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2670. end;
  2671. else
  2672. InternalError(2020012901);
  2673. end;
  2674. end;
  2675. else
  2676. if (hp.ops > 0) and
  2677. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2678. begin
  2679. Result := True;
  2680. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2681. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2682. end;
  2683. end;
  2684. end;
  2685. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2686. var
  2687. hp2, hp_regalloc: tai;
  2688. p_SourceReg, p_TargetReg: TRegister;
  2689. begin
  2690. Result := False;
  2691. { Backward optimisation. If we have:
  2692. func. %reg1,%reg2
  2693. mov %reg2,%reg3
  2694. (dealloc %reg2)
  2695. Change to:
  2696. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2697. Perform similar optimisations with 1, 3 and 4-operand instructions
  2698. that only have one output.
  2699. }
  2700. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2701. begin
  2702. p_SourceReg := taicpu(p).oper[0]^.reg;
  2703. p_TargetReg := taicpu(p).oper[1]^.reg;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2706. GetLastInstruction(p, hp2) and
  2707. (hp2.typ = ait_instruction) and
  2708. { Have to make sure it's an instruction that only reads from
  2709. the first operands and only writes (not reads or modifies) to
  2710. the last one; in essence, a pure function such as BSR, POPCNT
  2711. or ANDN }
  2712. (
  2713. (
  2714. (taicpu(hp2).ops = 1) and
  2715. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2716. ) or
  2717. (
  2718. (taicpu(hp2).ops = 2) and
  2719. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2720. ) or
  2721. (
  2722. (taicpu(hp2).ops = 3) and
  2723. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2724. ) or
  2725. (
  2726. (taicpu(hp2).ops = 4) and
  2727. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2728. )
  2729. ) and
  2730. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2732. begin
  2733. case taicpu(hp2).opcode of
  2734. A_FSTSW, A_FNSTSW,
  2735. A_IN, A_INS, A_OUT, A_OUTS,
  2736. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2737. { These routines have explicit operands, but they are restricted in
  2738. what they can be (e.g. IN and OUT can only read from AL, AX or
  2739. EAX. }
  2740. ;
  2741. else
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2744. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2745. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2746. if Assigned(hp_regalloc) then
  2747. begin
  2748. Asml.Remove(hp_regalloc);
  2749. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2750. begin
  2751. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2752. hp_regalloc.Free;
  2753. end
  2754. else
  2755. { If the register is not explicitly deallocated, it's
  2756. being reused, so move the allocation to after func. }
  2757. AsmL.InsertAfter(hp_regalloc, hp2);
  2758. end;
  2759. if not RegInInstruction(p_TargetReg, hp2) then
  2760. begin
  2761. TransferUsedRegs(TmpUsedRegs);
  2762. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2763. end;
  2764. { Actually make the changes }
  2765. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2766. RemoveCurrentp(p, hp1);
  2767. { If the Func was another MOV instruction, we might get
  2768. "mov %reg,%reg" that doesn't get removed in Pass 2
  2769. otherwise, so deal with it here (also do something
  2770. similar with lea (%reg),%reg}
  2771. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2772. begin
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2774. if p = hp2 then
  2775. RemoveCurrentp(p)
  2776. else
  2777. RemoveInstruction(hp2);
  2778. end;
  2779. Result := True;
  2780. Exit;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2787. begin
  2788. Result := False;
  2789. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2790. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2792. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2793. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2794. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2795. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2799. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2800. Result := True;
  2801. Include(OptsToCheck, aoc_ForceNewIteration);
  2802. end;
  2803. end;
  2804. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2805. var
  2806. hp1, hp2, hp3, hp4: tai;
  2807. DoOptimisation, TempBool: Boolean;
  2808. {$ifdef x86_64}
  2809. NewConst: TCGInt;
  2810. {$endif x86_64}
  2811. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2812. begin
  2813. if taicpu(hp1).opcode = signed_movop then
  2814. begin
  2815. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2816. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2817. end
  2818. else
  2819. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2820. end;
  2821. function TryConstMerge(var p1, p2: tai): Boolean;
  2822. var
  2823. ThisRef: TReference;
  2824. begin
  2825. Result := False;
  2826. ThisRef := taicpu(p2).oper[1]^.ref^;
  2827. { Only permit writes to the stack, since we can guarantee alignment with that }
  2828. if (ThisRef.index = NR_NO) and
  2829. (
  2830. (ThisRef.base = NR_STACK_POINTER_REG) or
  2831. (ThisRef.base = current_procinfo.framepointer)
  2832. ) then
  2833. begin
  2834. case taicpu(p).opsize of
  2835. S_B:
  2836. begin
  2837. { Word writes must be on a 2-byte boundary }
  2838. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2839. begin
  2840. { Reduce offset of second reference to see if it is sequential with the first }
  2841. Dec(ThisRef.offset, 1);
  2842. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2843. begin
  2844. { Make sure the constants aren't represented as a
  2845. negative number, as these won't merge properly }
  2846. taicpu(p1).opsize := S_W;
  2847. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2848. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2849. RemoveInstruction(p2);
  2850. Result := True;
  2851. end;
  2852. end;
  2853. end;
  2854. S_W:
  2855. begin
  2856. { Longword writes must be on a 4-byte boundary }
  2857. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2858. begin
  2859. { Reduce offset of second reference to see if it is sequential with the first }
  2860. Dec(ThisRef.offset, 2);
  2861. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2862. begin
  2863. { Make sure the constants aren't represented as a
  2864. negative number, as these won't merge properly }
  2865. taicpu(p1).opsize := S_L;
  2866. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2867. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2868. RemoveInstruction(p2);
  2869. Result := True;
  2870. end;
  2871. end;
  2872. end;
  2873. {$ifdef x86_64}
  2874. S_L:
  2875. begin
  2876. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2877. see if the constants can be encoded this way. }
  2878. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2879. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2880. { Quadword writes must be on an 8-byte boundary }
  2881. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2882. begin
  2883. { Reduce offset of second reference to see if it is sequential with the first }
  2884. Dec(ThisRef.offset, 4);
  2885. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2886. begin
  2887. { Make sure the constants aren't represented as a
  2888. negative number, as these won't merge properly }
  2889. taicpu(p1).opsize := S_Q;
  2890. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2891. taicpu(p1).oper[0]^.val := NewConst;
  2892. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2893. RemoveInstruction(p2);
  2894. Result := True;
  2895. end;
  2896. end;
  2897. end;
  2898. {$endif x86_64}
  2899. else
  2900. ;
  2901. end;
  2902. end;
  2903. end;
  2904. var
  2905. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2906. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2907. NewSize: topsize; NewOffset: asizeint;
  2908. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2909. SourceRef, TargetRef: TReference;
  2910. MovAligned, MovUnaligned: TAsmOp;
  2911. ThisRef: TReference;
  2912. JumpTracking: TLinkedList;
  2913. begin
  2914. Result:=false;
  2915. { remove mov reg1,reg1? }
  2916. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2917. then
  2918. begin
  2919. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2920. { take care of the register (de)allocs following p }
  2921. RemoveCurrentP(p);
  2922. Result := True;
  2923. exit;
  2924. end;
  2925. { Prevent compiler warnings }
  2926. p_SourceReg := NR_NO;
  2927. p_TargetReg := NR_NO;
  2928. if taicpu(p).oper[1]^.typ = top_reg then
  2929. begin
  2930. { Saves on a large number of dereferences }
  2931. p_TargetReg := taicpu(p).oper[1]^.reg;
  2932. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2933. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2934. else
  2935. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2936. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2937. begin
  2938. if (taicpu(hp1).opcode = A_AND) and
  2939. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2940. begin
  2941. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2942. begin
  2943. case taicpu(p).opsize of
  2944. S_L:
  2945. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2946. begin
  2947. { Optimize out:
  2948. mov x, %reg
  2949. and ffffffffh, %reg
  2950. }
  2951. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2952. RemoveInstruction(hp1);
  2953. Result:=true;
  2954. exit;
  2955. end;
  2956. S_Q: { TODO: Confirm if this is even possible }
  2957. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2958. begin
  2959. { Optimize out:
  2960. mov x, %reg
  2961. and ffffffffffffffffh, %reg
  2962. }
  2963. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2964. RemoveInstruction(hp1);
  2965. Result:=true;
  2966. exit;
  2967. end;
  2968. else
  2969. ;
  2970. end;
  2971. if (
  2972. { Make sure that if a reference is used, its registers
  2973. are not modified in between }
  2974. (
  2975. (taicpu(p).oper[0]^.typ = top_reg) and
  2976. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2977. ) or
  2978. (
  2979. (taicpu(p).oper[0]^.typ = top_ref) and
  2980. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2981. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2982. )
  2983. ) and
  2984. GetNextInstruction(hp1,hp2) and
  2985. MatchInstruction(hp2,A_TEST,[]) and
  2986. (
  2987. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2988. (
  2989. { If the register being tested is smaller than the one
  2990. that received a bitwise AND, permit it if the constant
  2991. fits into the smaller size }
  2992. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2993. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2994. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2995. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2996. (
  2997. (
  2998. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2999. (taicpu(hp1).oper[0]^.val <= $FF)
  3000. ) or
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3003. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3004. {$ifdef x86_64}
  3005. ) or
  3006. (
  3007. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3008. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3009. {$endif x86_64}
  3010. )
  3011. )
  3012. )
  3013. ) and
  3014. (
  3015. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3016. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3017. ) and
  3018. GetNextInstruction(hp2,hp3) and
  3019. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3020. (taicpu(hp3).condition in [C_E,C_NE]) then
  3021. begin
  3022. TransferUsedRegs(TmpUsedRegs);
  3023. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3024. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3025. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3026. begin
  3027. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3028. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3029. taicpu(hp1).opcode:=A_TEST;
  3030. { Shrink the TEST instruction down to the smallest possible size }
  3031. case taicpu(hp1).oper[0]^.val of
  3032. 0..255:
  3033. if (taicpu(hp1).opsize <> S_B)
  3034. {$ifndef x86_64}
  3035. and (
  3036. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3037. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3038. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3039. )
  3040. {$endif x86_64}
  3041. then
  3042. begin
  3043. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3044. { Only print debug message if the TEST instruction
  3045. is a different size before and after }
  3046. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3047. taicpu(hp1).opsize := S_B;
  3048. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3050. end;
  3051. 256..65535:
  3052. if (taicpu(hp1).opsize <> S_W) then
  3053. begin
  3054. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3055. { Only print debug message if the TEST instruction
  3056. is a different size before and after }
  3057. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3058. taicpu(hp1).opsize := S_W;
  3059. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3060. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3061. end;
  3062. {$ifdef x86_64}
  3063. 65536..$7FFFFFFF:
  3064. if (taicpu(hp1).opsize <> S_L) then
  3065. begin
  3066. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3067. { Only print debug message if the TEST instruction
  3068. is a different size before and after }
  3069. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3070. taicpu(hp1).opsize := S_L;
  3071. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3072. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3073. end;
  3074. {$endif x86_64}
  3075. else
  3076. ;
  3077. end;
  3078. RemoveInstruction(hp2);
  3079. RemoveCurrentP(p);
  3080. Result:=true;
  3081. exit;
  3082. end;
  3083. end;
  3084. end;
  3085. if IsMOVZXAcceptable and
  3086. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3087. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3088. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3089. then
  3090. begin
  3091. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3092. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3093. case taicpu(p).opsize of
  3094. S_B:
  3095. if (taicpu(hp1).oper[0]^.val = $ff) then
  3096. begin
  3097. { Convert:
  3098. movb x, %regl movb x, %regl
  3099. andw ffh, %regw andl ffh, %regd
  3100. To:
  3101. movzbw x, %regd movzbl x, %regd
  3102. (Identical registers, just different sizes)
  3103. }
  3104. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3105. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3106. case taicpu(hp1).opsize of
  3107. S_W: NewSize := S_BW;
  3108. S_L: NewSize := S_BL;
  3109. {$ifdef x86_64}
  3110. S_Q: NewSize := S_BQ;
  3111. {$endif x86_64}
  3112. else
  3113. InternalError(2018011510);
  3114. end;
  3115. end
  3116. else
  3117. NewSize := S_NO;
  3118. S_W:
  3119. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3120. begin
  3121. { Convert:
  3122. movw x, %regw
  3123. andl ffffh, %regd
  3124. To:
  3125. movzwl x, %regd
  3126. (Identical registers, just different sizes)
  3127. }
  3128. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3129. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3130. case taicpu(hp1).opsize of
  3131. S_L: NewSize := S_WL;
  3132. {$ifdef x86_64}
  3133. S_Q: NewSize := S_WQ;
  3134. {$endif x86_64}
  3135. else
  3136. InternalError(2018011511);
  3137. end;
  3138. end
  3139. else
  3140. NewSize := S_NO;
  3141. else
  3142. NewSize := S_NO;
  3143. end;
  3144. if NewSize <> S_NO then
  3145. begin
  3146. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3147. { The actual optimization }
  3148. taicpu(p).opcode := A_MOVZX;
  3149. taicpu(p).changeopsize(NewSize);
  3150. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3151. { Make sure we deal with any reference counts that were increased }
  3152. if taicpu(hp1).oper[1]^.typ = top_ref then
  3153. begin
  3154. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3155. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3156. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3157. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3158. end;
  3159. { Safeguard if "and" is followed by a conditional command }
  3160. TransferUsedRegs(TmpUsedRegs);
  3161. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3162. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3163. begin
  3164. { At this point, the "and" command is effectively equivalent to
  3165. "test %reg,%reg". This will be handled separately by the
  3166. Peephole Optimizer. [Kit] }
  3167. DebugMsg(SPeepholeOptimization + PreMessage +
  3168. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3169. end
  3170. else
  3171. begin
  3172. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3173. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3174. RemoveInstruction(hp1);
  3175. end;
  3176. Result := True;
  3177. Exit;
  3178. end;
  3179. end;
  3180. end;
  3181. if taicpu(p).oper[0]^.typ = top_reg then
  3182. begin
  3183. p_SourceReg := taicpu(p).oper[0]^.reg;
  3184. { Look for:
  3185. mov %reg1,%reg2
  3186. ??? %reg2,r/m
  3187. Change to:
  3188. mov %reg1,%reg2
  3189. ??? %reg1,r/m
  3190. }
  3191. if RegReadByInstruction(p_TargetReg, hp1) and
  3192. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3193. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3194. begin
  3195. { A change has occurred, just not in p }
  3196. Include(OptsToCheck, aoc_ForceNewIteration);
  3197. TransferUsedRegs(TmpUsedRegs);
  3198. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3199. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3200. { Just in case something didn't get modified (e.g. an
  3201. implicit register) }
  3202. not RegReadByInstruction(p_TargetReg, hp1) then
  3203. begin
  3204. { We can remove the original MOV }
  3205. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3206. RemoveCurrentP(p);
  3207. { UsedRegs got updated by RemoveCurrentp }
  3208. Result := True;
  3209. Exit;
  3210. end;
  3211. { If we know a MOV instruction has become a null operation, we might as well
  3212. get rid of it now to save time. }
  3213. if (taicpu(hp1).opcode = A_MOV) and
  3214. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3215. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3216. { Just being a register is enough to confirm it's a null operation }
  3217. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3218. begin
  3219. Result := True;
  3220. { Speed-up to reduce a pipeline stall... if we had something like...
  3221. movl %eax,%edx
  3222. movw %dx,%ax
  3223. ... the second instruction would change to movw %ax,%ax, but
  3224. given that it is now %ax that's active rather than %eax,
  3225. penalties might occur due to a partial register write, so instead,
  3226. change it to a MOVZX instruction when optimising for speed.
  3227. }
  3228. if not (cs_opt_size in current_settings.optimizerswitches) and
  3229. IsMOVZXAcceptable and
  3230. (taicpu(hp1).opsize < taicpu(p).opsize)
  3231. {$ifdef x86_64}
  3232. { operations already implicitly set the upper 64 bits to zero }
  3233. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3234. {$endif x86_64}
  3235. then
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3238. case taicpu(p).opsize of
  3239. S_W:
  3240. if taicpu(hp1).opsize = S_B then
  3241. taicpu(hp1).opsize := S_BL
  3242. else
  3243. InternalError(2020012911);
  3244. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3245. case taicpu(hp1).opsize of
  3246. S_B:
  3247. taicpu(hp1).opsize := S_BL;
  3248. S_W:
  3249. taicpu(hp1).opsize := S_WL;
  3250. else
  3251. InternalError(2020012912);
  3252. end;
  3253. else
  3254. InternalError(2020012910);
  3255. end;
  3256. taicpu(hp1).opcode := A_MOVZX;
  3257. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3258. end
  3259. else
  3260. begin
  3261. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3262. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3263. RemoveInstruction(hp1);
  3264. { The instruction after what was hp1 is now the immediate next instruction,
  3265. so we can continue to make optimisations if it's present }
  3266. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3267. Exit;
  3268. hp1 := hp2;
  3269. end;
  3270. end;
  3271. end;
  3272. {$ifdef x86_64}
  3273. { Change:
  3274. movl %reg1l,%reg2l
  3275. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3276. To:
  3277. movl %reg1l,%reg2l
  3278. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3279. If %reg1 = %reg3, convert to:
  3280. movl %reg1l,%reg2l
  3281. andl %reg1l,%reg1l
  3282. }
  3283. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3284. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3285. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3286. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3287. begin
  3288. TransferUsedRegs(TmpUsedRegs);
  3289. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3290. taicpu(hp1).opsize := S_L;
  3291. taicpu(hp1).loadreg(0, p_SourceReg);
  3292. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3293. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3294. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3295. begin
  3296. { %reg1 = %reg3 }
  3297. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3298. taicpu(hp1).opcode := A_AND;
  3299. end
  3300. else
  3301. begin
  3302. { %reg1 <> %reg3 }
  3303. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3304. end;
  3305. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3306. begin
  3307. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3308. RemoveCurrentP(p);
  3309. Result := True;
  3310. Exit;
  3311. end
  3312. else
  3313. begin
  3314. { Initial instruction wasn't actually changed }
  3315. Include(OptsToCheck, aoc_ForceNewIteration);
  3316. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3317. appears below since %reg1 has technically changed }
  3318. if taicpu(hp1).opcode = A_AND then
  3319. Exit;
  3320. end;
  3321. end;
  3322. {$endif x86_64}
  3323. end
  3324. else if taicpu(p).oper[0]^.typ = top_const then
  3325. begin
  3326. if (taicpu(hp1).opcode = A_OR) and
  3327. (taicpu(p).oper[1]^.typ = top_reg) and
  3328. MatchOperand(taicpu(p).oper[0]^, 0) and
  3329. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3330. begin
  3331. { mov 0, %reg
  3332. or ###,%reg
  3333. Change to (only if the flags are not used):
  3334. mov ###,%reg
  3335. }
  3336. TransferUsedRegs(TmpUsedRegs);
  3337. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3338. DoOptimisation := True;
  3339. { Even if the flags are used, we might be able to do the optimisation
  3340. if the conditions are predictable }
  3341. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3342. begin
  3343. { Only perform if ### = %reg (the same register) or equal to 0,
  3344. so %reg is guaranteed to still have a value of zero }
  3345. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3346. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3347. begin
  3348. hp2 := hp1;
  3349. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3350. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3351. GetNextInstruction(hp2, hp3) do
  3352. begin
  3353. { Don't continue modifying if the flags state is getting changed }
  3354. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3355. Break;
  3356. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3357. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3358. begin
  3359. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3360. begin
  3361. { Condition is always true }
  3362. case taicpu(hp3).opcode of
  3363. A_Jcc:
  3364. begin
  3365. { Check for jump shortcuts before we destroy the condition }
  3366. hp4 := hp3;
  3367. DoJumpOptimizations(hp3, TempBool);
  3368. { Make sure hp3 hasn't changed }
  3369. if (hp4 = hp3) then
  3370. begin
  3371. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3372. MakeUnconditional(taicpu(hp3));
  3373. end;
  3374. Result := True;
  3375. end;
  3376. A_CMOVcc:
  3377. begin
  3378. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3379. taicpu(hp3).opcode := A_MOV;
  3380. taicpu(hp3).condition := C_None;
  3381. Result := True;
  3382. end;
  3383. A_SETcc:
  3384. begin
  3385. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3386. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3387. taicpu(hp3).opcode := A_MOV;
  3388. taicpu(hp3).ops := 2;
  3389. taicpu(hp3).condition := C_None;
  3390. taicpu(hp3).opsize := S_B;
  3391. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3392. taicpu(hp3).loadconst(0, 1);
  3393. Result := True;
  3394. end;
  3395. else
  3396. InternalError(2021090701);
  3397. end;
  3398. end
  3399. 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
  3400. begin
  3401. { Condition is always false }
  3402. case taicpu(hp3).opcode of
  3403. A_Jcc:
  3404. begin
  3405. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3406. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3407. RemoveInstruction(hp3);
  3408. Result := True;
  3409. { Since hp3 was deleted, hp2 must not be updated }
  3410. Continue;
  3411. end;
  3412. A_CMOVcc:
  3413. begin
  3414. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3415. RemoveInstruction(hp3);
  3416. Result := True;
  3417. { Since hp3 was deleted, hp2 must not be updated }
  3418. Continue;
  3419. end;
  3420. A_SETcc:
  3421. begin
  3422. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3423. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3424. taicpu(hp3).opcode := A_MOV;
  3425. taicpu(hp3).ops := 2;
  3426. taicpu(hp3).condition := C_None;
  3427. taicpu(hp3).opsize := S_B;
  3428. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3429. taicpu(hp3).loadconst(0, 0);
  3430. Result := True;
  3431. end;
  3432. else
  3433. InternalError(2021090702);
  3434. end;
  3435. end
  3436. else
  3437. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3438. DoOptimisation := False;
  3439. end;
  3440. hp2 := hp3;
  3441. end;
  3442. if DoOptimisation then
  3443. begin
  3444. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3445. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3446. { Flags are still in use - don't optimise }
  3447. DoOptimisation := False;
  3448. end;
  3449. end
  3450. else
  3451. DoOptimisation := False;
  3452. end;
  3453. if DoOptimisation then
  3454. begin
  3455. {$ifdef x86_64}
  3456. { OR only supports 32-bit sign-extended constants for 64-bit
  3457. instructions, so compensate for this if the constant is
  3458. encoded as a value greater than or equal to 2^31 }
  3459. if (taicpu(hp1).opsize = S_Q) and
  3460. (taicpu(hp1).oper[0]^.typ = top_const) and
  3461. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3462. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3463. {$endif x86_64}
  3464. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3465. taicpu(hp1).opcode := A_MOV;
  3466. RemoveCurrentP(p);
  3467. Result := True;
  3468. Exit;
  3469. end;
  3470. end;
  3471. end
  3472. else if
  3473. { oper[0] is a reference }
  3474. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3475. begin
  3476. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3477. begin
  3478. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3479. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3480. ) or
  3481. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3482. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3483. )
  3484. ) and
  3485. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3486. { mov ref,reg1
  3487. lea (reg1,reg2),reg2
  3488. to
  3489. add ref,reg2 }
  3490. begin
  3491. TransferUsedRegs(TmpUsedRegs);
  3492. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3493. { If the flags register is in use, don't change the instruction to an
  3494. ADD otherwise this will scramble the flags. [Kit] }
  3495. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3496. { reg1 may not be used afterwards }
  3497. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3498. begin
  3499. Taicpu(hp1).opcode:=A_ADD;
  3500. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3501. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3502. RemoveCurrentp(p);
  3503. result:=true;
  3504. exit;
  3505. end;
  3506. end;
  3507. { If the LEA instruction can be converted into an arithmetic instruction,
  3508. it may be possible to then fold it in the next optimisation. }
  3509. if ConvertLEA(taicpu(hp1)) then
  3510. Include(OptsToCheck, aoc_ForceNewIteration);
  3511. end;
  3512. {
  3513. mov ref,reg0
  3514. <op> reg0,reg1
  3515. dealloc reg0
  3516. to
  3517. <op> ref,reg1
  3518. }
  3519. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3520. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3521. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3522. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3523. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3524. begin
  3525. TransferUsedRegs(TmpUsedRegs);
  3526. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3527. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3528. begin
  3529. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3530. { loadref increases the reference count, so decrement it again }
  3531. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3532. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3533. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3534. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3535. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3536. { See if we can remove the allocation of reg0 }
  3537. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3538. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3539. RemoveCurrentp(p);
  3540. Result:=true;
  3541. exit;
  3542. end;
  3543. end;
  3544. end;
  3545. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3546. overwrites the original destination register. e.g.
  3547. movl ###,%reg2d
  3548. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3549. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3550. }
  3551. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3552. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3553. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3554. begin
  3555. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3556. begin
  3557. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3558. case taicpu(p).oper[0]^.typ of
  3559. top_const:
  3560. { We have something like:
  3561. movb $x, %regb
  3562. movzbl %regb,%regd
  3563. Change to:
  3564. movl $x, %regd
  3565. }
  3566. begin
  3567. case taicpu(hp1).opsize of
  3568. S_BW:
  3569. begin
  3570. convert_mov_value(A_MOVSX, $FF);
  3571. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3572. taicpu(p).opsize := S_W;
  3573. end;
  3574. S_BL:
  3575. begin
  3576. convert_mov_value(A_MOVSX, $FF);
  3577. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3578. taicpu(p).opsize := S_L;
  3579. end;
  3580. S_WL:
  3581. begin
  3582. convert_mov_value(A_MOVSX, $FFFF);
  3583. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3584. taicpu(p).opsize := S_L;
  3585. end;
  3586. {$ifdef x86_64}
  3587. S_BQ:
  3588. begin
  3589. convert_mov_value(A_MOVSX, $FF);
  3590. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3591. taicpu(p).opsize := S_Q;
  3592. end;
  3593. S_WQ:
  3594. begin
  3595. convert_mov_value(A_MOVSX, $FFFF);
  3596. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3597. taicpu(p).opsize := S_Q;
  3598. end;
  3599. S_LQ:
  3600. begin
  3601. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3602. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3603. taicpu(p).opsize := S_Q;
  3604. end;
  3605. {$endif x86_64}
  3606. else
  3607. { If hp1 was a MOV instruction, it should have been
  3608. optimised already }
  3609. InternalError(2020021001);
  3610. end;
  3611. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3612. RemoveInstruction(hp1);
  3613. Result := True;
  3614. Exit;
  3615. end;
  3616. top_ref:
  3617. begin
  3618. { We have something like:
  3619. movb mem, %regb
  3620. movzbl %regb,%regd
  3621. Change to:
  3622. movzbl mem, %regd
  3623. }
  3624. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3625. begin
  3626. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3627. taicpu(p).opcode := taicpu(hp1).opcode;
  3628. taicpu(p).opsize := taicpu(hp1).opsize;
  3629. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3630. RemoveInstruction(hp1);
  3631. Result := True;
  3632. Exit;
  3633. end;
  3634. end;
  3635. else
  3636. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3637. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3638. Exit;
  3639. end;
  3640. end
  3641. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3642. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3643. optimised }
  3644. else
  3645. begin
  3646. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3647. RemoveCurrentP(p);
  3648. Result := True;
  3649. Exit;
  3650. end;
  3651. end;
  3652. if (taicpu(hp1).opcode = A_MOV) and
  3653. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3654. begin
  3655. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3656. TransferUsedRegs(TmpUsedRegs);
  3657. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3658. { we have
  3659. mov x, %treg
  3660. mov %treg, y
  3661. }
  3662. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3663. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3664. begin
  3665. { we've got
  3666. mov x, %treg
  3667. mov %treg, y
  3668. with %treg is not used after }
  3669. case taicpu(p).oper[0]^.typ Of
  3670. { top_reg is covered by DeepMOVOpt }
  3671. top_const:
  3672. begin
  3673. { change
  3674. mov const, %treg
  3675. mov %treg, y
  3676. to
  3677. mov const, y
  3678. }
  3679. {$ifdef x86_64}
  3680. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3681. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3682. {$endif x86_64}
  3683. begin
  3684. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3685. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3686. RemoveCurrentP(p);
  3687. Result := True;
  3688. Exit;
  3689. end;
  3690. end;
  3691. top_ref:
  3692. case taicpu(hp1).oper[1]^.typ of
  3693. top_reg:
  3694. { change
  3695. mov mem, %treg
  3696. mov %treg, %reg
  3697. to
  3698. mov mem, %reg"
  3699. }
  3700. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3701. begin
  3702. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3703. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3704. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3705. RemoveInstruction(hp1);
  3706. Result := True;
  3707. Exit;
  3708. end
  3709. else if
  3710. { Make sure that if a reference is used, its
  3711. registers are not modified in between }
  3712. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3713. begin
  3714. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3715. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3716. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3717. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3718. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3719. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3720. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3721. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3722. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3723. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3724. RemoveCurrentP(p);
  3725. Result := True;
  3726. Exit;
  3727. end;
  3728. top_ref:
  3729. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3730. begin
  3731. {$ifdef x86_64}
  3732. { Look for the following to simplify:
  3733. mov x(mem1), %reg
  3734. mov %reg, y(mem2)
  3735. mov x+8(mem1), %reg
  3736. mov %reg, y+8(mem2)
  3737. Change to:
  3738. movdqu x(mem1), %xmmreg
  3739. movdqu %xmmreg, y(mem2)
  3740. ...but only as long as the memory blocks don't overlap
  3741. }
  3742. SourceRef := taicpu(p).oper[0]^.ref^;
  3743. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3744. if (taicpu(p).opsize = S_Q) and
  3745. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3746. GetNextInstruction(hp1, hp2) and
  3747. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3748. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3749. begin
  3750. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3751. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3752. Inc(SourceRef.offset, 8);
  3753. if UseAVX then
  3754. begin
  3755. MovAligned := A_VMOVDQA;
  3756. MovUnaligned := A_VMOVDQU;
  3757. end
  3758. else
  3759. begin
  3760. MovAligned := A_MOVDQA;
  3761. MovUnaligned := A_MOVDQU;
  3762. end;
  3763. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3764. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3765. begin
  3766. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3767. Inc(TargetRef.offset, 8);
  3768. if GetNextInstruction(hp2, hp3) and
  3769. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3770. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3771. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3772. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3773. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3774. begin
  3775. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3776. if NewMMReg <> NR_NO then
  3777. begin
  3778. { Remember that the offsets are 8 ahead }
  3779. if ((SourceRef.offset mod 16) = 8) and
  3780. (
  3781. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3782. (SourceRef.base = current_procinfo.framepointer) or
  3783. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3784. ) then
  3785. taicpu(p).opcode := MovAligned
  3786. else
  3787. taicpu(p).opcode := MovUnaligned;
  3788. taicpu(p).opsize := S_XMM;
  3789. taicpu(p).oper[1]^.reg := NewMMReg;
  3790. if ((TargetRef.offset mod 16) = 8) and
  3791. (
  3792. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3793. (TargetRef.base = current_procinfo.framepointer) or
  3794. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3795. ) then
  3796. taicpu(hp1).opcode := MovAligned
  3797. else
  3798. taicpu(hp1).opcode := MovUnaligned;
  3799. taicpu(hp1).opsize := S_XMM;
  3800. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3801. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3802. RemoveInstruction(hp2);
  3803. RemoveInstruction(hp3);
  3804. Result := True;
  3805. Exit;
  3806. end;
  3807. end;
  3808. end
  3809. else
  3810. begin
  3811. { See if the next references are 8 less rather than 8 greater }
  3812. Dec(SourceRef.offset, 16); { -8 the other way }
  3813. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3814. begin
  3815. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3816. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3817. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3818. GetNextInstruction(hp2, hp3) and
  3819. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3820. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3821. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3822. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3823. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3824. begin
  3825. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3826. if NewMMReg <> NR_NO then
  3827. begin
  3828. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3829. if ((SourceRef.offset mod 16) = 0) and
  3830. (
  3831. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3832. (SourceRef.base = current_procinfo.framepointer) or
  3833. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3834. ) then
  3835. taicpu(hp2).opcode := MovAligned
  3836. else
  3837. taicpu(hp2).opcode := MovUnaligned;
  3838. taicpu(hp2).opsize := S_XMM;
  3839. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3840. if ((TargetRef.offset mod 16) = 0) and
  3841. (
  3842. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3843. (TargetRef.base = current_procinfo.framepointer) or
  3844. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3845. ) then
  3846. taicpu(hp3).opcode := MovAligned
  3847. else
  3848. taicpu(hp3).opcode := MovUnaligned;
  3849. taicpu(hp3).opsize := S_XMM;
  3850. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3851. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3852. RemoveInstruction(hp1);
  3853. RemoveCurrentP(p);
  3854. Result := True;
  3855. Exit;
  3856. end;
  3857. end;
  3858. end;
  3859. end;
  3860. end;
  3861. {$endif x86_64}
  3862. end;
  3863. else
  3864. { The write target should be a reg or a ref }
  3865. InternalError(2021091601);
  3866. end;
  3867. else
  3868. ;
  3869. end;
  3870. end
  3871. else if (taicpu(p).oper[0]^.typ = top_const) and
  3872. { %treg is used afterwards, but all eventualities other
  3873. than the first MOV instruction being a constant are
  3874. covered by DeepMOVOpt, so only check for that }
  3875. (
  3876. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3877. not (cs_opt_size in current_settings.optimizerswitches) or
  3878. (taicpu(hp1).opsize = S_B)
  3879. ) and
  3880. (
  3881. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3882. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3883. ) then
  3884. begin
  3885. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3886. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3887. Include(OptsToCheck, aoc_ForceNewIteration);
  3888. end;
  3889. end;
  3890. end;
  3891. end;
  3892. if taicpu(p).oper[0]^.typ = top_reg then
  3893. begin
  3894. { oper[1] is a reference }
  3895. { Saves on a large number of dereferences }
  3896. p_SourceReg := taicpu(p).oper[0]^.reg;
  3897. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3898. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3899. else
  3900. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3901. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3902. begin
  3903. if taicpu(p).oper[1]^.typ = top_reg then
  3904. begin
  3905. p_TargetReg := taicpu(p).oper[1]^.reg;
  3906. { Change:
  3907. movl %reg1,%reg2
  3908. ...
  3909. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3910. ...
  3911. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3912. To:
  3913. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3914. ...
  3915. movl x(%reg1),%reg1
  3916. ...
  3917. movl %reg1,%regX
  3918. }
  3919. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3920. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3921. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3922. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3923. not RegModifiedBetween(p_TargetReg, p, hp1) and
  3924. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  3925. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3926. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3927. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  3928. begin
  3929. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3930. if RegInRef(p_TargetReg, SourceRef) and
  3931. { If %reg1 also appears in the second reference, then it will
  3932. not refer to the same memory block as the first reference }
  3933. not RegInRef(p_SourceReg, SourceRef) then
  3934. begin
  3935. { Check to see if the references match if %reg2 is changed to %reg1 }
  3936. if SourceRef.base = p_TargetReg then
  3937. SourceRef.base := p_SourceReg;
  3938. if SourceRef.index = p_TargetReg then
  3939. SourceRef.index := p_SourceReg;
  3940. { RefsEqual also checks to ensure both references are non-volatile }
  3941. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3942. begin
  3943. taicpu(hp2).loadreg(0, p_SourceReg);
  3944. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3945. Result := True;
  3946. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3947. begin
  3948. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3949. RemoveCurrentP(p);
  3950. Exit;
  3951. end
  3952. else
  3953. begin
  3954. { Check to see if %reg2 is no longer in use }
  3955. TransferUsedRegs(TmpUsedRegs);
  3956. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3957. UpdateUsedRegsBetween(TmpUsedRegs, tai(hp1.Next), hp2);
  3958. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3959. begin
  3960. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3961. RemoveCurrentP(p);
  3962. Exit;
  3963. end;
  3964. end;
  3965. { If we reach this point, p and hp1 weren't actually modified,
  3966. so we can do a bit more work on this pass }
  3967. end;
  3968. end;
  3969. end;
  3970. end;
  3971. end;
  3972. end;
  3973. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3974. { All the next optimisations require a next instruction }
  3975. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3976. Exit;
  3977. { Next instruction is also a MOV ? }
  3978. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3979. begin
  3980. if MatchOpType(taicpu(p), top_const, top_ref) and
  3981. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3982. TryConstMerge(p, hp1) then
  3983. begin
  3984. Result := True;
  3985. { In case we have four byte writes in a row, check for 2 more
  3986. right now so we don't have to wait for another iteration of
  3987. pass 1
  3988. }
  3989. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3990. case taicpu(p).opsize of
  3991. S_W:
  3992. begin
  3993. if GetNextInstruction(p, hp1) and
  3994. MatchInstruction(hp1, A_MOV, [S_B]) and
  3995. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3996. GetNextInstruction(hp1, hp2) and
  3997. MatchInstruction(hp2, A_MOV, [S_B]) and
  3998. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3999. { Try to merge the two bytes }
  4000. TryConstMerge(hp1, hp2) then
  4001. { Now try to merge the two words (hp2 will get deleted) }
  4002. TryConstMerge(p, hp1);
  4003. end;
  4004. S_L:
  4005. begin
  4006. { Though this only really benefits x86_64 and not i386, it
  4007. gets a potential optimisation done faster and hence
  4008. reduces the number of times OptPass1MOV is entered }
  4009. if GetNextInstruction(p, hp1) and
  4010. MatchInstruction(hp1, A_MOV, [S_W]) and
  4011. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4012. GetNextInstruction(hp1, hp2) and
  4013. MatchInstruction(hp2, A_MOV, [S_W]) and
  4014. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4015. { Try to merge the two words }
  4016. TryConstMerge(hp1, hp2) then
  4017. { This will always fail on i386, so don't bother
  4018. calling it unless we're doing x86_64 }
  4019. {$ifdef x86_64}
  4020. { Now try to merge the two longwords (hp2 will get deleted) }
  4021. TryConstMerge(p, hp1)
  4022. {$endif x86_64}
  4023. ;
  4024. end;
  4025. else
  4026. ;
  4027. end;
  4028. Exit;
  4029. end;
  4030. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4031. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4032. { mov reg1, mem1 or mov mem1, reg1
  4033. mov mem2, reg2 mov reg2, mem2}
  4034. begin
  4035. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4036. { mov reg1, mem1 or mov mem1, reg1
  4037. mov mem2, reg1 mov reg2, mem1}
  4038. begin
  4039. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4040. { Removes the second statement from
  4041. mov reg1, mem1/reg2
  4042. mov mem1/reg2, reg1 }
  4043. begin
  4044. if taicpu(p).oper[0]^.typ=top_reg then
  4045. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4046. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4047. RemoveInstruction(hp1);
  4048. Result:=true;
  4049. exit;
  4050. end
  4051. else
  4052. begin
  4053. TransferUsedRegs(TmpUsedRegs);
  4054. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4055. if (taicpu(p).oper[1]^.typ = top_ref) and
  4056. { mov reg1, mem1
  4057. mov mem2, reg1 }
  4058. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4059. GetNextInstruction(hp1, hp2) and
  4060. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4061. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4062. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4063. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4064. { change to
  4065. mov reg1, mem1 mov reg1, mem1
  4066. mov mem2, reg1 cmp reg1, mem2
  4067. cmp mem1, reg1
  4068. }
  4069. begin
  4070. RemoveInstruction(hp2);
  4071. taicpu(hp1).opcode := A_CMP;
  4072. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4073. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4074. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4075. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4076. end;
  4077. end;
  4078. end
  4079. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4080. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4081. begin
  4082. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4083. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4084. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4085. end
  4086. else
  4087. begin
  4088. TransferUsedRegs(TmpUsedRegs);
  4089. if GetNextInstruction(hp1, hp2) and
  4090. MatchOpType(taicpu(p),top_ref,top_reg) and
  4091. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4092. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4093. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4094. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4095. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4096. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4097. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4098. { mov mem1, %reg1
  4099. mov %reg1, mem2
  4100. mov mem2, reg2
  4101. to:
  4102. mov mem1, reg2
  4103. mov reg2, mem2}
  4104. begin
  4105. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4106. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4107. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4108. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4109. RemoveInstruction(hp2);
  4110. Result := True;
  4111. end
  4112. {$ifdef i386}
  4113. { this is enabled for i386 only, as the rules to create the reg sets below
  4114. are too complicated for x86-64, so this makes this code too error prone
  4115. on x86-64
  4116. }
  4117. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4118. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4119. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4120. { mov mem1, reg1 mov mem1, reg1
  4121. mov reg1, mem2 mov reg1, mem2
  4122. mov mem2, reg2 mov mem2, reg1
  4123. to: to:
  4124. mov mem1, reg1 mov mem1, reg1
  4125. mov mem1, reg2 mov reg1, mem2
  4126. mov reg1, mem2
  4127. or (if mem1 depends on reg1
  4128. and/or if mem2 depends on reg2)
  4129. to:
  4130. mov mem1, reg1
  4131. mov reg1, mem2
  4132. mov reg1, reg2
  4133. }
  4134. begin
  4135. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4136. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4137. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4138. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4139. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4140. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4141. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4142. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4143. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4144. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4145. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4146. end
  4147. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4148. begin
  4149. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4150. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4151. end
  4152. else
  4153. begin
  4154. RemoveInstruction(hp2);
  4155. end
  4156. {$endif i386}
  4157. ;
  4158. end;
  4159. end
  4160. { movl [mem1],reg1
  4161. movl [mem1],reg2
  4162. to
  4163. movl [mem1],reg1
  4164. movl reg1,reg2
  4165. }
  4166. else if not CheckMovMov2MovMov2(p, hp1) and
  4167. { movl const1,[mem1]
  4168. movl [mem1],reg1
  4169. to
  4170. movl const1,reg1
  4171. movl reg1,[mem1]
  4172. }
  4173. MatchOpType(Taicpu(p),top_const,top_ref) and
  4174. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4175. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4176. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4177. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4178. begin
  4179. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4180. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4181. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4182. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4183. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4184. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4185. Result:=true;
  4186. exit;
  4187. end;
  4188. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4189. end;
  4190. { search further than the next instruction for a mov (as long as it's not a jump) }
  4191. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4192. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4193. (taicpu(p).oper[1]^.typ = top_reg) and
  4194. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4195. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4196. begin
  4197. { we work with hp2 here, so hp1 can be still used later on when
  4198. checking for GetNextInstruction_p }
  4199. hp3 := hp1;
  4200. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4201. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4202. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4203. TransferUsedRegs(TmpUsedRegs);
  4204. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4205. if NotFirstIteration then
  4206. JumpTracking := TLinkedList.Create
  4207. else
  4208. JumpTracking := nil;
  4209. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4210. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4211. (hp2.typ=ait_instruction) do
  4212. begin
  4213. case taicpu(hp2).opcode of
  4214. A_POP:
  4215. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4216. begin
  4217. if not CrossJump and
  4218. not RegUsedBetween(p_TargetReg, p, hp2) then
  4219. begin
  4220. { We can remove the original MOV since the register
  4221. wasn't used between it and its popping from the stack }
  4222. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4223. RemoveCurrentp(p, hp1);
  4224. Result := True;
  4225. JumpTracking.Free;
  4226. Exit;
  4227. end;
  4228. { Can't go any further }
  4229. Break;
  4230. end;
  4231. A_MOV:
  4232. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4233. ((taicpu(p).oper[0]^.typ=top_const) or
  4234. ((taicpu(p).oper[0]^.typ=top_reg) and
  4235. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4236. )
  4237. ) then
  4238. begin
  4239. { we have
  4240. mov x, %treg
  4241. mov %treg, y
  4242. }
  4243. { We don't need to call UpdateUsedRegs for every instruction between
  4244. p and hp2 because the register we're concerned about will not
  4245. become deallocated (otherwise GetNextInstructionUsingReg would
  4246. have stopped at an earlier instruction). [Kit] }
  4247. TempRegUsed :=
  4248. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4249. RegReadByInstruction(p_TargetReg, hp3) or
  4250. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4251. case taicpu(p).oper[0]^.typ Of
  4252. top_reg:
  4253. begin
  4254. { change
  4255. mov %reg, %treg
  4256. mov %treg, y
  4257. to
  4258. mov %reg, y
  4259. }
  4260. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4261. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4262. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4263. begin
  4264. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4265. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4266. if TempRegUsed then
  4267. begin
  4268. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4269. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4270. { Set the start of the next GetNextInstructionUsingRegCond search
  4271. to start at the entry right before hp2 (which is about to be removed) }
  4272. hp3 := tai(hp2.Previous);
  4273. RemoveInstruction(hp2);
  4274. Include(OptsToCheck, aoc_ForceNewIteration);
  4275. { See if there's more we can optimise }
  4276. Continue;
  4277. end
  4278. else
  4279. begin
  4280. RemoveInstruction(hp2);
  4281. { We can remove the original MOV too }
  4282. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4283. RemoveCurrentP(p, hp1);
  4284. Result:=true;
  4285. JumpTracking.Free;
  4286. Exit;
  4287. end;
  4288. end
  4289. else
  4290. begin
  4291. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4292. taicpu(hp2).loadReg(0, p_SourceReg);
  4293. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4294. { Check to see if the register also appears in the reference }
  4295. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4296. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4297. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4298. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4299. begin
  4300. { Don't remove the first instruction if the temporary register is in use }
  4301. if not TempRegUsed then
  4302. begin
  4303. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4304. RemoveCurrentP(p, hp1);
  4305. Result:=true;
  4306. JumpTracking.Free;
  4307. Exit;
  4308. end;
  4309. { No need to set Result to True here. If there's another instruction later
  4310. on that can be optimised, it will be detected when the main Pass 1 loop
  4311. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4312. hp3 := hp2;
  4313. Continue;
  4314. end;
  4315. end;
  4316. end;
  4317. top_const:
  4318. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4319. begin
  4320. { change
  4321. mov const, %treg
  4322. mov %treg, y
  4323. to
  4324. mov const, y
  4325. }
  4326. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4327. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4328. begin
  4329. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4330. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4331. if TempRegUsed then
  4332. begin
  4333. { Don't remove the first instruction if the temporary register is in use }
  4334. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4335. { No need to set Result to True. If there's another instruction later on
  4336. that can be optimised, it will be detected when the main Pass 1 loop
  4337. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4338. end
  4339. else
  4340. begin
  4341. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4342. RemoveCurrentP(p, hp1);
  4343. Result:=true;
  4344. Exit;
  4345. end;
  4346. end;
  4347. end;
  4348. else
  4349. Internalerror(2019103001);
  4350. end;
  4351. end
  4352. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4353. begin
  4354. if not CrossJump and
  4355. not RegUsedBetween(p_TargetReg, p, hp2) and
  4356. not RegReadByInstruction(p_TargetReg, hp2) then
  4357. begin
  4358. { Register is not used before it is overwritten }
  4359. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4360. RemoveCurrentp(p, hp1);
  4361. Result := True;
  4362. Exit;
  4363. end;
  4364. if (taicpu(p).oper[0]^.typ = top_const) and
  4365. (taicpu(hp2).oper[0]^.typ = top_const) then
  4366. begin
  4367. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4368. begin
  4369. { Same value - register hasn't changed }
  4370. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4371. RemoveInstruction(hp2);
  4372. Include(OptsToCheck, aoc_ForceNewIteration);
  4373. { See if there's more we can optimise }
  4374. Continue;
  4375. end;
  4376. end;
  4377. {$ifdef x86_64}
  4378. end
  4379. { Change:
  4380. movl %reg1l,%reg2l
  4381. ...
  4382. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4383. To:
  4384. movl %reg1l,%reg2l
  4385. ...
  4386. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4387. If %reg1 = %reg3, convert to:
  4388. movl %reg1l,%reg2l
  4389. ...
  4390. andl %reg1l,%reg1l
  4391. }
  4392. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4393. (taicpu(p).oper[0]^.typ = top_reg) and
  4394. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4395. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4396. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4397. begin
  4398. TempRegUsed :=
  4399. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4400. RegReadByInstruction(p_TargetReg, hp3) or
  4401. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4402. taicpu(hp2).opsize := S_L;
  4403. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4404. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4405. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4406. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4407. begin
  4408. { %reg1 = %reg3 }
  4409. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4410. taicpu(hp2).opcode := A_AND;
  4411. end
  4412. else
  4413. begin
  4414. { %reg1 <> %reg3 }
  4415. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4416. end;
  4417. if not TempRegUsed then
  4418. begin
  4419. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4420. RemoveCurrentP(p, hp1);
  4421. Result := True;
  4422. Exit;
  4423. end
  4424. else
  4425. begin
  4426. { Initial instruction wasn't actually changed }
  4427. Include(OptsToCheck, aoc_ForceNewIteration);
  4428. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4429. appears below since %reg1 has technically changed }
  4430. if taicpu(hp2).opcode = A_AND then
  4431. Break;
  4432. end;
  4433. {$endif x86_64}
  4434. end
  4435. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4436. GetNextInstruction(hp2, hp4) and
  4437. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4438. { Optimise the following first:
  4439. movl [mem1],reg1
  4440. movl [mem1],reg2
  4441. to
  4442. movl [mem1],reg1
  4443. movl reg1,reg2
  4444. If [mem1] contains the target register and reg1 is the
  4445. the source register, this optimisation will get missed
  4446. and produce less efficient code later on.
  4447. }
  4448. if CheckMovMov2MovMov2(hp2, hp4) then
  4449. { Initial instruction wasn't actually changed }
  4450. Include(OptsToCheck, aoc_ForceNewIteration);
  4451. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4452. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4453. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4454. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4455. begin
  4456. {
  4457. Change from:
  4458. mov ###, %reg
  4459. ...
  4460. movs/z %reg,%reg (Same register, just different sizes)
  4461. To:
  4462. movs/z ###, %reg (Longer version)
  4463. ...
  4464. (remove)
  4465. }
  4466. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4467. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4468. { Keep the first instruction as mov if ### is a constant }
  4469. if taicpu(p).oper[0]^.typ = top_const then
  4470. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4471. else
  4472. begin
  4473. taicpu(p).opcode := taicpu(hp2).opcode;
  4474. taicpu(p).opsize := taicpu(hp2).opsize;
  4475. end;
  4476. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4477. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4478. RemoveInstruction(hp2);
  4479. Result := True;
  4480. JumpTracking.Free;
  4481. Exit;
  4482. end;
  4483. else
  4484. { Move down to the if-block below };
  4485. end;
  4486. { Also catches MOV/S/Z instructions that aren't modified }
  4487. if taicpu(p).oper[0]^.typ = top_reg then
  4488. begin
  4489. p_SourceReg := taicpu(p).oper[0]^.reg;
  4490. if
  4491. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4492. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4493. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4494. begin
  4495. Result := True;
  4496. { Just in case something didn't get modified (e.g. an
  4497. implicit register). Also, if it does read from this
  4498. register, then there's no longer an advantage to
  4499. changing the register on subsequent instructions.}
  4500. if not RegReadByInstruction(p_TargetReg, hp2) then
  4501. begin
  4502. { If a conditional jump was crossed, do not delete
  4503. the original MOV no matter what }
  4504. if not CrossJump and
  4505. { RegEndOfLife returns True if the register is
  4506. deallocated before the next instruction or has
  4507. been loaded with a new value }
  4508. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4509. begin
  4510. { We can remove the original MOV }
  4511. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4512. RemoveCurrentp(p, hp1);
  4513. JumpTracking.Free;
  4514. Result := True;
  4515. Exit;
  4516. end;
  4517. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4518. begin
  4519. { See if there's more we can optimise }
  4520. hp3 := hp2;
  4521. Continue;
  4522. end;
  4523. end;
  4524. end;
  4525. end;
  4526. { Break out of the while loop under normal circumstances }
  4527. Break;
  4528. end;
  4529. JumpTracking.Free;
  4530. end;
  4531. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4532. (taicpu(p).oper[1]^.typ = top_reg) and
  4533. (taicpu(p).opsize = S_L) and
  4534. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4535. (hp2.typ = ait_instruction) and
  4536. (taicpu(hp2).opcode = A_AND) and
  4537. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4538. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4539. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4540. ) then
  4541. begin
  4542. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4543. begin
  4544. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4545. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4546. begin
  4547. { Optimize out:
  4548. mov x, %reg
  4549. and ffffffffh, %reg
  4550. }
  4551. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4552. RemoveInstruction(hp2);
  4553. Result:=true;
  4554. exit;
  4555. end;
  4556. end;
  4557. end;
  4558. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4559. x >= RetOffset) as it doesn't do anything (it writes either to a
  4560. parameter or to the temporary storage room for the function
  4561. result)
  4562. }
  4563. if IsExitCode(hp1) and
  4564. (taicpu(p).oper[1]^.typ = top_ref) and
  4565. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4566. (
  4567. (
  4568. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4569. not (
  4570. assigned(current_procinfo.procdef.funcretsym) and
  4571. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4572. )
  4573. ) or
  4574. { Also discard writes to the stack that are below the base pointer,
  4575. as this is temporary storage rather than a function result on the
  4576. stack, say. }
  4577. (
  4578. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4579. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4580. )
  4581. ) then
  4582. begin
  4583. RemoveCurrentp(p, hp1);
  4584. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4585. RemoveLastDeallocForFuncRes(p);
  4586. Result:=true;
  4587. exit;
  4588. end;
  4589. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4590. begin
  4591. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4592. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4593. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4594. begin
  4595. { change
  4596. mov reg1, mem1
  4597. test/cmp x, mem1
  4598. to
  4599. mov reg1, mem1
  4600. test/cmp x, reg1
  4601. }
  4602. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4603. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4604. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4605. Result := True;
  4606. Exit;
  4607. end;
  4608. if DoMovCmpMemOpt(p, hp1) then
  4609. begin
  4610. Result := True;
  4611. Exit;
  4612. end;
  4613. end;
  4614. if (taicpu(p).oper[1]^.typ = top_reg) and
  4615. (hp1.typ = ait_instruction) and
  4616. GetNextInstruction(hp1, hp2) and
  4617. MatchInstruction(hp2,A_MOV,[]) and
  4618. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4619. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4620. (
  4621. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4622. {$ifdef x86_64}
  4623. or
  4624. (
  4625. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4626. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4627. )
  4628. {$endif x86_64}
  4629. ) then
  4630. begin
  4631. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4632. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4633. { change movsX/movzX reg/ref, reg2
  4634. add/sub/or/... reg3/$const, reg2
  4635. mov reg2 reg/ref
  4636. dealloc reg2
  4637. to
  4638. add/sub/or/... reg3/$const, reg/ref }
  4639. begin
  4640. TransferUsedRegs(TmpUsedRegs);
  4641. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4642. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4643. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4644. begin
  4645. { by example:
  4646. movswl %si,%eax movswl %si,%eax p
  4647. decl %eax addl %edx,%eax hp1
  4648. movw %ax,%si movw %ax,%si hp2
  4649. ->
  4650. movswl %si,%eax movswl %si,%eax p
  4651. decw %eax addw %edx,%eax hp1
  4652. movw %ax,%si movw %ax,%si hp2
  4653. }
  4654. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4655. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4656. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4657. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4658. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4659. {
  4660. ->
  4661. movswl %si,%eax movswl %si,%eax p
  4662. decw %si addw %dx,%si hp1
  4663. movw %ax,%si movw %ax,%si hp2
  4664. }
  4665. case taicpu(hp1).ops of
  4666. 1:
  4667. begin
  4668. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4669. if taicpu(hp1).oper[0]^.typ=top_reg then
  4670. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4671. end;
  4672. 2:
  4673. begin
  4674. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4675. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4676. (taicpu(hp1).opcode<>A_SHL) and
  4677. (taicpu(hp1).opcode<>A_SHR) and
  4678. (taicpu(hp1).opcode<>A_SAR) then
  4679. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4680. end;
  4681. else
  4682. internalerror(2008042701);
  4683. end;
  4684. {
  4685. ->
  4686. decw %si addw %dx,%si p
  4687. }
  4688. RemoveInstruction(hp2);
  4689. RemoveCurrentP(p, hp1);
  4690. Result:=True;
  4691. Exit;
  4692. end;
  4693. end;
  4694. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4695. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4696. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4697. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4698. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4699. )
  4700. {$ifdef i386}
  4701. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4702. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4703. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4704. {$endif i386}
  4705. then
  4706. { change movsX/movzX reg/ref, reg2
  4707. add/sub/or/... regX/$const, reg2
  4708. mov reg2, reg3
  4709. dealloc reg2
  4710. to
  4711. movsX/movzX reg/ref, reg3
  4712. add/sub/or/... reg3/$const, reg3
  4713. }
  4714. begin
  4715. TransferUsedRegs(TmpUsedRegs);
  4716. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4717. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4718. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4719. begin
  4720. { by example:
  4721. movswl %si,%eax movswl %si,%eax p
  4722. decl %eax addl %edx,%eax hp1
  4723. movw %ax,%si movw %ax,%si hp2
  4724. ->
  4725. movswl %si,%eax movswl %si,%eax p
  4726. decw %eax addw %edx,%eax hp1
  4727. movw %ax,%si movw %ax,%si hp2
  4728. }
  4729. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4730. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4731. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4732. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4733. { limit size of constants as well to avoid assembler errors, but
  4734. check opsize to avoid overflow when left shifting the 1 }
  4735. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4736. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4737. {$ifdef x86_64}
  4738. { Be careful of, for example:
  4739. movl %reg1,%reg2
  4740. addl %reg3,%reg2
  4741. movq %reg2,%reg4
  4742. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4743. }
  4744. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4745. begin
  4746. taicpu(hp2).changeopsize(S_L);
  4747. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4748. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4749. end;
  4750. {$endif x86_64}
  4751. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4752. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4753. if taicpu(p).oper[0]^.typ=top_reg then
  4754. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4755. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4756. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4757. {
  4758. ->
  4759. movswl %si,%eax movswl %si,%eax p
  4760. decw %si addw %dx,%si hp1
  4761. movw %ax,%si movw %ax,%si hp2
  4762. }
  4763. case taicpu(hp1).ops of
  4764. 1:
  4765. begin
  4766. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4767. if taicpu(hp1).oper[0]^.typ=top_reg then
  4768. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4769. end;
  4770. 2:
  4771. begin
  4772. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4773. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4774. (taicpu(hp1).opcode<>A_SHL) and
  4775. (taicpu(hp1).opcode<>A_SHR) and
  4776. (taicpu(hp1).opcode<>A_SAR) then
  4777. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4778. end;
  4779. else
  4780. internalerror(2018111801);
  4781. end;
  4782. {
  4783. ->
  4784. decw %si addw %dx,%si p
  4785. }
  4786. RemoveInstruction(hp2);
  4787. end;
  4788. end;
  4789. end;
  4790. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4791. GetNextInstruction(hp1, hp2) and
  4792. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4793. MatchOperand(Taicpu(p).oper[0]^,0) and
  4794. (Taicpu(p).oper[1]^.typ = top_reg) and
  4795. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4796. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4797. { mov reg1,0
  4798. bts reg1,operand1 --> mov reg1,operand2
  4799. or reg1,operand2 bts reg1,operand1}
  4800. begin
  4801. Taicpu(hp2).opcode:=A_MOV;
  4802. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4803. asml.remove(hp1);
  4804. insertllitem(hp2,hp2.next,hp1);
  4805. RemoveCurrentp(p, hp1);
  4806. Result:=true;
  4807. exit;
  4808. end;
  4809. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4810. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4811. GetNextInstruction(hp1, hp2) and
  4812. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4813. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4814. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4815. { change
  4816. mov reg1,reg2
  4817. sub reg3,reg2
  4818. cmp reg3,reg1
  4819. into
  4820. mov reg1,reg2
  4821. sub reg3,reg2
  4822. }
  4823. begin
  4824. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4825. RemoveInstruction(hp2);
  4826. Result:=true;
  4827. exit;
  4828. end;
  4829. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4830. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4831. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4832. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4833. begin
  4834. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4835. {$ifdef x86_64}
  4836. { Convert:
  4837. movq x(ref),%reg64
  4838. shrq y,%reg64
  4839. To:
  4840. movl x+4(ref),%reg32
  4841. shrl y-32,%reg32 (Remove if y = 32)
  4842. }
  4843. if (taicpu(p).opsize = S_Q) and
  4844. (taicpu(hp1).opcode = A_SHR) and
  4845. (taicpu(hp1).oper[0]^.val >= 32) then
  4846. begin
  4847. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4848. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4849. { Convert to 32-bit }
  4850. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4851. taicpu(p).opsize := S_L;
  4852. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4853. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4854. if (taicpu(hp1).oper[0]^.val = 32) then
  4855. begin
  4856. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4857. RemoveInstruction(hp1);
  4858. end
  4859. else
  4860. begin
  4861. { This will potentially open up more arithmetic operations since
  4862. the peephole optimizer now has a big hint that only the lower
  4863. 32 bits are currently in use (and opcodes are smaller in size) }
  4864. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4865. taicpu(hp1).opsize := S_L;
  4866. Dec(taicpu(hp1).oper[0]^.val, 32);
  4867. DebugMsg(SPeepholeOptimization + PreMessage +
  4868. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4869. end;
  4870. Result := True;
  4871. Exit;
  4872. end;
  4873. {$endif x86_64}
  4874. { Convert:
  4875. movl x(ref),%reg
  4876. shrl $24,%reg
  4877. To:
  4878. movzbl x+3(ref),%reg
  4879. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4880. Also accept sar instead of shr, but convert to movsx instead of movzx
  4881. }
  4882. if taicpu(hp1).opcode = A_SHR then
  4883. MovUnaligned := A_MOVZX
  4884. else
  4885. MovUnaligned := A_MOVSX;
  4886. NewSize := S_NO;
  4887. NewOffset := 0;
  4888. case taicpu(p).opsize of
  4889. S_B:
  4890. { No valid combinations };
  4891. S_W:
  4892. if (taicpu(hp1).oper[0]^.val = 8) then
  4893. begin
  4894. NewSize := S_BW;
  4895. NewOffset := 1;
  4896. end;
  4897. S_L:
  4898. case taicpu(hp1).oper[0]^.val of
  4899. 16:
  4900. begin
  4901. NewSize := S_WL;
  4902. NewOffset := 2;
  4903. end;
  4904. 24:
  4905. begin
  4906. NewSize := S_BL;
  4907. NewOffset := 3;
  4908. end;
  4909. else
  4910. ;
  4911. end;
  4912. {$ifdef x86_64}
  4913. S_Q:
  4914. case taicpu(hp1).oper[0]^.val of
  4915. 32:
  4916. begin
  4917. if taicpu(hp1).opcode = A_SAR then
  4918. begin
  4919. { 32-bit to 64-bit is a distinct instruction }
  4920. MovUnaligned := A_MOVSXD;
  4921. NewSize := S_LQ;
  4922. NewOffset := 4;
  4923. end
  4924. else
  4925. { Should have been handled by MovShr2Mov above }
  4926. InternalError(2022081811);
  4927. end;
  4928. 48:
  4929. begin
  4930. NewSize := S_WQ;
  4931. NewOffset := 6;
  4932. end;
  4933. 56:
  4934. begin
  4935. NewSize := S_BQ;
  4936. NewOffset := 7;
  4937. end;
  4938. else
  4939. ;
  4940. end;
  4941. {$endif x86_64}
  4942. else
  4943. InternalError(2022081810);
  4944. end;
  4945. if (NewSize <> S_NO) and
  4946. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4947. begin
  4948. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4949. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4950. debug_op2str(MovUnaligned);
  4951. {$ifdef x86_64}
  4952. if MovUnaligned <> A_MOVSXD then
  4953. { Don't add size suffix for MOVSXD }
  4954. {$endif x86_64}
  4955. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4956. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4957. taicpu(p).opcode := MovUnaligned;
  4958. taicpu(p).opsize := NewSize;
  4959. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4960. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4961. RemoveInstruction(hp1);
  4962. Result := True;
  4963. Exit;
  4964. end;
  4965. end;
  4966. { Backward optimisation shared with OptPass2MOV }
  4967. if FuncMov2Func(p, hp1) then
  4968. begin
  4969. Result := True;
  4970. Exit;
  4971. end;
  4972. end;
  4973. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4974. var
  4975. hp1 : tai;
  4976. begin
  4977. Result:=false;
  4978. if taicpu(p).ops <> 2 then
  4979. exit;
  4980. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4981. GetNextInstruction(p,hp1) then
  4982. begin
  4983. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4984. (taicpu(hp1).ops = 2) then
  4985. begin
  4986. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4987. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4988. { movXX reg1, mem1 or movXX mem1, reg1
  4989. movXX mem2, reg2 movXX reg2, mem2}
  4990. begin
  4991. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4992. { movXX reg1, mem1 or movXX mem1, reg1
  4993. movXX mem2, reg1 movXX reg2, mem1}
  4994. begin
  4995. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4996. begin
  4997. { Removes the second statement from
  4998. movXX reg1, mem1/reg2
  4999. movXX mem1/reg2, reg1
  5000. }
  5001. if taicpu(p).oper[0]^.typ=top_reg then
  5002. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5003. { Removes the second statement from
  5004. movXX mem1/reg1, reg2
  5005. movXX reg2, mem1/reg1
  5006. }
  5007. if (taicpu(p).oper[1]^.typ=top_reg) and
  5008. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5009. begin
  5010. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5011. RemoveInstruction(hp1);
  5012. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5013. Result:=true;
  5014. exit;
  5015. end
  5016. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5017. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5018. begin
  5019. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5020. RemoveInstruction(hp1);
  5021. Result:=true;
  5022. exit;
  5023. end;
  5024. end
  5025. end;
  5026. end;
  5027. end;
  5028. end;
  5029. end;
  5030. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5031. var
  5032. hp1 : tai;
  5033. begin
  5034. result:=false;
  5035. { replace
  5036. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5037. MovX %mreg2,%mreg1
  5038. dealloc %mreg2
  5039. by
  5040. <Op>X %mreg2,%mreg1
  5041. ?
  5042. }
  5043. if GetNextInstruction(p,hp1) and
  5044. { we mix single and double opperations here because we assume that the compiler
  5045. generates vmovapd only after double operations and vmovaps only after single operations }
  5046. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5047. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5048. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5049. (taicpu(p).oper[0]^.typ=top_reg) then
  5050. begin
  5051. TransferUsedRegs(TmpUsedRegs);
  5052. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5053. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5054. begin
  5055. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5056. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5057. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5058. RemoveInstruction(hp1);
  5059. result:=true;
  5060. end;
  5061. end;
  5062. end;
  5063. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5064. var
  5065. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5066. JumpLabel, JumpLabel_dist: TAsmLabel;
  5067. FirstValue, SecondValue: TCGInt;
  5068. function OptimizeJump(var InputP: tai): Boolean;
  5069. var
  5070. TempBool: Boolean;
  5071. begin
  5072. Result := False;
  5073. TempBool := True;
  5074. if DoJumpOptimizations(InputP, TempBool) or
  5075. not TempBool then
  5076. begin
  5077. Result := True;
  5078. if Assigned(InputP) then
  5079. begin
  5080. { CollapseZeroDistJump will be set to the label or an align
  5081. before it after the jump if it optimises, whether or not
  5082. the label is live or dead }
  5083. if (InputP.typ = ait_align) or
  5084. (
  5085. (InputP.typ = ait_label) and
  5086. not (tai_label(InputP).labsym.is_used)
  5087. ) then
  5088. GetNextInstruction(InputP, InputP);
  5089. end;
  5090. Exit;
  5091. end;
  5092. end;
  5093. begin
  5094. Result := False;
  5095. if (taicpu(p).oper[0]^.typ = top_const) and
  5096. (taicpu(p).oper[0]^.val <> -1) then
  5097. begin
  5098. { Convert unsigned maximum constants to -1 to aid optimisation }
  5099. case taicpu(p).opsize of
  5100. S_B:
  5101. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5102. begin
  5103. taicpu(p).oper[0]^.val := -1;
  5104. Result := True;
  5105. Exit;
  5106. end;
  5107. S_W:
  5108. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5109. begin
  5110. taicpu(p).oper[0]^.val := -1;
  5111. Result := True;
  5112. Exit;
  5113. end;
  5114. S_L:
  5115. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5116. begin
  5117. taicpu(p).oper[0]^.val := -1;
  5118. Result := True;
  5119. Exit;
  5120. end;
  5121. {$ifdef x86_64}
  5122. S_Q:
  5123. { Storing anything greater than $7FFFFFFF is not possible so do
  5124. nothing };
  5125. {$endif x86_64}
  5126. else
  5127. InternalError(2021121001);
  5128. end;
  5129. end;
  5130. if GetNextInstruction(p, hp1) and
  5131. TrySwapMovCmp(p, hp1) then
  5132. begin
  5133. Result := True;
  5134. Exit;
  5135. end;
  5136. p_label := nil;
  5137. JumpLabel := nil;
  5138. if MatchInstruction(hp1, A_Jcc, []) then
  5139. begin
  5140. if OptimizeJump(hp1) then
  5141. begin
  5142. Result := True;
  5143. if Assigned(hp1) then
  5144. begin
  5145. { CollapseZeroDistJump will be set to the label or an align
  5146. before it after the jump if it optimises, whether or not
  5147. the label is live or dead }
  5148. if (hp1.typ = ait_align) or
  5149. (
  5150. (hp1.typ = ait_label) and
  5151. not (tai_label(hp1).labsym.is_used)
  5152. ) then
  5153. GetNextInstruction(hp1, hp1);
  5154. end;
  5155. TransferUsedRegs(TmpUsedRegs);
  5156. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5157. if not Assigned(hp1) or
  5158. (
  5159. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5160. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5161. ) then
  5162. begin
  5163. { No more conditional jumps; conditional statement is no longer required }
  5164. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5165. RemoveCurrentP(p);
  5166. end;
  5167. Exit;
  5168. end;
  5169. if IsJumpToLabel(taicpu(hp1)) then
  5170. begin
  5171. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5172. if Assigned(JumpLabel) then
  5173. p_label := getlabelwithsym(JumpLabel);
  5174. end;
  5175. end;
  5176. { Search for:
  5177. test $x,(reg/ref)
  5178. jne @lbl1
  5179. test $y,(reg/ref) (same register or reference)
  5180. jne @lbl1
  5181. Change to:
  5182. test $(x or y),(reg/ref)
  5183. jne @lbl1
  5184. (Note, this doesn't work with je instead of jne)
  5185. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5186. Also search for:
  5187. test $x,(reg/ref)
  5188. je @lbl1
  5189. ...
  5190. test $y,(reg/ref)
  5191. je/jne @lbl2
  5192. If (x or y) = x, then the second jump is deterministic
  5193. }
  5194. if (
  5195. (
  5196. (taicpu(p).oper[0]^.typ = top_const) or
  5197. (
  5198. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5199. (taicpu(p).oper[0]^.typ = top_reg) and
  5200. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5201. )
  5202. ) and
  5203. MatchInstruction(hp1, A_JCC, [])
  5204. ) then
  5205. begin
  5206. if (taicpu(p).oper[0]^.typ = top_reg) and
  5207. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5208. FirstValue := -1
  5209. else
  5210. FirstValue := taicpu(p).oper[0]^.val;
  5211. { If we have several test/jne's in a row, it might be the case that
  5212. the second label doesn't go to the same location, but the one
  5213. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5214. so accommodate for this with a while loop.
  5215. }
  5216. hp1_last := hp1;
  5217. while (
  5218. (
  5219. (taicpu(p).oper[1]^.typ = top_reg) and
  5220. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5221. ) or GetNextInstruction(hp1_last, p_dist)
  5222. ) and (p_dist.typ = ait_instruction) do
  5223. begin
  5224. if (
  5225. (
  5226. (taicpu(p_dist).opcode = A_TEST) and
  5227. (
  5228. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5229. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5230. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5231. )
  5232. ) or
  5233. (
  5234. { cmp 0,%reg = test %reg,%reg }
  5235. (taicpu(p_dist).opcode = A_CMP) and
  5236. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5237. )
  5238. ) and
  5239. { Make sure the destination operands are actually the same }
  5240. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5241. GetNextInstruction(p_dist, hp1_dist) and
  5242. MatchInstruction(hp1_dist, A_JCC, []) then
  5243. begin
  5244. if OptimizeJump(hp1_dist) then
  5245. begin
  5246. Result := True;
  5247. Exit;
  5248. end;
  5249. if
  5250. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5251. (
  5252. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5253. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5254. ) then
  5255. SecondValue := -1
  5256. else
  5257. SecondValue := taicpu(p_dist).oper[0]^.val;
  5258. { If both of the TEST constants are identical, delete the
  5259. second TEST that is unnecessary (be careful though, just
  5260. in case the flags are modified in between) }
  5261. if (FirstValue = SecondValue) then
  5262. begin
  5263. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5264. begin
  5265. { Since the second jump's condition is a subset of the first, we
  5266. know it will never branch because the first jump dominates it.
  5267. Get it out of the way now rather than wait for the jump
  5268. optimisations for a speed boost. }
  5269. if IsJumpToLabel(taicpu(hp1_dist)) then
  5270. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5271. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5272. RemoveInstruction(hp1_dist);
  5273. Result := True;
  5274. end
  5275. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5276. begin
  5277. { If the inverse of the first condition is a subset of the second,
  5278. the second one will definitely branch if the first one doesn't }
  5279. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5280. { We can remove the TEST instruction too }
  5281. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5282. RemoveInstruction(p_dist);
  5283. MakeUnconditional(taicpu(hp1_dist));
  5284. RemoveDeadCodeAfterJump(hp1_dist);
  5285. { Since the jump is now unconditional, we can't
  5286. continue any further with this particular
  5287. optimisation. The original TEST is still intact
  5288. though, so there might be something else we can
  5289. do }
  5290. Include(OptsToCheck, aoc_ForceNewIteration);
  5291. Break;
  5292. end;
  5293. if Result or
  5294. { If a jump wasn't removed or made unconditional, only
  5295. remove the identical TEST instruction if the flags
  5296. weren't modified }
  5297. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5298. begin
  5299. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5300. RemoveInstruction(p_dist);
  5301. { If the jump was removed or made unconditional, we
  5302. don't need to allocate NR_DEFAULTFLAGS over the
  5303. entire range }
  5304. if not Result then
  5305. begin
  5306. { Mark the flags as 'in use' over the entire range }
  5307. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5308. { Speed gain - continue search from the Jcc instruction }
  5309. hp1_last := hp1_dist;
  5310. { Only the TEST instruction was removed, and the
  5311. original was unchanged, so we can safely do
  5312. another iteration of the while loop }
  5313. Include(OptsToCheck, aoc_ForceNewIteration);
  5314. Continue;
  5315. end;
  5316. Exit;
  5317. end;
  5318. end;
  5319. hp1_last := nil;
  5320. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5321. (
  5322. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5323. { Always adjacent under -O2 and under }
  5324. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5325. (
  5326. GetNextInstruction(hp1, hp1_last) and
  5327. (hp1_last = p_dist)
  5328. )
  5329. ) and
  5330. (
  5331. (
  5332. { Test the following variant:
  5333. test $x,(reg/ref)
  5334. jne @lbl1
  5335. test $y,(reg/ref)
  5336. je @lbl2
  5337. @lbl1:
  5338. Becomes:
  5339. test $(x or y),(reg/ref)
  5340. je @lbl2
  5341. @lbl1: (may become a dead label)
  5342. }
  5343. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5344. GetNextInstruction(hp1_dist, hp1_last) and
  5345. (hp1_last = p_label)
  5346. ) or
  5347. (
  5348. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5349. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5350. then the second jump will never branch, so it can also be
  5351. removed regardless of where it goes }
  5352. (
  5353. (FirstValue = -1) or
  5354. (SecondValue = -1) or
  5355. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5356. )
  5357. )
  5358. ) then
  5359. begin
  5360. { Same jump location... can be a register since nothing's changed }
  5361. { If any of the entries are equivalent to test %reg,%reg, then the
  5362. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5363. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5364. if (hp1_last = p_label) then
  5365. begin
  5366. { Variant }
  5367. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5368. RemoveInstruction(p_dist);
  5369. if Assigned(JumpLabel) then
  5370. JumpLabel.decrefs;
  5371. RemoveInstruction(hp1);
  5372. end
  5373. else
  5374. begin
  5375. { Only remove the second test if no jumps or other conditional instructions follow }
  5376. TransferUsedRegs(TmpUsedRegs);
  5377. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5378. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5379. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5380. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5381. begin
  5382. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5383. RemoveInstruction(p_dist);
  5384. { Remove the first jump, not the second, to keep
  5385. any register deallocations between the second
  5386. TEST/JNE pair in the same place. Aids future
  5387. optimisation. }
  5388. if Assigned(JumpLabel) then
  5389. JumpLabel.decrefs;
  5390. RemoveInstruction(hp1);
  5391. end
  5392. else
  5393. begin
  5394. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5395. if IsJumpToLabel(taicpu(hp1_dist)) then
  5396. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5397. { Remove second jump in this instance }
  5398. RemoveInstruction(hp1_dist);
  5399. end;
  5400. end;
  5401. Result := True;
  5402. Exit;
  5403. end;
  5404. end;
  5405. if { If -O2 and under, it may stop on any old instruction }
  5406. (cs_opt_level3 in current_settings.optimizerswitches) and
  5407. (taicpu(p).oper[1]^.typ = top_reg) and
  5408. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5409. begin
  5410. hp1_last := p_dist;
  5411. Continue;
  5412. end;
  5413. Break;
  5414. end;
  5415. end;
  5416. { Search for:
  5417. test %reg,%reg
  5418. j(c1) @lbl1
  5419. ...
  5420. @lbl:
  5421. test %reg,%reg (same register)
  5422. j(c2) @lbl2
  5423. If c2 is a subset of c1, change to:
  5424. test %reg,%reg
  5425. j(c1) @lbl2
  5426. (@lbl1 may become a dead label as a result)
  5427. }
  5428. if (taicpu(p).oper[1]^.typ = top_reg) and
  5429. (taicpu(p).oper[0]^.typ = top_reg) and
  5430. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5431. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5432. Assigned(p_label) and
  5433. GetNextInstruction(p_label, p_dist) and
  5434. MatchInstruction(p_dist, A_TEST, []) and
  5435. { It's fine if the second test uses smaller sub-registers }
  5436. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5437. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5438. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5439. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5440. GetNextInstruction(p_dist, hp1_dist) and
  5441. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5442. begin
  5443. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5444. if JumpLabel = JumpLabel_dist then
  5445. { This is an infinite loop }
  5446. Exit;
  5447. { Best optimisation when the first condition is a subset (or equal) of the second }
  5448. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5449. begin
  5450. { Any registers used here will already be allocated }
  5451. if Assigned(JumpLabel) then
  5452. JumpLabel.DecRefs;
  5453. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5454. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5455. Result := True;
  5456. Exit;
  5457. end;
  5458. end;
  5459. end;
  5460. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5461. var
  5462. hp1, hp2: tai;
  5463. ActiveReg: TRegister;
  5464. OldOffset: asizeint;
  5465. ThisConst: TCGInt;
  5466. function RegDeallocated: Boolean;
  5467. begin
  5468. TransferUsedRegs(TmpUsedRegs);
  5469. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5470. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5471. end;
  5472. begin
  5473. result:=false;
  5474. hp1 := nil;
  5475. { replace
  5476. addX const,%reg1
  5477. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5478. dealloc %reg1
  5479. by
  5480. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5481. }
  5482. if MatchOpType(taicpu(p),top_const,top_reg) then
  5483. begin
  5484. ActiveReg := taicpu(p).oper[1]^.reg;
  5485. { Ensures the entire register was updated }
  5486. if (taicpu(p).opsize >= S_L) and
  5487. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5488. MatchInstruction(hp1,A_LEA,[]) and
  5489. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5490. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5491. (
  5492. { Cover the case where the register in the reference is also the destination register }
  5493. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5494. (
  5495. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5496. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5497. RegDeallocated
  5498. )
  5499. ) then
  5500. begin
  5501. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5502. {$push}
  5503. {$R-}{$Q-}
  5504. { Explicitly disable overflow checking for these offset calculation
  5505. as those do not matter for the final result }
  5506. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5507. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5508. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5509. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5510. {$pop}
  5511. {$ifdef x86_64}
  5512. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5513. begin
  5514. { Overflow; abort }
  5515. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5516. end
  5517. else
  5518. {$endif x86_64}
  5519. begin
  5520. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5521. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5522. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5523. RemoveCurrentP(p, hp1)
  5524. else
  5525. RemoveCurrentP(p);
  5526. result:=true;
  5527. Exit;
  5528. end;
  5529. end;
  5530. if (
  5531. { Save calling GetNextInstructionUsingReg again }
  5532. Assigned(hp1) or
  5533. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5534. ) and
  5535. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5536. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5537. begin
  5538. if taicpu(hp1).oper[0]^.typ = top_const then
  5539. begin
  5540. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5541. if taicpu(hp1).opcode = A_ADD then
  5542. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5543. else
  5544. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5545. Result := True;
  5546. { Handle any overflows }
  5547. case taicpu(p).opsize of
  5548. S_B:
  5549. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5550. S_W:
  5551. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5552. S_L:
  5553. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5554. {$ifdef x86_64}
  5555. S_Q:
  5556. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5557. { Overflow; abort }
  5558. Result := False
  5559. else
  5560. taicpu(p).oper[0]^.val := ThisConst;
  5561. {$endif x86_64}
  5562. else
  5563. InternalError(2021102610);
  5564. end;
  5565. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5566. if Result then
  5567. begin
  5568. if (taicpu(p).oper[0]^.val < 0) and
  5569. (
  5570. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5571. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5572. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5573. ) then
  5574. begin
  5575. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5576. taicpu(p).opcode := A_SUB;
  5577. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5578. end
  5579. else
  5580. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5581. RemoveInstruction(hp1);
  5582. end;
  5583. end
  5584. else
  5585. begin
  5586. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5587. TransferUsedRegs(TmpUsedRegs);
  5588. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5589. hp2 := p;
  5590. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5591. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5592. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5593. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5594. begin
  5595. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5596. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5597. Asml.Remove(p);
  5598. Asml.InsertAfter(p, hp1);
  5599. p := hp1;
  5600. Result := True;
  5601. Exit;
  5602. end;
  5603. end;
  5604. end;
  5605. if DoArithCombineOpt(p) then
  5606. Result:=true;
  5607. end;
  5608. end;
  5609. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5610. var
  5611. hp1, hp2: tai;
  5612. ref: Integer;
  5613. saveref: treference;
  5614. offsetcalc: Int64;
  5615. TempReg: TRegister;
  5616. Multiple: TCGInt;
  5617. Adjacent, IntermediateRegDiscarded: Boolean;
  5618. begin
  5619. Result:=false;
  5620. { play save and throw an error if LEA uses a seg register prefix,
  5621. this is most likely an error somewhere else }
  5622. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5623. internalerror(2022022001);
  5624. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5625. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5626. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5627. (
  5628. { do not mess with leas accessing the stack pointer
  5629. unless it's a null operation }
  5630. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5631. (
  5632. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5633. (taicpu(p).oper[0]^.ref^.offset = 0)
  5634. )
  5635. ) and
  5636. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5637. begin
  5638. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5639. begin
  5640. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5641. begin
  5642. taicpu(p).opcode := A_MOV;
  5643. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5644. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5645. end
  5646. else
  5647. begin
  5648. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5649. RemoveCurrentP(p);
  5650. end;
  5651. Result:=true;
  5652. exit;
  5653. end
  5654. else if (
  5655. { continue to use lea to adjust the stack pointer,
  5656. it is the recommended way, but only if not optimizing for size }
  5657. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5658. (cs_opt_size in current_settings.optimizerswitches)
  5659. ) and
  5660. { If the flags register is in use, don't change the instruction
  5661. to an ADD otherwise this will scramble the flags. [Kit] }
  5662. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5663. ConvertLEA(taicpu(p)) then
  5664. begin
  5665. Result:=true;
  5666. exit;
  5667. end;
  5668. end;
  5669. { Don't optimise if the stack or frame pointer is the destination register }
  5670. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5671. Exit;
  5672. if GetNextInstruction(p,hp1) and
  5673. (hp1.typ=ait_instruction) then
  5674. begin
  5675. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5676. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5677. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5678. begin
  5679. TransferUsedRegs(TmpUsedRegs);
  5680. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5681. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5682. begin
  5683. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5684. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5685. RemoveInstruction(hp1);
  5686. result:=true;
  5687. exit;
  5688. end;
  5689. end;
  5690. { changes
  5691. lea <ref1>, reg1
  5692. <op> ...,<ref. with reg1>,...
  5693. to
  5694. <op> ...,<ref1>,... }
  5695. { find a reference which uses reg1 }
  5696. 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
  5697. ref:=0
  5698. 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
  5699. ref:=1
  5700. else
  5701. ref:=-1;
  5702. if (ref<>-1) and
  5703. { reg1 must be either the base or the index }
  5704. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5705. begin
  5706. { reg1 can be removed from the reference }
  5707. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5708. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5709. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5710. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5711. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5712. else
  5713. Internalerror(2019111201);
  5714. { check if the can insert all data of the lea into the second instruction }
  5715. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5716. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5717. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5718. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5719. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5720. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5721. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5722. {$ifdef x86_64}
  5723. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5724. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5725. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5726. )
  5727. {$endif x86_64}
  5728. then
  5729. begin
  5730. { reg1 might not used by the second instruction after it is remove from the reference }
  5731. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5732. begin
  5733. TransferUsedRegs(TmpUsedRegs);
  5734. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5735. { reg1 is not updated so it might not be used afterwards }
  5736. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5737. begin
  5738. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5739. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5740. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5741. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5742. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5743. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5744. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5745. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5746. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5747. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5748. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5749. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5750. RemoveCurrentP(p, hp1);
  5751. result:=true;
  5752. exit;
  5753. end
  5754. end;
  5755. end;
  5756. { recover }
  5757. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5758. end;
  5759. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5760. if Adjacent or
  5761. { Check further ahead (up to 2 instructions ahead for -O2) }
  5762. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5763. begin
  5764. { Check common LEA/LEA conditions }
  5765. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5766. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5767. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5768. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5769. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5770. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5771. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5772. (
  5773. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5774. calling it (since it calls GetNextInstruction) }
  5775. Adjacent or
  5776. (
  5777. (
  5778. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5779. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5780. ) and (
  5781. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5782. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5783. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5784. )
  5785. )
  5786. ) then
  5787. begin
  5788. TransferUsedRegs(TmpUsedRegs);
  5789. hp2 := p;
  5790. repeat
  5791. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5792. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5793. IntermediateRegDiscarded :=
  5794. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5795. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5796. { changes
  5797. lea offset1(regX,scale), reg1
  5798. lea offset2(reg1,reg1), reg2
  5799. to
  5800. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5801. and
  5802. lea offset1(regX,scale1), reg1
  5803. lea offset2(reg1,scale2), reg2
  5804. to
  5805. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5806. and
  5807. lea offset1(regX,scale1), reg1
  5808. lea offset2(reg3,reg1,scale2), reg2
  5809. to
  5810. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5811. ... so long as the final scale does not exceed 8
  5812. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5813. }
  5814. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5815. (
  5816. { Don't optimise if size is a concern and the intermediate register remains in use }
  5817. IntermediateRegDiscarded or
  5818. not (cs_opt_size in current_settings.optimizerswitches)
  5819. ) and
  5820. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5821. (
  5822. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5823. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5824. ) and (
  5825. (
  5826. { lea (reg1,scale2), reg2 variant }
  5827. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5828. (
  5829. Adjacent or
  5830. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5831. ) and
  5832. (
  5833. (
  5834. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5835. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5836. ) or (
  5837. { lea (regX,regX), reg1 variant }
  5838. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5839. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5840. )
  5841. )
  5842. ) or (
  5843. { lea (reg1,reg1), reg1 variant }
  5844. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5845. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5846. )
  5847. ) then
  5848. begin
  5849. { Make everything homogeneous to make calculations easier }
  5850. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5851. begin
  5852. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5853. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5854. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5855. else
  5856. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5857. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5858. end;
  5859. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5860. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5861. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5862. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5863. begin
  5864. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5865. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5866. begin
  5867. { Put the register to change in the index register }
  5868. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5869. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5870. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5871. end;
  5872. { Change lea (reg,reg) to lea(,reg,2) }
  5873. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5874. begin
  5875. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5876. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5877. end;
  5878. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5879. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5880. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5881. { Just to prevent miscalculations }
  5882. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5883. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5884. else
  5885. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5886. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5887. if IntermediateRegDiscarded then
  5888. begin
  5889. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5890. RemoveCurrentP(p);
  5891. end
  5892. else
  5893. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5894. result:=true;
  5895. exit;
  5896. end;
  5897. end;
  5898. { changes
  5899. lea offset1(regX), reg1
  5900. lea offset2(reg1), reg2
  5901. to
  5902. lea offset1+offset2(regX), reg2 }
  5903. if (
  5904. { Don't optimise if size is a concern and the intermediate register remains in use }
  5905. IntermediateRegDiscarded or
  5906. not (cs_opt_size in current_settings.optimizerswitches)
  5907. ) and
  5908. (
  5909. (
  5910. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5911. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5912. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5913. ) or (
  5914. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5915. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5916. (
  5917. (
  5918. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5919. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5920. ) or (
  5921. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5922. (
  5923. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5924. (
  5925. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5926. (
  5927. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5928. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5929. )
  5930. )
  5931. )
  5932. )
  5933. )
  5934. )
  5935. ) then
  5936. begin
  5937. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5938. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5939. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5940. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5941. begin
  5942. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5943. begin
  5944. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5945. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5946. { if the register is used as index and base, we have to increase for base as well
  5947. and adapt base }
  5948. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5949. begin
  5950. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5951. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5952. end;
  5953. end
  5954. else
  5955. begin
  5956. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5957. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5958. end;
  5959. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5960. begin
  5961. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5962. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5963. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5964. { Catch the situation where the base = index
  5965. and treat this as *2. The scalefactor of
  5966. p will be 0 or 1 due to the conditional
  5967. checks above. Fixes i40647 }
  5968. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5969. else
  5970. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5971. end;
  5972. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5973. if IntermediateRegDiscarded then
  5974. begin
  5975. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5976. RemoveCurrentP(p);
  5977. end
  5978. else
  5979. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5980. result:=true;
  5981. exit;
  5982. end;
  5983. end;
  5984. end;
  5985. { Change:
  5986. leal/q $x(%reg1),%reg2
  5987. ...
  5988. shll/q $y,%reg2
  5989. To:
  5990. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5991. }
  5992. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5993. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5994. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5995. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5996. (taicpu(hp1).oper[0]^.val <= 3) then
  5997. begin
  5998. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5999. TransferUsedRegs(TmpUsedRegs);
  6000. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6001. if
  6002. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6003. (this works even if scalefactor is zero) }
  6004. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6005. { Ensure offset doesn't go out of bounds }
  6006. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6007. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6008. (
  6009. (
  6010. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6011. (
  6012. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6013. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6014. (
  6015. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6016. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6017. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6018. )
  6019. )
  6020. ) or (
  6021. (
  6022. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6023. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6024. ) and
  6025. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6026. )
  6027. ) then
  6028. begin
  6029. repeat
  6030. with taicpu(p).oper[0]^.ref^ do
  6031. begin
  6032. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6033. if index = base then
  6034. begin
  6035. if Multiple > 4 then
  6036. { Optimisation will no longer work because resultant
  6037. scale factor will exceed 8 }
  6038. Break;
  6039. base := NR_NO;
  6040. scalefactor := 2;
  6041. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6042. end
  6043. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6044. begin
  6045. { Scale factor only works on the index register }
  6046. index := base;
  6047. base := NR_NO;
  6048. end;
  6049. { For safety }
  6050. if scalefactor <= 1 then
  6051. begin
  6052. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6053. scalefactor := Multiple;
  6054. end
  6055. else
  6056. begin
  6057. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6058. scalefactor := scalefactor * Multiple;
  6059. end;
  6060. offset := offset * Multiple;
  6061. end;
  6062. RemoveInstruction(hp1);
  6063. Result := True;
  6064. Exit;
  6065. { This repeat..until loop exists for the benefit of Break }
  6066. until True;
  6067. end;
  6068. end;
  6069. end;
  6070. end;
  6071. end;
  6072. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6073. var
  6074. hp1 : tai;
  6075. SubInstr: Boolean;
  6076. ThisConst: TCGInt;
  6077. const
  6078. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6079. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6080. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6081. begin
  6082. Result := False;
  6083. if taicpu(p).oper[0]^.typ <> top_const then
  6084. { Should have been confirmed before calling }
  6085. InternalError(2021102601);
  6086. SubInstr := (taicpu(p).opcode = A_SUB);
  6087. if GetLastInstruction(p, hp1) and
  6088. (hp1.typ = ait_instruction) and
  6089. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6090. begin
  6091. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6092. { Bad size }
  6093. InternalError(2022042001);
  6094. case taicpu(hp1).opcode Of
  6095. A_INC:
  6096. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6097. begin
  6098. if SubInstr then
  6099. ThisConst := taicpu(p).oper[0]^.val - 1
  6100. else
  6101. ThisConst := taicpu(p).oper[0]^.val + 1;
  6102. end
  6103. else
  6104. Exit;
  6105. A_DEC:
  6106. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6107. begin
  6108. if SubInstr then
  6109. ThisConst := taicpu(p).oper[0]^.val + 1
  6110. else
  6111. ThisConst := taicpu(p).oper[0]^.val - 1;
  6112. end
  6113. else
  6114. Exit;
  6115. A_SUB:
  6116. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6117. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6118. begin
  6119. if SubInstr then
  6120. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6121. else
  6122. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6123. end
  6124. else
  6125. Exit;
  6126. A_ADD:
  6127. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6128. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6129. begin
  6130. if SubInstr then
  6131. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6132. else
  6133. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6134. end
  6135. else
  6136. Exit;
  6137. else
  6138. Exit;
  6139. end;
  6140. { Check that the values are in range }
  6141. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6142. { Overflow; abort }
  6143. Exit;
  6144. if (ThisConst = 0) then
  6145. begin
  6146. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6147. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6148. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6149. RemoveInstruction(hp1);
  6150. hp1 := tai(p.next);
  6151. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6152. if not GetLastInstruction(hp1, p) then
  6153. p := hp1;
  6154. end
  6155. else
  6156. begin
  6157. if taicpu(hp1).opercnt=1 then
  6158. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6159. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6160. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6161. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6162. else
  6163. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6164. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6165. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6166. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6167. RemoveInstruction(hp1);
  6168. taicpu(p).loadconst(0, ThisConst);
  6169. end;
  6170. Result := True;
  6171. end;
  6172. end;
  6173. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6174. begin
  6175. Result := False;
  6176. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6177. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6178. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6179. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6180. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6181. (
  6182. (
  6183. (taicpu(hp1).opcode = A_TEST)
  6184. ) or (
  6185. (taicpu(hp1).opcode = A_CMP) and
  6186. { A sanity check more than anything }
  6187. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6188. )
  6189. ) then
  6190. begin
  6191. { change
  6192. mov mem, %reg
  6193. ...
  6194. cmp/test x, %reg / test %reg,%reg
  6195. (reg deallocated)
  6196. to
  6197. cmp/test x, mem / cmp 0, mem
  6198. }
  6199. TransferUsedRegs(TmpUsedRegs);
  6200. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6201. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6202. begin
  6203. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6204. if (taicpu(hp1).opcode = A_TEST) and
  6205. (
  6206. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6207. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6208. ) then
  6209. begin
  6210. taicpu(hp1).opcode := A_CMP;
  6211. taicpu(hp1).loadconst(0, 0);
  6212. end;
  6213. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6214. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6215. RemoveCurrentP(p);
  6216. if (p <> hp1) then
  6217. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6218. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6219. { Make sure the flags are allocated across the CMP instruction }
  6220. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6221. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6222. Result := True;
  6223. Exit;
  6224. end;
  6225. end;
  6226. end;
  6227. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6228. var
  6229. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6230. ThisReg, SecondReg: TRegister;
  6231. JumpLoc: TAsmLabel;
  6232. NewSize: TOpSize;
  6233. begin
  6234. Result := False;
  6235. {
  6236. Convert:
  6237. j<c> .L1
  6238. .L2:
  6239. mov 1,reg
  6240. jmp .L3 (or ret, although it might not be a RET yet)
  6241. .L1:
  6242. mov 0,reg
  6243. jmp .L3 (or ret)
  6244. ( As long as .L3 <> .L1 or .L2)
  6245. To:
  6246. mov 0,reg
  6247. set<not(c)> reg
  6248. jmp .L3 (or ret)
  6249. .L2:
  6250. mov 1,reg
  6251. jmp .L3 (or ret)
  6252. .L1:
  6253. mov 0,reg
  6254. jmp .L3 (or ret)
  6255. }
  6256. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6257. Exit;
  6258. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6259. if GetNextInstruction(hp_label, hp2) and
  6260. MatchInstruction(hp2,A_MOV,[]) and
  6261. (taicpu(hp2).oper[0]^.typ = top_const) and
  6262. (
  6263. (
  6264. (taicpu(hp2).oper[1]^.typ = top_reg)
  6265. {$ifdef i386}
  6266. { Under i386, ESI, EDI, EBP and ESP
  6267. don't have an 8-bit representation }
  6268. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6269. {$endif i386}
  6270. ) or (
  6271. {$ifdef i386}
  6272. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6273. {$endif i386}
  6274. (taicpu(hp2).opsize = S_B)
  6275. )
  6276. ) and
  6277. GetNextInstruction(hp2, hp3) and
  6278. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6279. (
  6280. (taicpu(hp3).opcode=A_RET) or
  6281. (
  6282. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6283. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6284. )
  6285. ) and
  6286. GetNextInstruction(hp3, hp4) and
  6287. FindLabel(JumpLoc, hp4) and
  6288. (
  6289. not (cs_opt_size in current_settings.optimizerswitches) or
  6290. { If the initial jump is the label's only reference, then it will
  6291. become a dead label if the other conditions are met and hence
  6292. remove at least 2 instructions, including a jump }
  6293. (JumpLoc.getrefs = 1)
  6294. ) and
  6295. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6296. that will be optimised out }
  6297. GetNextInstruction(hp4, hp5) and
  6298. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6299. (taicpu(hp5).oper[0]^.typ = top_const) and
  6300. (
  6301. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6302. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6303. ) and
  6304. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6305. GetNextInstruction(hp5,hp6) and
  6306. (
  6307. not (hp6.typ in [ait_align, ait_label]) or
  6308. SkipLabels(hp6, hp6)
  6309. ) and
  6310. (hp6.typ=ait_instruction) then
  6311. begin
  6312. { First, let's look at the two jumps that are hp3 and hp6 }
  6313. if not
  6314. (
  6315. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6316. (
  6317. (taicpu(hp6).opcode=A_RET) or
  6318. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6319. )
  6320. ) then
  6321. { If condition is False, then the JMP/RET instructions matched conventionally }
  6322. begin
  6323. { See if one of the jumps can be instantly converted into a RET }
  6324. if (taicpu(hp3).opcode=A_JMP) then
  6325. begin
  6326. { Reuse hp5 }
  6327. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6328. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6329. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6330. Exit;
  6331. if MatchInstruction(hp5, A_RET, []) then
  6332. begin
  6333. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6334. ConvertJumpToRET(hp3, hp5);
  6335. Result := True;
  6336. end
  6337. else
  6338. Exit;
  6339. end;
  6340. if (taicpu(hp6).opcode=A_JMP) then
  6341. begin
  6342. { Reuse hp5 }
  6343. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6344. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6345. Exit;
  6346. if MatchInstruction(hp5, A_RET, []) then
  6347. begin
  6348. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6349. ConvertJumpToRET(hp6, hp5);
  6350. Result := True;
  6351. end
  6352. else
  6353. Exit;
  6354. end;
  6355. if not
  6356. (
  6357. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6358. (
  6359. (taicpu(hp6).opcode=A_RET) or
  6360. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6361. )
  6362. ) then
  6363. { Still doesn't match }
  6364. Exit;
  6365. end;
  6366. if (taicpu(hp2).oper[0]^.val = 1) then
  6367. begin
  6368. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6369. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6370. end
  6371. else
  6372. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6373. if taicpu(hp2).opsize=S_B then
  6374. begin
  6375. if taicpu(hp2).oper[1]^.typ = top_reg then
  6376. begin
  6377. SecondReg := taicpu(hp2).oper[1]^.reg;
  6378. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6379. end
  6380. else
  6381. begin
  6382. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6383. SecondReg := NR_NO;
  6384. end;
  6385. hp_pos := p;
  6386. hp_allocstart := hp4;
  6387. end
  6388. else
  6389. begin
  6390. { Will be a register because the size can't be S_B otherwise }
  6391. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6392. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6393. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6394. if (cs_opt_size in current_settings.optimizerswitches) then
  6395. begin
  6396. { Favour using MOVZX when optimising for size }
  6397. case taicpu(hp2).opsize of
  6398. S_W:
  6399. NewSize := S_BW;
  6400. S_L:
  6401. NewSize := S_BL;
  6402. {$ifdef x86_64}
  6403. S_Q:
  6404. begin
  6405. NewSize := S_BL;
  6406. { Will implicitly zero-extend to 64-bit }
  6407. setsubreg(SecondReg, R_SUBD);
  6408. end;
  6409. {$endif x86_64}
  6410. else
  6411. InternalError(2022101301);
  6412. end;
  6413. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6414. { Inserting it right before p will guarantee that the flags are also tracked }
  6415. Asml.InsertBefore(hp5, p);
  6416. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6417. hp_pos := hp5;
  6418. hp_allocstart := hp4;
  6419. end
  6420. else
  6421. begin
  6422. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6423. { Inserting it right before p will guarantee that the flags are also tracked }
  6424. Asml.InsertBefore(hp5, p);
  6425. hp_pos := p;
  6426. hp_allocstart := hp5;
  6427. end;
  6428. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6429. end;
  6430. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6431. taicpu(hp4).condition := taicpu(p).condition;
  6432. asml.InsertBefore(hp4, hp_pos);
  6433. if taicpu(hp3).is_jmp then
  6434. begin
  6435. JumpLoc.decrefs;
  6436. MakeUnconditional(taicpu(p));
  6437. { This also increases the reference count }
  6438. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6439. end
  6440. else
  6441. ConvertJumpToRET(p, hp3);
  6442. if SecondReg <> NR_NO then
  6443. { Ensure the destination register is allocated over this region }
  6444. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6445. if (JumpLoc.getrefs = 0) then
  6446. RemoveDeadCodeAfterJump(hp3);
  6447. Result:=true;
  6448. exit;
  6449. end;
  6450. end;
  6451. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6452. var
  6453. hp1, hp2: tai;
  6454. ActiveReg: TRegister;
  6455. OldOffset: asizeint;
  6456. ThisConst: TCGInt;
  6457. function RegDeallocated: Boolean;
  6458. begin
  6459. TransferUsedRegs(TmpUsedRegs);
  6460. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6461. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6462. end;
  6463. begin
  6464. Result:=false;
  6465. hp1 := nil;
  6466. { replace
  6467. subX const,%reg1
  6468. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6469. dealloc %reg1
  6470. by
  6471. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6472. }
  6473. if MatchOpType(taicpu(p),top_const,top_reg) then
  6474. begin
  6475. ActiveReg := taicpu(p).oper[1]^.reg;
  6476. { Ensures the entire register was updated }
  6477. if (taicpu(p).opsize >= S_L) and
  6478. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6479. MatchInstruction(hp1,A_LEA,[]) and
  6480. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6481. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6482. (
  6483. { Cover the case where the register in the reference is also the destination register }
  6484. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6485. (
  6486. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6487. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6488. RegDeallocated
  6489. )
  6490. ) then
  6491. begin
  6492. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6493. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6494. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6495. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6496. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6497. {$ifdef x86_64}
  6498. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6499. begin
  6500. { Overflow; abort }
  6501. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6502. end
  6503. else
  6504. {$endif x86_64}
  6505. begin
  6506. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6507. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6508. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6509. RemoveCurrentP(p, hp1)
  6510. else
  6511. RemoveCurrentP(p);
  6512. result:=true;
  6513. Exit;
  6514. end;
  6515. end;
  6516. if (
  6517. { Save calling GetNextInstructionUsingReg again }
  6518. Assigned(hp1) or
  6519. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6520. ) and
  6521. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6522. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6523. begin
  6524. if taicpu(hp1).oper[0]^.typ = top_const then
  6525. begin
  6526. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6527. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6528. Result := True;
  6529. { Handle any overflows }
  6530. case taicpu(p).opsize of
  6531. S_B:
  6532. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6533. S_W:
  6534. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6535. S_L:
  6536. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6537. {$ifdef x86_64}
  6538. S_Q:
  6539. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6540. { Overflow; abort }
  6541. Result := False
  6542. else
  6543. taicpu(p).oper[0]^.val := ThisConst;
  6544. {$endif x86_64}
  6545. else
  6546. InternalError(2021102611);
  6547. end;
  6548. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6549. if Result then
  6550. begin
  6551. if (taicpu(p).oper[0]^.val < 0) and
  6552. (
  6553. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6554. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6555. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6556. ) then
  6557. begin
  6558. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6559. taicpu(p).opcode := A_SUB;
  6560. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6561. end
  6562. else
  6563. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6564. RemoveInstruction(hp1);
  6565. end;
  6566. end
  6567. else
  6568. begin
  6569. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6570. TransferUsedRegs(TmpUsedRegs);
  6571. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6572. hp2 := p;
  6573. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6574. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6575. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6576. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6577. begin
  6578. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6579. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6580. Asml.Remove(p);
  6581. Asml.InsertAfter(p, hp1);
  6582. p := hp1;
  6583. Result := True;
  6584. Exit;
  6585. end;
  6586. end;
  6587. end;
  6588. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6589. { * change "sub/add const1, reg" or "dec reg" followed by
  6590. "sub const2, reg" to one "sub ..., reg" }
  6591. {$ifdef i386}
  6592. if (taicpu(p).oper[0]^.val = 2) and
  6593. (ActiveReg = NR_ESP) and
  6594. { Don't do the sub/push optimization if the sub }
  6595. { comes from setting up the stack frame (JM) }
  6596. (not(GetLastInstruction(p,hp1)) or
  6597. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6598. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6599. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6600. begin
  6601. hp1 := tai(p.next);
  6602. while Assigned(hp1) and
  6603. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6604. not RegReadByInstruction(NR_ESP,hp1) and
  6605. not RegModifiedByInstruction(NR_ESP,hp1) do
  6606. hp1 := tai(hp1.next);
  6607. if Assigned(hp1) and
  6608. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6609. begin
  6610. taicpu(hp1).changeopsize(S_L);
  6611. if taicpu(hp1).oper[0]^.typ=top_reg then
  6612. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6613. hp1 := tai(p.next);
  6614. RemoveCurrentp(p, hp1);
  6615. Result:=true;
  6616. exit;
  6617. end;
  6618. end;
  6619. {$endif i386}
  6620. if DoArithCombineOpt(p) then
  6621. Result:=true;
  6622. end;
  6623. end;
  6624. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6625. var
  6626. TmpBool1,TmpBool2 : Boolean;
  6627. tmpref : treference;
  6628. hp1,hp2: tai;
  6629. mask, shiftval: tcgint;
  6630. begin
  6631. Result:=false;
  6632. { All these optimisations work on "shl/sal const,%reg" }
  6633. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6634. Exit;
  6635. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6636. (taicpu(p).oper[0]^.val <= 3) then
  6637. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6638. begin
  6639. { should we check the next instruction? }
  6640. TmpBool1 := True;
  6641. { have we found an add/sub which could be
  6642. integrated in the lea? }
  6643. TmpBool2 := False;
  6644. reference_reset(tmpref,2,[]);
  6645. TmpRef.index := taicpu(p).oper[1]^.reg;
  6646. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6647. while TmpBool1 and
  6648. GetNextInstruction(p, hp1) and
  6649. (tai(hp1).typ = ait_instruction) and
  6650. ((((taicpu(hp1).opcode = A_ADD) or
  6651. (taicpu(hp1).opcode = A_SUB)) and
  6652. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6653. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6654. (((taicpu(hp1).opcode = A_INC) or
  6655. (taicpu(hp1).opcode = A_DEC)) and
  6656. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6657. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6658. ((taicpu(hp1).opcode = A_LEA) and
  6659. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6660. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6661. (not GetNextInstruction(hp1,hp2) or
  6662. not instrReadsFlags(hp2)) Do
  6663. begin
  6664. TmpBool1 := False;
  6665. if taicpu(hp1).opcode=A_LEA then
  6666. begin
  6667. if (TmpRef.base = NR_NO) and
  6668. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6669. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6670. { Segment register isn't a concern here }
  6671. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6672. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6673. begin
  6674. TmpBool1 := True;
  6675. TmpBool2 := True;
  6676. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6677. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6678. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6679. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6680. RemoveInstruction(hp1);
  6681. end
  6682. end
  6683. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6684. begin
  6685. TmpBool1 := True;
  6686. TmpBool2 := True;
  6687. case taicpu(hp1).opcode of
  6688. A_ADD:
  6689. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6690. A_SUB:
  6691. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6692. else
  6693. internalerror(2019050536);
  6694. end;
  6695. RemoveInstruction(hp1);
  6696. end
  6697. else
  6698. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6699. (((taicpu(hp1).opcode = A_ADD) and
  6700. (TmpRef.base = NR_NO)) or
  6701. (taicpu(hp1).opcode = A_INC) or
  6702. (taicpu(hp1).opcode = A_DEC)) then
  6703. begin
  6704. TmpBool1 := True;
  6705. TmpBool2 := True;
  6706. case taicpu(hp1).opcode of
  6707. A_ADD:
  6708. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6709. A_INC:
  6710. inc(TmpRef.offset);
  6711. A_DEC:
  6712. dec(TmpRef.offset);
  6713. else
  6714. internalerror(2019050535);
  6715. end;
  6716. RemoveInstruction(hp1);
  6717. end;
  6718. end;
  6719. if TmpBool2
  6720. {$ifndef x86_64}
  6721. or
  6722. ((current_settings.optimizecputype < cpu_Pentium2) and
  6723. (taicpu(p).oper[0]^.val <= 3) and
  6724. not(cs_opt_size in current_settings.optimizerswitches))
  6725. {$endif x86_64}
  6726. then
  6727. begin
  6728. if not(TmpBool2) and
  6729. (taicpu(p).oper[0]^.val=1) then
  6730. begin
  6731. taicpu(p).opcode := A_ADD;
  6732. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6733. end
  6734. else
  6735. begin
  6736. taicpu(p).opcode := A_LEA;
  6737. taicpu(p).loadref(0, TmpRef);
  6738. end;
  6739. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6740. Result := True;
  6741. end;
  6742. end
  6743. {$ifndef x86_64}
  6744. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6745. begin
  6746. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6747. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6748. (unlike shl, which is only Tairable in the U pipe) }
  6749. if taicpu(p).oper[0]^.val=1 then
  6750. begin
  6751. taicpu(p).opcode := A_ADD;
  6752. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6753. Result := True;
  6754. end
  6755. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6756. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6757. else if (taicpu(p).opsize = S_L) and
  6758. (taicpu(p).oper[0]^.val<= 3) then
  6759. begin
  6760. reference_reset(tmpref,2,[]);
  6761. TmpRef.index := taicpu(p).oper[1]^.reg;
  6762. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6763. taicpu(p).opcode := A_LEA;
  6764. taicpu(p).loadref(0, TmpRef);
  6765. Result := True;
  6766. end;
  6767. end
  6768. {$endif x86_64}
  6769. else if
  6770. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6771. (
  6772. (
  6773. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6774. SetAndTest(hp1, hp2)
  6775. {$ifdef x86_64}
  6776. ) or
  6777. (
  6778. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6779. GetNextInstruction(hp1, hp2) and
  6780. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6781. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6782. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6783. {$endif x86_64}
  6784. )
  6785. ) and
  6786. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6787. begin
  6788. { Change:
  6789. shl x, %reg1
  6790. mov -(1<<x), %reg2
  6791. and %reg2, %reg1
  6792. Or:
  6793. shl x, %reg1
  6794. and -(1<<x), %reg1
  6795. To just:
  6796. shl x, %reg1
  6797. Since the and operation only zeroes bits that are already zero from the shl operation
  6798. }
  6799. case taicpu(p).oper[0]^.val of
  6800. 8:
  6801. mask:=$FFFFFFFFFFFFFF00;
  6802. 16:
  6803. mask:=$FFFFFFFFFFFF0000;
  6804. 32:
  6805. mask:=$FFFFFFFF00000000;
  6806. 63:
  6807. { Constant pre-calculated to prevent overflow errors with Int64 }
  6808. mask:=$8000000000000000;
  6809. else
  6810. begin
  6811. if taicpu(p).oper[0]^.val >= 64 then
  6812. { Shouldn't happen realistically, since the register
  6813. is guaranteed to be set to zero at this point }
  6814. mask := 0
  6815. else
  6816. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6817. end;
  6818. end;
  6819. if taicpu(hp1).oper[0]^.val = mask then
  6820. begin
  6821. { Everything checks out, perform the optimisation, as long as
  6822. the FLAGS register isn't being used}
  6823. TransferUsedRegs(TmpUsedRegs);
  6824. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6825. {$ifdef x86_64}
  6826. if (hp1 <> hp2) then
  6827. begin
  6828. { "shl/mov/and" version }
  6829. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6830. { Don't do the optimisation if the FLAGS register is in use }
  6831. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6832. begin
  6833. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6834. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6835. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6836. begin
  6837. RemoveInstruction(hp1);
  6838. Result := True;
  6839. end;
  6840. { Only set Result to True if the 'mov' instruction was removed }
  6841. RemoveInstruction(hp2);
  6842. end;
  6843. end
  6844. else
  6845. {$endif x86_64}
  6846. begin
  6847. { "shl/and" version }
  6848. { Don't do the optimisation if the FLAGS register is in use }
  6849. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6850. begin
  6851. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6852. RemoveInstruction(hp1);
  6853. Result := True;
  6854. end;
  6855. end;
  6856. Exit;
  6857. end
  6858. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6859. begin
  6860. { Even if the mask doesn't allow for its removal, we might be
  6861. able to optimise the mask for the "shl/and" version, which
  6862. may permit other peephole optimisations }
  6863. {$ifdef DEBUG_AOPTCPU}
  6864. mask := taicpu(hp1).oper[0]^.val and mask;
  6865. if taicpu(hp1).oper[0]^.val <> mask then
  6866. begin
  6867. DebugMsg(
  6868. SPeepholeOptimization +
  6869. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6870. ' to $' + debug_tostr(mask) +
  6871. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6872. taicpu(hp1).oper[0]^.val := mask;
  6873. end;
  6874. {$else DEBUG_AOPTCPU}
  6875. { If debugging is off, just set the operand even if it's the same }
  6876. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6877. {$endif DEBUG_AOPTCPU}
  6878. end;
  6879. end;
  6880. {
  6881. change
  6882. shl/sal const,reg
  6883. <op> ...(...,reg,1),...
  6884. into
  6885. <op> ...(...,reg,1 shl const),...
  6886. if const in 1..3
  6887. }
  6888. if MatchOpType(taicpu(p), top_const, top_reg) and
  6889. (taicpu(p).oper[0]^.val in [1..3]) and
  6890. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6891. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6892. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6893. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6894. MatchOpType(taicpu(hp1),top_ref))
  6895. ) and
  6896. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6897. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6898. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6899. begin
  6900. TransferUsedRegs(TmpUsedRegs);
  6901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6902. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6903. begin
  6904. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6905. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6906. RemoveCurrentP(p);
  6907. Result:=true;
  6908. exit;
  6909. end;
  6910. end;
  6911. if MatchOpType(taicpu(p), top_const, top_reg) and
  6912. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6913. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6914. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6915. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6916. begin
  6917. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6918. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6919. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6920. {$ifdef x86_64}
  6921. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6922. {$endif x86_64}
  6923. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6924. begin
  6925. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6926. taicpu(hp1).opcode:=A_MOV;
  6927. taicpu(hp1).oper[0]^.val:=0;
  6928. end
  6929. else
  6930. begin
  6931. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6932. taicpu(hp1).oper[0]^.val:=shiftval;
  6933. end;
  6934. RemoveCurrentP(p);
  6935. Result:=true;
  6936. exit;
  6937. end;
  6938. end;
  6939. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6940. begin
  6941. case shr_size of
  6942. S_B:
  6943. { No valid combinations }
  6944. Result := False;
  6945. S_W:
  6946. Result := (Shift >= 8) and (movz_size = S_BW);
  6947. S_L:
  6948. Result :=
  6949. (Shift >= 24) { Any opsize is valid for this shift } or
  6950. ((Shift >= 16) and (movz_size = S_WL));
  6951. {$ifdef x86_64}
  6952. S_Q:
  6953. Result :=
  6954. (Shift >= 56) { Any opsize is valid for this shift } or
  6955. ((Shift >= 48) and (movz_size = S_WL));
  6956. {$endif x86_64}
  6957. else
  6958. InternalError(2022081510);
  6959. end;
  6960. end;
  6961. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6962. var
  6963. hp1, hp2: tai;
  6964. Shift: TCGInt;
  6965. LimitSize: Topsize;
  6966. DoNotMerge: Boolean;
  6967. begin
  6968. Result := False;
  6969. { All these optimisations work on "shr const,%reg" }
  6970. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6971. Exit;
  6972. DoNotMerge := False;
  6973. Shift := taicpu(p).oper[0]^.val;
  6974. LimitSize := taicpu(p).opsize;
  6975. hp1 := p;
  6976. repeat
  6977. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6978. Exit;
  6979. case taicpu(hp1).opcode of
  6980. A_TEST, A_CMP, A_Jcc:
  6981. { Skip over conditional jumps and relevant comparisons }
  6982. Continue;
  6983. A_MOVZX:
  6984. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6985. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6986. begin
  6987. { Since the original register is being read as is, subsequent
  6988. SHRs must not be merged at this point }
  6989. DoNotMerge := True;
  6990. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6991. begin
  6992. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6993. begin
  6994. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6995. taicpu(hp1).opcode := A_MOV;
  6996. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6997. case taicpu(hp1).opsize of
  6998. S_BW:
  6999. taicpu(hp1).opsize := S_W;
  7000. S_BL, S_WL:
  7001. taicpu(hp1).opsize := S_L;
  7002. else
  7003. InternalError(2022081503);
  7004. end;
  7005. { p itself hasn't changed, so no need to set Result to True }
  7006. Include(OptsToCheck, aoc_ForceNewIteration);
  7007. { See if there's anything afterwards that can be
  7008. optimised, since the input register hasn't changed }
  7009. Continue;
  7010. end;
  7011. { NOTE: If the MOVZX instruction reads and writes the same
  7012. register, defer this to the post-peephole optimisation stage }
  7013. Exit;
  7014. end;
  7015. end;
  7016. A_SHL, A_SAL, A_SHR:
  7017. if (taicpu(hp1).opsize <= LimitSize) and
  7018. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7019. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7020. begin
  7021. { Make sure the sizes don't exceed the register size limit
  7022. (measured by the shift value falling below the limit) }
  7023. if taicpu(hp1).opsize < LimitSize then
  7024. LimitSize := taicpu(hp1).opsize;
  7025. if taicpu(hp1).opcode = A_SHR then
  7026. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7027. else
  7028. begin
  7029. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7030. DoNotMerge := True;
  7031. end;
  7032. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7033. Exit;
  7034. { Since we've established that the combined shift is within
  7035. limits, we can actually combine the adjacent SHR
  7036. instructions even if they're different sizes }
  7037. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7038. begin
  7039. hp2 := tai(hp1.Previous);
  7040. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7041. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7042. RemoveInstruction(hp1);
  7043. hp1 := hp2;
  7044. { Though p has changed, only the constant has, and its
  7045. effects can still be detected on the next iteration of
  7046. the repeat..until loop }
  7047. Include(OptsToCheck, aoc_ForceNewIteration);
  7048. end;
  7049. { Move onto the next instruction }
  7050. Continue;
  7051. end;
  7052. else
  7053. ;
  7054. end;
  7055. Break;
  7056. until False;
  7057. end;
  7058. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7059. var
  7060. CurrentRef: TReference;
  7061. FullReg: TRegister;
  7062. hp1, hp2: tai;
  7063. begin
  7064. Result := False;
  7065. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7066. Exit;
  7067. { We assume you've checked if the operand is actually a reference by
  7068. this point. If it isn't, you'll most likely get an access violation }
  7069. CurrentRef := first_mov.oper[1]^.ref^;
  7070. { Memory must be aligned }
  7071. if (CurrentRef.offset mod 4) <> 0 then
  7072. Exit;
  7073. Inc(CurrentRef.offset);
  7074. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7075. if MatchOperand(second_mov.oper[0]^, 0) and
  7076. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7077. GetNextInstruction(second_mov, hp1) and
  7078. (hp1.typ = ait_instruction) and
  7079. (taicpu(hp1).opcode = A_MOV) and
  7080. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7081. (taicpu(hp1).oper[0]^.val = 0) then
  7082. begin
  7083. Inc(CurrentRef.offset);
  7084. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7085. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7086. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7087. begin
  7088. case taicpu(hp1).opsize of
  7089. S_B:
  7090. if GetNextInstruction(hp1, hp2) and
  7091. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7092. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7093. (taicpu(hp2).oper[0]^.val = 0) then
  7094. begin
  7095. Inc(CurrentRef.offset);
  7096. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7097. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7098. (taicpu(hp2).opsize = S_B) then
  7099. begin
  7100. RemoveInstruction(hp1);
  7101. RemoveInstruction(hp2);
  7102. first_mov.opsize := S_L;
  7103. if first_mov.oper[0]^.typ = top_reg then
  7104. begin
  7105. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7106. { Reuse second_mov as a MOVZX instruction }
  7107. second_mov.opcode := A_MOVZX;
  7108. second_mov.opsize := S_BL;
  7109. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7110. second_mov.loadreg(1, FullReg);
  7111. first_mov.oper[0]^.reg := FullReg;
  7112. asml.Remove(second_mov);
  7113. asml.InsertBefore(second_mov, first_mov);
  7114. end
  7115. else
  7116. { It's a value }
  7117. begin
  7118. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7119. RemoveInstruction(second_mov);
  7120. end;
  7121. Result := True;
  7122. Exit;
  7123. end;
  7124. end;
  7125. S_W:
  7126. begin
  7127. RemoveInstruction(hp1);
  7128. first_mov.opsize := S_L;
  7129. if first_mov.oper[0]^.typ = top_reg then
  7130. begin
  7131. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7132. { Reuse second_mov as a MOVZX instruction }
  7133. second_mov.opcode := A_MOVZX;
  7134. second_mov.opsize := S_BL;
  7135. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7136. second_mov.loadreg(1, FullReg);
  7137. first_mov.oper[0]^.reg := FullReg;
  7138. asml.Remove(second_mov);
  7139. asml.InsertBefore(second_mov, first_mov);
  7140. end
  7141. else
  7142. { It's a value }
  7143. begin
  7144. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7145. RemoveInstruction(second_mov);
  7146. end;
  7147. Result := True;
  7148. Exit;
  7149. end;
  7150. else
  7151. ;
  7152. end;
  7153. end;
  7154. end;
  7155. end;
  7156. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7157. { returns true if a "continue" should be done after this optimization }
  7158. var
  7159. hp1, hp2, hp3: tai;
  7160. begin
  7161. Result := false;
  7162. hp3 := nil;
  7163. if MatchOpType(taicpu(p),top_ref) and
  7164. GetNextInstruction(p, hp1) and
  7165. (hp1.typ = ait_instruction) and
  7166. (((taicpu(hp1).opcode = A_FLD) and
  7167. (taicpu(p).opcode = A_FSTP)) or
  7168. ((taicpu(p).opcode = A_FISTP) and
  7169. (taicpu(hp1).opcode = A_FILD))) and
  7170. MatchOpType(taicpu(hp1),top_ref) and
  7171. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7172. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7173. begin
  7174. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7175. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7176. GetNextInstruction(hp1, hp2) and
  7177. (((hp2.typ = ait_instruction) and
  7178. IsExitCode(hp2) and
  7179. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7180. not(assigned(current_procinfo.procdef.funcretsym) and
  7181. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7182. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7183. { fstp <temp>
  7184. fld <temp>
  7185. <dealloc> <temp>
  7186. }
  7187. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7188. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7189. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7190. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7191. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7192. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7193. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7194. )
  7195. )
  7196. ) then
  7197. begin
  7198. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7199. RemoveInstruction(hp1);
  7200. RemoveCurrentP(p, hp2);
  7201. { first case: exit code }
  7202. if hp2.typ = ait_instruction then
  7203. RemoveLastDeallocForFuncRes(p);
  7204. Result := true;
  7205. end
  7206. else
  7207. { we can do this only in fast math mode as fstp is rounding ...
  7208. ... still disabled as it breaks the compiler and/or rtl }
  7209. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7210. { ... or if another fstp equal to the first one follows }
  7211. GetNextInstruction(hp1,hp2) and
  7212. (hp2.typ = ait_instruction) and
  7213. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7214. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7215. begin
  7216. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7217. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7218. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7219. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7220. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7221. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7222. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7223. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7224. ) then
  7225. begin
  7226. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7227. RemoveCurrentP(p,hp2);
  7228. RemoveInstruction(hp1);
  7229. Result := true;
  7230. end
  7231. else if { fst can't store an extended/comp value }
  7232. (taicpu(p).opsize <> S_FX) and
  7233. (taicpu(p).opsize <> S_IQ) then
  7234. begin
  7235. if (taicpu(p).opcode = A_FSTP) then
  7236. taicpu(p).opcode := A_FST
  7237. else
  7238. taicpu(p).opcode := A_FIST;
  7239. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7240. RemoveInstruction(hp1);
  7241. Result := true;
  7242. end;
  7243. end;
  7244. end;
  7245. end;
  7246. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7247. var
  7248. hp1, hp2, hp3: tai;
  7249. begin
  7250. result:=false;
  7251. if MatchOpType(taicpu(p),top_reg) and
  7252. GetNextInstruction(p, hp1) and
  7253. (hp1.typ = Ait_Instruction) and
  7254. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7255. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7256. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7257. { change to
  7258. fld reg fxxx reg,st
  7259. fxxxp st, st1 (hp1)
  7260. Remark: non commutative operations must be reversed!
  7261. }
  7262. begin
  7263. case taicpu(hp1).opcode Of
  7264. A_FMULP,A_FADDP,
  7265. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7266. begin
  7267. case taicpu(hp1).opcode Of
  7268. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7269. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7270. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7271. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7272. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7273. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7274. else
  7275. internalerror(2019050534);
  7276. end;
  7277. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7278. taicpu(hp1).oper[1]^.reg := NR_ST;
  7279. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7280. RemoveCurrentP(p, hp1);
  7281. Result:=true;
  7282. exit;
  7283. end;
  7284. else
  7285. ;
  7286. end;
  7287. end
  7288. else
  7289. if MatchOpType(taicpu(p),top_ref) and
  7290. GetNextInstruction(p, hp2) and
  7291. (hp2.typ = Ait_Instruction) and
  7292. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7293. (taicpu(p).opsize in [S_FS, S_FL]) and
  7294. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7295. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7296. if GetLastInstruction(p, hp1) and
  7297. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7298. MatchOpType(taicpu(hp1),top_ref) and
  7299. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7300. if ((taicpu(hp2).opcode = A_FMULP) or
  7301. (taicpu(hp2).opcode = A_FADDP)) then
  7302. { change to
  7303. fld/fst mem1 (hp1) fld/fst mem1
  7304. fld mem1 (p) fadd/
  7305. faddp/ fmul st, st
  7306. fmulp st, st1 (hp2) }
  7307. begin
  7308. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7309. RemoveCurrentP(p, hp1);
  7310. if (taicpu(hp2).opcode = A_FADDP) then
  7311. taicpu(hp2).opcode := A_FADD
  7312. else
  7313. taicpu(hp2).opcode := A_FMUL;
  7314. taicpu(hp2).oper[1]^.reg := NR_ST;
  7315. end
  7316. else
  7317. { change to
  7318. fld/fst mem1 (hp1) fld/fst mem1
  7319. fld mem1 (p) fld st
  7320. }
  7321. begin
  7322. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7323. taicpu(p).changeopsize(S_FL);
  7324. taicpu(p).loadreg(0,NR_ST);
  7325. end
  7326. else
  7327. begin
  7328. case taicpu(hp2).opcode Of
  7329. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7330. { change to
  7331. fld/fst mem1 (hp1) fld/fst mem1
  7332. fld mem2 (p) fxxx mem2
  7333. fxxxp st, st1 (hp2) }
  7334. begin
  7335. case taicpu(hp2).opcode Of
  7336. A_FADDP: taicpu(p).opcode := A_FADD;
  7337. A_FMULP: taicpu(p).opcode := A_FMUL;
  7338. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7339. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7340. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7341. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7342. else
  7343. internalerror(2019050533);
  7344. end;
  7345. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7346. RemoveInstruction(hp2);
  7347. end
  7348. else
  7349. ;
  7350. end
  7351. end
  7352. end;
  7353. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7354. begin
  7355. Result := condition_in(cond1, cond2) or
  7356. { Not strictly subsets due to the actual flags checked, but because we're
  7357. comparing integers, E is a subset of AE and GE and their aliases }
  7358. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7359. end;
  7360. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7361. var
  7362. v: TCGInt;
  7363. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7364. FirstMatch, TempBool: Boolean;
  7365. NewReg: TRegister;
  7366. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7367. begin
  7368. Result:=false;
  7369. { All these optimisations need a next instruction }
  7370. if not GetNextInstruction(p, hp1) then
  7371. Exit;
  7372. true_hp1 := hp1;
  7373. { Search for:
  7374. cmp ###,###
  7375. j(c1) @lbl1
  7376. ...
  7377. @lbl:
  7378. cmp ###,### (same comparison as above)
  7379. j(c2) @lbl2
  7380. If c1 is a subset of c2, change to:
  7381. cmp ###,###
  7382. j(c1) @lbl2
  7383. (@lbl1 may become a dead label as a result)
  7384. }
  7385. { Also handle cases where there are multiple jumps in a row }
  7386. p_jump := hp1;
  7387. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7388. begin
  7389. Prefetch(p_jump.Next);
  7390. if IsJumpToLabel(taicpu(p_jump)) then
  7391. begin
  7392. { Do jump optimisations first in case the condition becomes
  7393. unnecessary }
  7394. TempBool := True;
  7395. if DoJumpOptimizations(p_jump, TempBool) or
  7396. not TempBool then
  7397. begin
  7398. if Assigned(p_jump) then
  7399. begin
  7400. { CollapseZeroDistJump will be set to the label or an align
  7401. before it after the jump if it optimises, whether or not
  7402. the label is live or dead }
  7403. if (p_jump.typ = ait_align) or
  7404. (
  7405. (p_jump.typ = ait_label) and
  7406. not (tai_label(p_jump).labsym.is_used)
  7407. ) then
  7408. GetNextInstruction(p_jump, p_jump);
  7409. end;
  7410. TransferUsedRegs(TmpUsedRegs);
  7411. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7412. if not Assigned(p_jump) or
  7413. (
  7414. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7415. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7416. ) then
  7417. begin
  7418. { No more conditional jumps; conditional statement is no longer required }
  7419. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7420. RemoveCurrentP(p);
  7421. Result := True;
  7422. Exit;
  7423. end;
  7424. hp1 := p_jump;
  7425. Include(OptsToCheck, aoc_ForceNewIteration);
  7426. Continue;
  7427. end;
  7428. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7429. if GetNextInstruction(p_jump, hp2) and
  7430. (
  7431. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7432. not TempBool
  7433. ) then
  7434. begin
  7435. hp1 := p_jump;
  7436. Include(OptsToCheck, aoc_ForceNewIteration);
  7437. Continue;
  7438. end;
  7439. p_label := nil;
  7440. if Assigned(JumpLabel) then
  7441. p_label := getlabelwithsym(JumpLabel);
  7442. if Assigned(p_label) and
  7443. GetNextInstruction(p_label, p_dist) and
  7444. MatchInstruction(p_dist, A_CMP, []) and
  7445. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7446. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7447. GetNextInstruction(p_dist, hp1_dist) and
  7448. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7449. begin
  7450. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7451. if JumpLabel = JumpLabel_dist then
  7452. { This is an infinite loop }
  7453. Exit;
  7454. { Best optimisation when the first condition is a subset (or equal) of the second }
  7455. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7456. begin
  7457. { Any registers used here will already be allocated }
  7458. if Assigned(JumpLabel) then
  7459. JumpLabel.DecRefs;
  7460. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7461. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7462. Include(OptsToCheck, aoc_ForceNewIteration);
  7463. { Don't exit yet. Since p and p_jump haven't actually been
  7464. removed, we can check for more on this iteration }
  7465. end
  7466. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7467. GetNextInstruction(hp1_dist, hp1_label) and
  7468. (hp1_label.typ = ait_label) then
  7469. begin
  7470. JumpLabel_far := tai_label(hp1_label).labsym;
  7471. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7472. { This is an infinite loop }
  7473. Exit;
  7474. if Assigned(JumpLabel_far) then
  7475. begin
  7476. { In this situation, if the first jump branches, the second one will never,
  7477. branch so change the destination label to after the second jump }
  7478. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7479. if Assigned(JumpLabel) then
  7480. JumpLabel.DecRefs;
  7481. JumpLabel_far.IncRefs;
  7482. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7483. Result := True;
  7484. { Don't exit yet. Since p and p_jump haven't actually been
  7485. removed, we can check for more on this iteration }
  7486. Continue;
  7487. end;
  7488. end;
  7489. end;
  7490. end;
  7491. { Search for:
  7492. cmp ###,###
  7493. j(c1) @lbl1
  7494. cmp ###,### (same as first)
  7495. Remove second cmp
  7496. }
  7497. if GetNextInstruction(p_jump, hp2) and
  7498. (
  7499. (
  7500. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7501. (
  7502. (
  7503. MatchOpType(taicpu(p), top_const, top_reg) and
  7504. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7505. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7506. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7507. ) or (
  7508. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7509. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7510. )
  7511. )
  7512. ) or (
  7513. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7514. MatchOperand(taicpu(p).oper[0]^, 0) and
  7515. (taicpu(p).oper[1]^.typ = top_reg) and
  7516. MatchInstruction(hp2, A_TEST, []) and
  7517. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7518. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7519. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7520. )
  7521. ) then
  7522. begin
  7523. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7524. TransferUsedRegs(TmpUsedRegs);
  7525. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7526. RemoveInstruction(hp2);
  7527. Result := True;
  7528. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7529. end
  7530. else
  7531. begin
  7532. { hp2 is the next instruction, so save time and just set p_jump
  7533. to it instead of calling GetNextInstruction below }
  7534. p_jump := hp2;
  7535. Continue;
  7536. end;
  7537. GetNextInstruction(p_jump, p_jump);
  7538. end;
  7539. if (
  7540. { Don't call GetNextInstruction again if we already have it }
  7541. (true_hp1 = p_jump) or
  7542. GetNextInstruction(p, hp1)
  7543. ) and
  7544. MatchInstruction(hp1, A_Jcc, []) and
  7545. IsJumpToLabel(taicpu(hp1)) and
  7546. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7547. GetNextInstruction(hp1, hp2) then
  7548. begin
  7549. {
  7550. cmp x, y (or "cmp y, x")
  7551. je @lbl
  7552. mov x, y
  7553. @lbl:
  7554. (x and y can be constants, registers or references)
  7555. Change to:
  7556. mov x, y (x and y will always be equal in the end)
  7557. @lbl: (may beceome a dead label)
  7558. Also:
  7559. cmp x, y (or "cmp y, x")
  7560. jne @lbl
  7561. mov x, y
  7562. @lbl:
  7563. (x and y can be constants, registers or references)
  7564. Change to:
  7565. Absolutely nothing! (Except @lbl if it's still live)
  7566. }
  7567. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7568. (
  7569. (
  7570. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7571. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7572. ) or (
  7573. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7574. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7575. )
  7576. ) and
  7577. GetNextInstruction(hp2, hp1_label) and
  7578. (hp1_label.typ = ait_label) and
  7579. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7580. begin
  7581. tai_label(hp1_label).labsym.DecRefs;
  7582. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7583. begin
  7584. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7585. RemoveInstruction(hp2);
  7586. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7587. end
  7588. else
  7589. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7590. RemoveInstruction(hp1);
  7591. RemoveCurrentp(p, hp2);
  7592. Result := True;
  7593. Exit;
  7594. end;
  7595. {
  7596. Try to optimise the following:
  7597. cmp $x,### ($x and $y can be registers or constants)
  7598. je @lbl1 (only reference)
  7599. cmp $y,### (### are identical)
  7600. @Lbl:
  7601. sete %reg1
  7602. Change to:
  7603. cmp $x,###
  7604. sete %reg2 (allocate new %reg2)
  7605. cmp $y,###
  7606. sete %reg1
  7607. orb %reg2,%reg1
  7608. (dealloc %reg2)
  7609. This adds an instruction (so don't perform under -Os), but it removes
  7610. a conditional branch.
  7611. }
  7612. if not (cs_opt_size in current_settings.optimizerswitches) and
  7613. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7614. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7615. { The first operand of CMP instructions can only be a register or
  7616. immediate anyway, so no need to check }
  7617. GetNextInstruction(hp2, p_label) and
  7618. (p_label.typ = ait_label) and
  7619. (tai_label(p_label).labsym.getrefs = 1) and
  7620. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7621. GetNextInstruction(p_label, p_dist) and
  7622. MatchInstruction(p_dist, A_SETcc, []) and
  7623. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7624. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7625. begin
  7626. TransferUsedRegs(TmpUsedRegs);
  7627. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7628. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7629. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7630. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7631. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7632. { Get the instruction after the SETcc instruction so we can
  7633. allocate a new register over the entire range }
  7634. GetNextInstruction(p_dist, hp1_dist) then
  7635. begin
  7636. { Register can appear in p if it's not used afterwards, so only
  7637. allocate between hp1 and hp1_dist }
  7638. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7639. if NewReg <> NR_NO then
  7640. begin
  7641. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7642. { Change the jump instruction into a SETcc instruction }
  7643. taicpu(hp1).opcode := A_SETcc;
  7644. taicpu(hp1).opsize := S_B;
  7645. taicpu(hp1).loadreg(0, NewReg);
  7646. { This is now a dead label }
  7647. tai_label(p_label).labsym.decrefs;
  7648. { Prefer adding before the next instruction so the FLAGS
  7649. register is deallicated first }
  7650. AsmL.InsertBefore(
  7651. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7652. hp1_dist
  7653. );
  7654. Result := True;
  7655. { Don't exit yet, as p wasn't changed and hp1, while
  7656. modified, is still intact and might be optimised by the
  7657. SETcc optimisation below }
  7658. end;
  7659. end;
  7660. end;
  7661. end;
  7662. if (taicpu(p).oper[0]^.typ = top_const) and
  7663. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7664. begin
  7665. if (taicpu(p).oper[0]^.val = 0) and
  7666. (taicpu(p).oper[1]^.typ = top_reg) then
  7667. begin
  7668. hp2 := p;
  7669. FirstMatch := True;
  7670. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7671. anything meaningful once it's converted to "test %reg,%reg";
  7672. additionally, some jumps will always (or never) branch, so
  7673. evaluate every jump immediately following the
  7674. comparison, optimising the conditions if possible.
  7675. Similarly with SETcc... those that are always set to 0 or 1
  7676. are changed to MOV instructions }
  7677. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7678. (
  7679. GetNextInstruction(hp2, hp1) and
  7680. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7681. ) do
  7682. begin
  7683. Prefetch(hp1.Next);
  7684. FirstMatch := False;
  7685. case taicpu(hp1).condition of
  7686. C_B, C_C, C_NAE, C_O:
  7687. { For B/NAE:
  7688. Will never branch since an unsigned integer can never be below zero
  7689. For C/O:
  7690. Result cannot overflow because 0 is being subtracted
  7691. }
  7692. begin
  7693. if taicpu(hp1).opcode = A_Jcc then
  7694. begin
  7695. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7696. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7697. RemoveInstruction(hp1);
  7698. { Since hp1 was deleted, hp2 must not be updated }
  7699. Continue;
  7700. end
  7701. else
  7702. begin
  7703. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7704. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7705. taicpu(hp1).opcode := A_MOV;
  7706. taicpu(hp1).ops := 2;
  7707. taicpu(hp1).condition := C_None;
  7708. taicpu(hp1).opsize := S_B;
  7709. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7710. taicpu(hp1).loadconst(0, 0);
  7711. end;
  7712. end;
  7713. C_BE, C_NA:
  7714. begin
  7715. { Will only branch if equal to zero }
  7716. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7717. taicpu(hp1).condition := C_E;
  7718. end;
  7719. C_A, C_NBE:
  7720. begin
  7721. { Will only branch if not equal to zero }
  7722. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7723. taicpu(hp1).condition := C_NE;
  7724. end;
  7725. C_AE, C_NB, C_NC, C_NO:
  7726. begin
  7727. { Will always branch }
  7728. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7729. if taicpu(hp1).opcode = A_Jcc then
  7730. begin
  7731. MakeUnconditional(taicpu(hp1));
  7732. { Any jumps/set that follow will now be dead code }
  7733. RemoveDeadCodeAfterJump(taicpu(hp1));
  7734. Break;
  7735. end
  7736. else
  7737. begin
  7738. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7739. taicpu(hp1).opcode := A_MOV;
  7740. taicpu(hp1).ops := 2;
  7741. taicpu(hp1).condition := C_None;
  7742. taicpu(hp1).opsize := S_B;
  7743. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7744. taicpu(hp1).loadconst(0, 1);
  7745. end;
  7746. end;
  7747. C_None:
  7748. InternalError(2020012201);
  7749. C_P, C_PE, C_NP, C_PO:
  7750. { We can't handle parity checks and they should never be generated
  7751. after a general-purpose CMP (it's used in some floating-point
  7752. comparisons that don't use CMP) }
  7753. InternalError(2020012202);
  7754. else
  7755. { Zero/Equality, Sign, their complements and all of the
  7756. signed comparisons do not need to be converted };
  7757. end;
  7758. hp2 := hp1;
  7759. end;
  7760. { Convert the instruction to a TEST }
  7761. taicpu(p).opcode := A_TEST;
  7762. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7763. Result := True;
  7764. Exit;
  7765. end
  7766. else
  7767. begin
  7768. TransferUsedRegs(TmpUsedRegs);
  7769. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7770. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7771. begin
  7772. if (taicpu(p).oper[0]^.val = 1) and
  7773. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7774. begin
  7775. { Convert; To:
  7776. cmp $1,r/m cmp $0,r/m
  7777. jl @lbl jle @lbl
  7778. (Also do inverted conditions)
  7779. }
  7780. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7781. taicpu(p).oper[0]^.val := 0;
  7782. if taicpu(hp1).condition in [C_L, C_NGE] then
  7783. taicpu(hp1).condition := C_LE
  7784. else
  7785. taicpu(hp1).condition := C_NLE;
  7786. { If the instruction is now "cmp $0,%reg", convert it to a
  7787. TEST (and effectively do the work of the "cmp $0,%reg" in
  7788. the block above)
  7789. }
  7790. if (taicpu(p).oper[1]^.typ = top_reg) then
  7791. begin
  7792. taicpu(p).opcode := A_TEST;
  7793. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7794. end;
  7795. Result := True;
  7796. Exit;
  7797. end
  7798. else if (taicpu(p).oper[1]^.typ = top_reg)
  7799. {$ifdef x86_64}
  7800. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7801. {$endif x86_64}
  7802. then
  7803. begin
  7804. { cmp register,$8000 neg register
  7805. je target --> jo target
  7806. .... only if register is deallocated before jump.}
  7807. case Taicpu(p).opsize of
  7808. S_B: v:=$80;
  7809. S_W: v:=$8000;
  7810. S_L: v:=qword($80000000);
  7811. else
  7812. internalerror(2013112905);
  7813. end;
  7814. if (taicpu(p).oper[0]^.val=v) and
  7815. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7816. begin
  7817. TransferUsedRegs(TmpUsedRegs);
  7818. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7819. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7820. begin
  7821. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7822. Taicpu(p).opcode:=A_NEG;
  7823. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7824. Taicpu(p).clearop(1);
  7825. Taicpu(p).ops:=1;
  7826. if Taicpu(hp1).condition=C_E then
  7827. Taicpu(hp1).condition:=C_O
  7828. else
  7829. Taicpu(hp1).condition:=C_NO;
  7830. Result:=true;
  7831. exit;
  7832. end;
  7833. end;
  7834. end;
  7835. end;
  7836. end;
  7837. end;
  7838. if TrySwapMovCmp(p, hp1) then
  7839. begin
  7840. Result := True;
  7841. Exit;
  7842. end;
  7843. end;
  7844. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7845. var
  7846. hp1: tai;
  7847. begin
  7848. {
  7849. remove the second (v)pxor from
  7850. pxor reg,reg
  7851. ...
  7852. pxor reg,reg
  7853. }
  7854. Result:=false;
  7855. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7856. MatchOpType(taicpu(p),top_reg,top_reg) and
  7857. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7858. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7859. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7860. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7861. begin
  7862. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7863. RemoveInstruction(hp1);
  7864. Result:=true;
  7865. Exit;
  7866. end
  7867. {
  7868. replace
  7869. pxor reg1,reg1
  7870. movapd/s reg1,reg2
  7871. dealloc reg1
  7872. by
  7873. pxor reg2,reg2
  7874. }
  7875. else if GetNextInstruction(p,hp1) and
  7876. { we mix single and double opperations here because we assume that the compiler
  7877. generates vmovapd only after double operations and vmovaps only after single operations }
  7878. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7879. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7880. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7881. (taicpu(p).oper[0]^.typ=top_reg) then
  7882. begin
  7883. TransferUsedRegs(TmpUsedRegs);
  7884. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7885. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7886. begin
  7887. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7888. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7889. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7890. RemoveInstruction(hp1);
  7891. result:=true;
  7892. end;
  7893. end;
  7894. end;
  7895. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7896. var
  7897. hp1: tai;
  7898. begin
  7899. {
  7900. remove the second (v)pxor from
  7901. (v)pxor reg,reg
  7902. ...
  7903. (v)pxor reg,reg
  7904. }
  7905. Result:=false;
  7906. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7907. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7908. begin
  7909. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7910. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7911. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7912. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7913. begin
  7914. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7915. RemoveInstruction(hp1);
  7916. Result:=true;
  7917. Exit;
  7918. end;
  7919. {$ifdef x86_64}
  7920. {
  7921. replace
  7922. vpxor reg1,reg1,reg1
  7923. vmov reg,mem
  7924. by
  7925. movq $0,mem
  7926. }
  7927. if GetNextInstruction(p,hp1) and
  7928. MatchInstruction(hp1,A_VMOVSD,[]) and
  7929. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7930. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7931. begin
  7932. TransferUsedRegs(TmpUsedRegs);
  7933. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7934. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7935. begin
  7936. taicpu(hp1).loadconst(0,0);
  7937. taicpu(hp1).opcode:=A_MOV;
  7938. taicpu(hp1).opsize:=S_Q;
  7939. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7940. RemoveCurrentP(p);
  7941. result:=true;
  7942. Exit;
  7943. end;
  7944. end;
  7945. {$endif x86_64}
  7946. end
  7947. {
  7948. replace
  7949. vpxor reg1,reg1,reg2
  7950. by
  7951. vpxor reg2,reg2,reg2
  7952. to avoid unncessary data dependencies
  7953. }
  7954. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7955. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7956. begin
  7957. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7958. { avoid unncessary data dependency }
  7959. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7960. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7961. result:=true;
  7962. exit;
  7963. end;
  7964. Result:=OptPass1VOP(p);
  7965. end;
  7966. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7967. var
  7968. hp1 : tai;
  7969. begin
  7970. result:=false;
  7971. { replace
  7972. IMul const,%mreg1,%mreg2
  7973. Mov %reg2,%mreg3
  7974. dealloc %mreg3
  7975. by
  7976. Imul const,%mreg1,%mreg23
  7977. }
  7978. if (taicpu(p).ops=3) and
  7979. GetNextInstruction(p,hp1) and
  7980. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7981. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7982. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7983. begin
  7984. TransferUsedRegs(TmpUsedRegs);
  7985. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7986. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7987. begin
  7988. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7989. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7990. RemoveInstruction(hp1);
  7991. result:=true;
  7992. end;
  7993. end;
  7994. end;
  7995. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7996. var
  7997. hp1 : tai;
  7998. begin
  7999. result:=false;
  8000. { replace
  8001. IMul %reg0,%reg1,%reg2
  8002. Mov %reg2,%reg3
  8003. dealloc %reg2
  8004. by
  8005. Imul %reg0,%reg1,%reg3
  8006. }
  8007. if GetNextInstruction(p,hp1) and
  8008. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8009. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8010. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8011. begin
  8012. TransferUsedRegs(TmpUsedRegs);
  8013. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8014. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8015. begin
  8016. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8017. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8018. RemoveInstruction(hp1);
  8019. result:=true;
  8020. end;
  8021. end;
  8022. end;
  8023. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8024. var
  8025. hp1: tai;
  8026. begin
  8027. Result:=false;
  8028. { get rid of
  8029. (v)cvtss2sd reg0,<reg1,>reg2
  8030. (v)cvtss2sd reg2,<reg2,>reg0
  8031. }
  8032. if GetNextInstruction(p,hp1) and
  8033. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8034. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8035. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8036. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8037. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8038. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8039. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8040. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8041. )
  8042. ) then
  8043. begin
  8044. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8045. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8046. begin
  8047. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8048. RemoveCurrentP(p);
  8049. RemoveInstruction(hp1);
  8050. end
  8051. else
  8052. begin
  8053. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8054. if taicpu(hp1).opcode=A_CVTSD2SS then
  8055. begin
  8056. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8057. taicpu(p).opcode:=A_MOVAPS;
  8058. end
  8059. else
  8060. begin
  8061. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8062. taicpu(p).opcode:=A_VMOVAPS;
  8063. end;
  8064. taicpu(p).ops:=2;
  8065. RemoveInstruction(hp1);
  8066. end;
  8067. Result:=true;
  8068. Exit;
  8069. end;
  8070. end;
  8071. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8072. var
  8073. hp1, hp2, hp3, hp4, hp5: tai;
  8074. ThisReg: TRegister;
  8075. begin
  8076. Result := False;
  8077. if not GetNextInstruction(p,hp1) then
  8078. Exit;
  8079. {
  8080. convert
  8081. j<c> .L1
  8082. mov 1,reg
  8083. jmp .L2
  8084. .L1
  8085. mov 0,reg
  8086. .L2
  8087. into
  8088. mov 0,reg
  8089. set<not(c)> reg
  8090. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8091. would destroy the flag contents
  8092. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8093. executed at the same time as a previous comparison.
  8094. set<not(c)> reg
  8095. movzx reg, reg
  8096. }
  8097. if MatchInstruction(hp1,A_MOV,[]) and
  8098. (taicpu(hp1).oper[0]^.typ = top_const) and
  8099. (
  8100. (
  8101. (taicpu(hp1).oper[1]^.typ = top_reg)
  8102. {$ifdef i386}
  8103. { Under i386, ESI, EDI, EBP and ESP
  8104. don't have an 8-bit representation }
  8105. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8106. {$endif i386}
  8107. ) or (
  8108. {$ifdef i386}
  8109. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8110. {$endif i386}
  8111. (taicpu(hp1).opsize = S_B)
  8112. )
  8113. ) and
  8114. GetNextInstruction(hp1,hp2) and
  8115. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8116. GetNextInstruction(hp2,hp3) and
  8117. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8118. GetNextInstruction(hp3,hp4) and
  8119. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8120. (taicpu(hp4).oper[0]^.typ = top_const) and
  8121. (
  8122. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8123. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8124. ) and
  8125. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8126. GetNextInstruction(hp4,hp5) and
  8127. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8128. begin
  8129. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8130. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8131. tai_label(hp3).labsym.DecRefs;
  8132. { If this isn't the only reference to the middle label, we can
  8133. still make a saving - only that the first jump and everything
  8134. that follows will remain. }
  8135. if (tai_label(hp3).labsym.getrefs = 0) then
  8136. begin
  8137. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8138. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8139. else
  8140. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8141. { remove jump, first label and second MOV (also catching any aligns) }
  8142. repeat
  8143. if not GetNextInstruction(hp2, hp3) then
  8144. InternalError(2021040810);
  8145. RemoveInstruction(hp2);
  8146. hp2 := hp3;
  8147. until hp2 = hp5;
  8148. { Don't decrement reference count before the removal loop
  8149. above, otherwise GetNextInstruction won't stop on the
  8150. the label }
  8151. tai_label(hp5).labsym.DecRefs;
  8152. end
  8153. else
  8154. begin
  8155. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8156. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8157. else
  8158. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8159. end;
  8160. taicpu(p).opcode:=A_SETcc;
  8161. taicpu(p).opsize:=S_B;
  8162. taicpu(p).is_jmp:=False;
  8163. if taicpu(hp1).opsize=S_B then
  8164. begin
  8165. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8166. if taicpu(hp1).oper[1]^.typ = top_reg then
  8167. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8168. RemoveInstruction(hp1);
  8169. end
  8170. else
  8171. begin
  8172. { Will be a register because the size can't be S_B otherwise }
  8173. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8174. taicpu(p).loadreg(0, ThisReg);
  8175. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8176. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8177. begin
  8178. case taicpu(hp1).opsize of
  8179. S_W:
  8180. taicpu(hp1).opsize := S_BW;
  8181. S_L:
  8182. taicpu(hp1).opsize := S_BL;
  8183. {$ifdef x86_64}
  8184. S_Q:
  8185. begin
  8186. taicpu(hp1).opsize := S_BL;
  8187. { Change the destination register to 32-bit }
  8188. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8189. end;
  8190. {$endif x86_64}
  8191. else
  8192. InternalError(2021040820);
  8193. end;
  8194. taicpu(hp1).opcode := A_MOVZX;
  8195. taicpu(hp1).loadreg(0, ThisReg);
  8196. end
  8197. else
  8198. begin
  8199. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8200. { hp1 is already a MOV instruction with the correct register }
  8201. taicpu(hp1).loadconst(0, 0);
  8202. { Inserting it right before p will guarantee that the flags are also tracked }
  8203. asml.Remove(hp1);
  8204. asml.InsertBefore(hp1, p);
  8205. end;
  8206. end;
  8207. Result:=true;
  8208. exit;
  8209. end
  8210. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8211. Result := TryJccStcClcOpt(p, hp1)
  8212. else if (hp1.typ = ait_label) then
  8213. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8214. end;
  8215. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8216. var
  8217. hp1, hp2, hp3: tai;
  8218. SourceRef, TargetRef: TReference;
  8219. CurrentReg: TRegister;
  8220. begin
  8221. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8222. if not UseAVX then
  8223. InternalError(2021100501);
  8224. Result := False;
  8225. { Look for the following to simplify:
  8226. vmovdqa/u x(mem1), %xmmreg
  8227. vmovdqa/u %xmmreg, y(mem2)
  8228. vmovdqa/u x+16(mem1), %xmmreg
  8229. vmovdqa/u %xmmreg, y+16(mem2)
  8230. Change to:
  8231. vmovdqa/u x(mem1), %ymmreg
  8232. vmovdqa/u %ymmreg, y(mem2)
  8233. vpxor %ymmreg, %ymmreg, %ymmreg
  8234. ( The VPXOR instruction is to zero the upper half, thus removing the
  8235. need to call the potentially expensive VZEROUPPER instruction. Other
  8236. peephole optimisations can remove VPXOR if it's unnecessary )
  8237. }
  8238. TransferUsedRegs(TmpUsedRegs);
  8239. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8240. { NOTE: In the optimisations below, if the references dictate that an
  8241. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8242. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8243. if (taicpu(p).opsize = S_XMM) and
  8244. MatchOpType(taicpu(p), top_ref, top_reg) and
  8245. GetNextInstruction(p, hp1) and
  8246. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8247. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8248. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8249. begin
  8250. SourceRef := taicpu(p).oper[0]^.ref^;
  8251. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8252. if GetNextInstruction(hp1, hp2) and
  8253. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8254. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8255. begin
  8256. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8257. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8258. Inc(SourceRef.offset, 16);
  8259. { Reuse the register in the first block move }
  8260. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8261. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8262. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8263. begin
  8264. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8265. Inc(TargetRef.offset, 16);
  8266. if GetNextInstruction(hp2, hp3) and
  8267. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8268. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8269. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8270. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8271. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8272. begin
  8273. { Update the register tracking to the new size }
  8274. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8275. { Remember that the offsets are 16 ahead }
  8276. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8277. if not (
  8278. ((SourceRef.offset mod 32) = 16) and
  8279. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8280. ) then
  8281. taicpu(p).opcode := A_VMOVDQU;
  8282. taicpu(p).opsize := S_YMM;
  8283. taicpu(p).oper[1]^.reg := CurrentReg;
  8284. if not (
  8285. ((TargetRef.offset mod 32) = 16) and
  8286. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8287. ) then
  8288. taicpu(hp1).opcode := A_VMOVDQU;
  8289. taicpu(hp1).opsize := S_YMM;
  8290. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8291. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8292. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8293. if (pi_uses_ymm in current_procinfo.flags) then
  8294. RemoveInstruction(hp2)
  8295. else
  8296. begin
  8297. taicpu(hp2).opcode := A_VPXOR;
  8298. taicpu(hp2).opsize := S_YMM;
  8299. taicpu(hp2).loadreg(0, CurrentReg);
  8300. taicpu(hp2).loadreg(1, CurrentReg);
  8301. taicpu(hp2).loadreg(2, CurrentReg);
  8302. taicpu(hp2).ops := 3;
  8303. end;
  8304. RemoveInstruction(hp3);
  8305. Result := True;
  8306. Exit;
  8307. end;
  8308. end
  8309. else
  8310. begin
  8311. { See if the next references are 16 less rather than 16 greater }
  8312. Dec(SourceRef.offset, 32); { -16 the other way }
  8313. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8314. begin
  8315. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8316. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8317. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8318. GetNextInstruction(hp2, hp3) and
  8319. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8320. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8321. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8322. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8323. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8324. begin
  8325. { Update the register tracking to the new size }
  8326. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8327. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8328. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8329. if not(
  8330. ((SourceRef.offset mod 32) = 0) and
  8331. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8332. ) then
  8333. taicpu(hp2).opcode := A_VMOVDQU;
  8334. taicpu(hp2).opsize := S_YMM;
  8335. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8336. if not (
  8337. ((TargetRef.offset mod 32) = 0) and
  8338. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8339. ) then
  8340. taicpu(hp3).opcode := A_VMOVDQU;
  8341. taicpu(hp3).opsize := S_YMM;
  8342. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8343. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8344. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8345. if (pi_uses_ymm in current_procinfo.flags) then
  8346. RemoveInstruction(hp1)
  8347. else
  8348. begin
  8349. taicpu(hp1).opcode := A_VPXOR;
  8350. taicpu(hp1).opsize := S_YMM;
  8351. taicpu(hp1).loadreg(0, CurrentReg);
  8352. taicpu(hp1).loadreg(1, CurrentReg);
  8353. taicpu(hp1).loadreg(2, CurrentReg);
  8354. taicpu(hp1).ops := 3;
  8355. Asml.Remove(hp1);
  8356. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8357. end;
  8358. RemoveCurrentP(p, hp2);
  8359. Result := True;
  8360. Exit;
  8361. end;
  8362. end;
  8363. end;
  8364. end;
  8365. end;
  8366. end;
  8367. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8368. var
  8369. hp2, hp3, first_assignment: tai;
  8370. IncCount, OperIdx: Integer;
  8371. OrigLabel: TAsmLabel;
  8372. begin
  8373. Count := 0;
  8374. Result := False;
  8375. first_assignment := nil;
  8376. if (LoopCount >= 20) then
  8377. begin
  8378. { Guard against infinite loops }
  8379. Exit;
  8380. end;
  8381. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8382. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8383. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8384. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8385. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8386. Exit;
  8387. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8388. {
  8389. change
  8390. jmp .L1
  8391. ...
  8392. .L1:
  8393. mov ##, ## ( multiple movs possible )
  8394. jmp/ret
  8395. into
  8396. mov ##, ##
  8397. jmp/ret
  8398. }
  8399. if not Assigned(hp1) then
  8400. begin
  8401. hp1 := GetLabelWithSym(OrigLabel);
  8402. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8403. Exit;
  8404. end;
  8405. hp2 := hp1;
  8406. while Assigned(hp2) do
  8407. begin
  8408. if Assigned(hp2) and (hp2.typ = ait_label) then
  8409. SkipLabels(hp2,hp2);
  8410. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8411. Break;
  8412. case taicpu(hp2).opcode of
  8413. A_MOVSD:
  8414. begin
  8415. if taicpu(hp2).ops = 0 then
  8416. { Wrong MOVSD }
  8417. Break;
  8418. Inc(Count);
  8419. if Count >= 5 then
  8420. { Too many to be worthwhile }
  8421. Break;
  8422. GetNextInstruction(hp2, hp2);
  8423. Continue;
  8424. end;
  8425. A_MOV,
  8426. A_MOVD,
  8427. A_MOVQ,
  8428. A_MOVSX,
  8429. {$ifdef x86_64}
  8430. A_MOVSXD,
  8431. {$endif x86_64}
  8432. A_MOVZX,
  8433. A_MOVAPS,
  8434. A_MOVUPS,
  8435. A_MOVSS,
  8436. A_MOVAPD,
  8437. A_MOVUPD,
  8438. A_MOVDQA,
  8439. A_MOVDQU,
  8440. A_VMOVSS,
  8441. A_VMOVAPS,
  8442. A_VMOVUPS,
  8443. A_VMOVSD,
  8444. A_VMOVAPD,
  8445. A_VMOVUPD,
  8446. A_VMOVDQA,
  8447. A_VMOVDQU:
  8448. begin
  8449. Inc(Count);
  8450. if Count >= 5 then
  8451. { Too many to be worthwhile }
  8452. Break;
  8453. GetNextInstruction(hp2, hp2);
  8454. Continue;
  8455. end;
  8456. A_JMP:
  8457. begin
  8458. { Guard against infinite loops }
  8459. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8460. Exit;
  8461. { Analyse this jump first in case it also duplicates assignments }
  8462. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8463. begin
  8464. { Something did change! }
  8465. Result := True;
  8466. Inc(Count, IncCount);
  8467. if Count >= 5 then
  8468. begin
  8469. { Too many to be worthwhile }
  8470. Exit;
  8471. end;
  8472. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8473. Break;
  8474. end;
  8475. Result := True;
  8476. Break;
  8477. end;
  8478. A_RET:
  8479. begin
  8480. Result := True;
  8481. Break;
  8482. end;
  8483. else
  8484. Break;
  8485. end;
  8486. end;
  8487. if Result then
  8488. begin
  8489. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8490. if Count = 0 then
  8491. begin
  8492. Result := False;
  8493. Exit;
  8494. end;
  8495. TransferUsedRegs(TmpUsedRegs);
  8496. hp3 := p;
  8497. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8498. while True do
  8499. begin
  8500. if Assigned(hp1) and (hp1.typ = ait_label) then
  8501. SkipLabels(hp1,hp1);
  8502. case hp1.typ of
  8503. ait_regalloc:
  8504. if tai_regalloc(hp1).ratype = ra_dealloc then
  8505. begin
  8506. { Duplicate the register deallocation... }
  8507. hp3:=tai(hp1.getcopy);
  8508. if first_assignment = nil then
  8509. first_assignment := hp3;
  8510. asml.InsertBefore(hp3, p);
  8511. { ... but also reallocate it after the jump }
  8512. hp3:=tai(hp1.getcopy);
  8513. tai_regalloc(hp3).ratype := ra_alloc;
  8514. asml.InsertAfter(hp3, p);
  8515. end;
  8516. ait_instruction:
  8517. case taicpu(hp1).opcode of
  8518. A_JMP:
  8519. begin
  8520. { Change the original jump to the new destination }
  8521. OrigLabel.decrefs;
  8522. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8523. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8524. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8525. if not Assigned(first_assignment) then
  8526. InternalError(2021040810)
  8527. else
  8528. p := first_assignment;
  8529. Exit;
  8530. end;
  8531. A_RET:
  8532. begin
  8533. { Now change the jump into a RET instruction }
  8534. ConvertJumpToRET(p, hp1);
  8535. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8536. if not Assigned(first_assignment) then
  8537. InternalError(2021040811)
  8538. else
  8539. p := first_assignment;
  8540. Exit;
  8541. end;
  8542. else
  8543. begin
  8544. { Duplicate the MOV instruction }
  8545. hp3:=tai(hp1.getcopy);
  8546. if first_assignment = nil then
  8547. first_assignment := hp3;
  8548. asml.InsertBefore(hp3, p);
  8549. { Make sure the compiler knows about any final registers written here }
  8550. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8551. with taicpu(hp3).oper[OperIdx]^ do
  8552. begin
  8553. case typ of
  8554. top_ref:
  8555. begin
  8556. if (ref^.base <> NR_NO) and
  8557. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8558. (
  8559. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8560. (
  8561. { Allow the frame pointer if it's not being used by the procedure as such }
  8562. Assigned(current_procinfo) and
  8563. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8564. )
  8565. )
  8566. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8567. then
  8568. begin
  8569. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8570. if not Assigned(first_assignment) then
  8571. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8572. end;
  8573. if (ref^.index <> NR_NO) and
  8574. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8575. (
  8576. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8577. (
  8578. { Allow the frame pointer if it's not being used by the procedure as such }
  8579. Assigned(current_procinfo) and
  8580. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8581. )
  8582. )
  8583. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8584. (ref^.index <> ref^.base) then
  8585. begin
  8586. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8587. if not Assigned(first_assignment) then
  8588. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8589. end;
  8590. end;
  8591. top_reg:
  8592. begin
  8593. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8594. if not Assigned(first_assignment) then
  8595. IncludeRegInUsedRegs(reg, UsedRegs);
  8596. end;
  8597. else
  8598. ;
  8599. end;
  8600. end;
  8601. end;
  8602. end;
  8603. else
  8604. InternalError(2021040720);
  8605. end;
  8606. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8607. { Should have dropped out earlier }
  8608. InternalError(2021040710);
  8609. end;
  8610. end;
  8611. end;
  8612. const
  8613. WriteOp: array[0..3] of set of TInsChange = (
  8614. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8615. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8616. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8617. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8618. RegWriteFlags: array[0..7] of set of TInsChange = (
  8619. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8620. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8621. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8622. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8623. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8624. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8625. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8626. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8627. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8628. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8629. var
  8630. hp2: tai;
  8631. X: Integer;
  8632. begin
  8633. { If we have something like:
  8634. op ###,###
  8635. mov ###,###
  8636. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8637. interfere in regards to what they write to.
  8638. NOTE: p must be a 2-operand instruction
  8639. }
  8640. Result := False;
  8641. if (hp1.typ <> ait_instruction) or
  8642. taicpu(hp1).is_jmp or
  8643. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8644. Exit;
  8645. { NOP is a pipeline fence, likely marking the beginning of the function
  8646. epilogue, so drop out. Similarly, drop out if POP or RET are
  8647. encountered }
  8648. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8649. Exit;
  8650. if (taicpu(hp1).opcode = A_MOVSD) and
  8651. (taicpu(hp1).ops = 0) then
  8652. { Wrong MOVSD }
  8653. Exit;
  8654. { Check for writes to specific registers first }
  8655. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8656. for X := 0 to 7 do
  8657. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8658. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8659. Exit;
  8660. for X := 0 to taicpu(hp1).ops - 1 do
  8661. begin
  8662. { Check to see if this operand writes to something }
  8663. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8664. { And matches something in the CMP/TEST instruction }
  8665. (
  8666. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8667. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8668. (
  8669. { If it's a register, make sure the register written to doesn't
  8670. appear in the cmp instruction as part of a reference }
  8671. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8672. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8673. )
  8674. ) then
  8675. Exit;
  8676. end;
  8677. { Check p to make sure it doesn't write to something that affects hp1 }
  8678. { Check for writes to specific registers first }
  8679. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8680. for X := 0 to 7 do
  8681. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8682. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8683. Exit;
  8684. for X := 0 to taicpu(p).ops - 1 do
  8685. begin
  8686. { Check to see if this operand writes to something }
  8687. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8688. { And matches something in hp1 }
  8689. (taicpu(p).oper[X]^.typ = top_reg) and
  8690. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8691. Exit;
  8692. end;
  8693. { The instruction can be safely moved }
  8694. asml.Remove(hp1);
  8695. { Try to insert after the last instructions where the FLAGS register is not
  8696. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8697. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8698. asml.InsertBefore(hp1, hp2)
  8699. { Failing that, try to insert after the last instructions where the
  8700. FLAGS register is not yet in use }
  8701. else if GetLastInstruction(p, hp2) and
  8702. (
  8703. (hp2.typ <> ait_instruction) or
  8704. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8705. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8706. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8707. ) then
  8708. asml.InsertAfter(hp1, hp2)
  8709. else
  8710. { Note, if p.Previous is nil (even if it should logically never be the
  8711. case), FindRegAllocBackward immediately exits with False and so we
  8712. safely land here (we can't just pass p because FindRegAllocBackward
  8713. immediately exits on an instruction). [Kit] }
  8714. asml.InsertBefore(hp1, p);
  8715. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8716. { We can't trust UsedRegs because we're looking backwards, although we
  8717. know the registers are allocated after p at the very least, so manually
  8718. create tai_regalloc objects if needed }
  8719. for X := 0 to taicpu(hp1).ops - 1 do
  8720. case taicpu(hp1).oper[X]^.typ of
  8721. top_reg:
  8722. begin
  8723. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8724. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8725. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8726. end;
  8727. top_ref:
  8728. begin
  8729. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8730. begin
  8731. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8732. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8733. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8734. end;
  8735. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8736. begin
  8737. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8738. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8739. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8740. end;
  8741. end;
  8742. else
  8743. ;
  8744. end;
  8745. Result := True;
  8746. end;
  8747. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8748. var
  8749. hp2: tai;
  8750. X: Integer;
  8751. begin
  8752. { If we have something like:
  8753. cmp ###,%reg1
  8754. mov 0,%reg2
  8755. And no modified registers are shared, move the instruction to before
  8756. the comparison as this means it can be optimised without worrying
  8757. about the FLAGS register. (CMP/MOV is generated by
  8758. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8759. As long as the second instruction doesn't use the flags or one of the
  8760. registers used by CMP or TEST (also check any references that use the
  8761. registers), then it can be moved prior to the comparison.
  8762. }
  8763. Result := False;
  8764. if not TrySwapMovOp(p, hp1) then
  8765. Exit;
  8766. if taicpu(hp1).opcode = A_LEA then
  8767. { The flags will be overwritten by the CMP/TEST instruction }
  8768. ConvertLEA(taicpu(hp1));
  8769. Result := True;
  8770. { Can we move it one further back? }
  8771. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8772. { Check to see if CMP/TEST is a comparison against zero }
  8773. (
  8774. (
  8775. (taicpu(p).opcode = A_CMP) and
  8776. MatchOperand(taicpu(p).oper[0]^, 0)
  8777. ) or
  8778. (
  8779. (taicpu(p).opcode = A_TEST) and
  8780. (
  8781. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8782. MatchOperand(taicpu(p).oper[0]^, -1)
  8783. )
  8784. )
  8785. ) and
  8786. { These instructions set the zero flag if the result is zero }
  8787. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8788. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8789. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8790. TrySwapMovOp(hp2, hp1);
  8791. end;
  8792. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8793. var
  8794. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8795. JumpLabel: TAsmLabel;
  8796. TmpBool: Boolean;
  8797. begin
  8798. Result := False;
  8799. { Look for:
  8800. stc/clc
  8801. j(c) .L1
  8802. ...
  8803. .L1:
  8804. set(n)cb %reg
  8805. (flags deallocated)
  8806. j(c) .L2
  8807. Change to:
  8808. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8809. j(c) .L2
  8810. }
  8811. p_last := p;
  8812. while GetNextInstruction(p_last, hp1) and
  8813. (hp1.typ = ait_instruction) and
  8814. IsJumpToLabel(taicpu(hp1)) do
  8815. begin
  8816. if DoJumpOptimizations(hp1, TmpBool) then
  8817. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8818. Continue;
  8819. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8820. if not Assigned(JumpLabel) then
  8821. InternalError(2024012801);
  8822. { Optimise the J(c); stc/clc optimisation first since this will
  8823. get missed if the main optimisation takes place }
  8824. if (taicpu(hp1).opcode = A_JCC) then
  8825. begin
  8826. if GetNextInstruction(hp1, hp2) and
  8827. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8828. TryJccStcClcOpt(hp1, hp2) then
  8829. begin
  8830. Result := True;
  8831. Exit;
  8832. end;
  8833. hp2 := nil; { Suppress compiler warning }
  8834. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8835. { Make sure the flags aren't used again }
  8836. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8837. begin
  8838. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8839. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8840. begin
  8841. if (taicpu(p).opcode = A_STC) then
  8842. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8843. else
  8844. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8845. MakeUnconditional(taicpu(hp1));
  8846. { Move the jump to after the flag deallocations }
  8847. Asml.Remove(hp1);
  8848. Asml.InsertAfter(hp1, hp2);
  8849. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8850. Result := True;
  8851. Exit;
  8852. end
  8853. else
  8854. begin
  8855. if (taicpu(p).opcode = A_STC) then
  8856. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8857. else
  8858. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8859. { In this case, the jump is deterministic in that it will never be taken }
  8860. JumpLabel.DecRefs;
  8861. RemoveInstruction(hp1);
  8862. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8863. Result := True;
  8864. Exit;
  8865. end;
  8866. end;
  8867. end;
  8868. hp2 := nil; { Suppress compiler warning }
  8869. if
  8870. { Make sure the carry flag doesn't appear in the jump conditions }
  8871. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8872. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8873. GetNextInstruction(hp2, p_dist) and
  8874. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8875. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8876. begin
  8877. case taicpu(p_dist).opcode of
  8878. A_Jcc:
  8879. begin
  8880. if DoJumpOptimizations(p_dist, TmpBool) then
  8881. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8882. Continue;
  8883. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8884. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8885. begin
  8886. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8887. JumpLabel.decrefs;
  8888. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8889. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8890. Result := True;
  8891. Exit;
  8892. end
  8893. else if GetNextInstruction(p_dist, hp1_dist) and
  8894. (hp1_dist.typ = ait_label) then
  8895. begin
  8896. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8897. JumpLabel.decrefs;
  8898. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8899. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8900. Result := True;
  8901. Exit;
  8902. end;
  8903. end;
  8904. A_SETcc:
  8905. if { Make sure the flags aren't used again }
  8906. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8907. GetNextInstruction(hp2, hp1_dist) and
  8908. (hp1_dist.typ = ait_instruction) and
  8909. IsJumpToLabel(taicpu(hp1_dist)) and
  8910. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8911. { This works if hp1_dist or both are regular JMP instructions }
  8912. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8913. (
  8914. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8915. { Make sure the register isn't still in use, otherwise it
  8916. may get corrupted (fixes #40659) }
  8917. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8918. ) then
  8919. begin
  8920. taicpu(p).allocate_oper(2);
  8921. taicpu(p).ops := 2;
  8922. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8923. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8924. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8925. taicpu(p).opcode := A_MOV;
  8926. taicpu(p).opsize := S_B;
  8927. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8928. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8929. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8930. JumpLabel.decrefs;
  8931. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8932. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8933. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8934. (tai_regalloc(hp2).ratype = ra_alloc) then
  8935. begin
  8936. Asml.Remove(hp2);
  8937. Asml.InsertAfter(hp2, p);
  8938. end;
  8939. Result := True;
  8940. Exit;
  8941. end;
  8942. else
  8943. ;
  8944. end;
  8945. end;
  8946. p_last := hp1;
  8947. end;
  8948. end;
  8949. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8950. var
  8951. hp2, hp3: tai;
  8952. TempBool: Boolean;
  8953. begin
  8954. Result := False;
  8955. {
  8956. j(c) .L1
  8957. stc/clc
  8958. .L1:
  8959. jc/jnc .L2
  8960. (Flags deallocated)
  8961. Change to:
  8962. j)c) .L1
  8963. jmp .L2
  8964. .L1:
  8965. jc/jnc .L2
  8966. Then call DoJumpOptimizations to convert to:
  8967. j(nc) .L2
  8968. .L1: (may become a dead label)
  8969. jc/jnc .L2
  8970. }
  8971. if GetNextInstruction(hp1, hp2) and
  8972. (hp2.typ = ait_label) and
  8973. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8974. GetNextInstruction(hp2, hp3) and
  8975. MatchInstruction(hp3, A_Jcc, []) and
  8976. (
  8977. (
  8978. (taicpu(hp3).condition = C_C) and
  8979. (taicpu(hp1).opcode = A_STC)
  8980. ) or (
  8981. (taicpu(hp3).condition = C_NC) and
  8982. (taicpu(hp1).opcode = A_CLC)
  8983. )
  8984. ) and
  8985. { Make sure the flags aren't used again }
  8986. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8987. begin
  8988. taicpu(hp1).allocate_oper(1);
  8989. taicpu(hp1).ops := 1;
  8990. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8991. taicpu(hp1).opcode := A_JMP;
  8992. taicpu(hp1).is_jmp := True;
  8993. TempBool := True; { Prevent compiler warnings }
  8994. if DoJumpOptimizations(p, TempBool) then
  8995. Result := True
  8996. else
  8997. Include(OptsToCheck, aoc_ForceNewIteration);
  8998. end;
  8999. end;
  9000. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9001. begin
  9002. { This generally only executes under -O3 and above }
  9003. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9004. end;
  9005. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9006. var
  9007. hp1, hp2: tai;
  9008. FoundComparison: Boolean;
  9009. begin
  9010. { Run the pass 1 optimisations as well, since they may have some effect
  9011. after the CMOV blocks are created in OptPass2Jcc }
  9012. Result := False;
  9013. { Result := OptPass1CMOVcc(p);
  9014. if Result then
  9015. Exit;}
  9016. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9017. and make a slightly inefficent result on branching-type blocks, notably
  9018. when setting a function result then jumping to the function epilogue.
  9019. In this case, change:
  9020. cmov(c) %reg1,%reg2
  9021. j(c) @lbl
  9022. (%reg2 deallocated)
  9023. To:
  9024. mov %reg11,%reg2
  9025. j(c) @lbl
  9026. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9027. jump because if it's not present, we may end up with a jump that's
  9028. completely unrelated.
  9029. }
  9030. hp1 := p;
  9031. while GetNextInstruction(hp1, hp1) and
  9032. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9033. if (hp1.typ = ait_instruction) and
  9034. (taicpu(hp1).opcode = A_Jcc) and
  9035. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9036. begin
  9037. TransferUsedRegs(TmpUsedRegs);
  9038. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9039. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9040. (
  9041. { See if we can find a more distant instruction that overwrites
  9042. the destination register }
  9043. (cs_opt_level3 in current_settings.optimizerswitches) and
  9044. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9045. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9046. ) then
  9047. begin
  9048. if (taicpu(p).oper[0]^.typ = top_reg) then
  9049. begin
  9050. { Search backwards to see if the source register is set to a
  9051. constant }
  9052. FoundComparison := False;
  9053. hp1 := p;
  9054. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9055. begin
  9056. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9057. begin
  9058. FoundComparison := True;
  9059. Continue;
  9060. end;
  9061. { Once we find the CMP, TEST or similar instruction, we
  9062. have to stop if we find anything other than a MOV }
  9063. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9064. Break;
  9065. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9066. { Destination register was modified }
  9067. Break;
  9068. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9069. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9070. begin
  9071. { Found a constant! }
  9072. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9073. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9074. { The source register is no longer in use }
  9075. RemoveInstruction(hp1);
  9076. Break;
  9077. end;
  9078. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9079. { Some other instruction has modified the source register }
  9080. Break;
  9081. end;
  9082. end;
  9083. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9084. taicpu(p).opcode := A_MOV;
  9085. taicpu(p).condition := C_None;
  9086. { Rely on the post peephole stage to put the MOV before the
  9087. CMP/TEST instruction that appears prior }
  9088. Result := True;
  9089. Exit;
  9090. end;
  9091. end;
  9092. end;
  9093. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9094. function IsXCHGAcceptable: Boolean; inline;
  9095. begin
  9096. { Always accept if optimising for size }
  9097. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9098. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9099. than 3, so it becomes a saving compared to three MOVs with two of
  9100. them able to execute simultaneously. [Kit] }
  9101. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9102. end;
  9103. var
  9104. NewRef: TReference;
  9105. hp1, hp2, hp3, hp4: Tai;
  9106. {$ifndef x86_64}
  9107. OperIdx: Integer;
  9108. {$endif x86_64}
  9109. NewInstr : Taicpu;
  9110. NewAligh : Tai_align;
  9111. DestLabel: TAsmLabel;
  9112. TempTracking: TAllUsedRegs;
  9113. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9114. var
  9115. NextInstr: tai;
  9116. begin
  9117. Result := False;
  9118. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9119. if not GetNextInstruction(InputInstr, NextInstr) or
  9120. (
  9121. { The FLAGS register isn't always tracked properly, so do not
  9122. perform this optimisation if a conditional statement follows }
  9123. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9124. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9125. ) then
  9126. begin
  9127. reference_reset(NewRef, 1, []);
  9128. NewRef.base := taicpu(p).oper[0]^.reg;
  9129. NewRef.scalefactor := 1;
  9130. if taicpu(InputInstr).opcode = A_ADD then
  9131. begin
  9132. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9133. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9134. end
  9135. else
  9136. begin
  9137. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9138. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9139. end;
  9140. taicpu(p).opcode := A_LEA;
  9141. taicpu(p).loadref(0, NewRef);
  9142. { For the sake of debugging, have the line info match the
  9143. arithmetic instruction rather than the MOV instruction }
  9144. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9145. RemoveInstruction(InputInstr);
  9146. Result := True;
  9147. end;
  9148. end;
  9149. begin
  9150. Result:=false;
  9151. { This optimisation adds an instruction, so only do it for speed }
  9152. if not (cs_opt_size in current_settings.optimizerswitches) and
  9153. MatchOpType(taicpu(p), top_const, top_reg) and
  9154. (taicpu(p).oper[0]^.val = 0) then
  9155. begin
  9156. { To avoid compiler warning }
  9157. DestLabel := nil;
  9158. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9159. InternalError(2021040750);
  9160. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9161. Exit;
  9162. case hp1.typ of
  9163. ait_label:
  9164. begin
  9165. { Change:
  9166. mov $0,%reg mov $0,%reg
  9167. @Lbl1: @Lbl1:
  9168. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9169. je @Lbl2 jne @Lbl2
  9170. To: To:
  9171. mov $0,%reg mov $0,%reg
  9172. jmp @Lbl2 jmp @Lbl3
  9173. (align) (align)
  9174. @Lbl1: @Lbl1:
  9175. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9176. je @Lbl2 je @Lbl2
  9177. @Lbl3: <-- Only if label exists
  9178. (Not if it's optimised for size)
  9179. }
  9180. if not GetNextInstruction(hp1, hp2) then
  9181. Exit;
  9182. if (hp2.typ = ait_instruction) and
  9183. (
  9184. { Register sizes must exactly match }
  9185. (
  9186. (taicpu(hp2).opcode = A_CMP) and
  9187. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9188. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9189. ) or (
  9190. (taicpu(hp2).opcode = A_TEST) and
  9191. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9192. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9193. )
  9194. ) and GetNextInstruction(hp2, hp3) and
  9195. (hp3.typ = ait_instruction) and
  9196. (taicpu(hp3).opcode = A_JCC) and
  9197. (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
  9198. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9199. begin
  9200. { Check condition of jump }
  9201. { Always true? }
  9202. if condition_in(C_E, taicpu(hp3).condition) then
  9203. begin
  9204. { Copy label symbol and obtain matching label entry for the
  9205. conditional jump, as this will be our destination}
  9206. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9207. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9208. Result := True;
  9209. end
  9210. { Always false? }
  9211. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9212. begin
  9213. { This is only worth it if there's a jump to take }
  9214. case hp2.typ of
  9215. ait_instruction:
  9216. begin
  9217. if taicpu(hp2).opcode = A_JMP then
  9218. begin
  9219. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9220. { An unconditional jump follows the conditional jump which will always be false,
  9221. so use this jump's destination for the new jump }
  9222. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9223. Result := True;
  9224. end
  9225. else if taicpu(hp2).opcode = A_JCC then
  9226. begin
  9227. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9228. if condition_in(C_E, taicpu(hp2).condition) then
  9229. begin
  9230. { A second conditional jump follows the conditional jump which will always be false,
  9231. while the second jump is always True, so use this jump's destination for the new jump }
  9232. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9233. Result := True;
  9234. end;
  9235. { Don't risk it if the jump isn't always true (Result remains False) }
  9236. end;
  9237. end;
  9238. else
  9239. { If anything else don't optimise };
  9240. end;
  9241. end;
  9242. if Result then
  9243. begin
  9244. { Just so we have something to insert as a paremeter}
  9245. reference_reset(NewRef, 1, []);
  9246. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9247. { Now actually load the correct parameter (this also
  9248. increases the reference count) }
  9249. NewInstr.loadsymbol(0, DestLabel, 0);
  9250. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9251. begin
  9252. { Get instruction before original label (may not be p under -O3) }
  9253. if not GetLastInstruction(hp1, hp2) then
  9254. { Shouldn't fail here }
  9255. InternalError(2021040701);
  9256. end
  9257. else
  9258. hp2 := p;
  9259. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9260. AsmL.InsertAfter(NewInstr, hp2);
  9261. { Add new alignment field }
  9262. (* AsmL.InsertAfter(
  9263. cai_align.create_max(
  9264. current_settings.alignment.jumpalign,
  9265. current_settings.alignment.jumpalignskipmax
  9266. ),
  9267. NewInstr
  9268. ); *)
  9269. end;
  9270. Exit;
  9271. end;
  9272. end;
  9273. else
  9274. ;
  9275. end;
  9276. end;
  9277. if not GetNextInstruction(p, hp1) then
  9278. Exit;
  9279. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9280. begin
  9281. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9282. begin
  9283. Result := True;
  9284. Exit;
  9285. end;
  9286. { This optimisation is only effective on a second run of Pass 2,
  9287. hence -O3 or above.
  9288. Change:
  9289. mov %reg1,%reg2
  9290. cmp/test (contains %reg1)
  9291. mov x, %reg1
  9292. (another mov or a j(c))
  9293. To:
  9294. mov %reg1,%reg2
  9295. mov x, %reg1
  9296. cmp (%reg1 replaced with %reg2)
  9297. (another mov or a j(c))
  9298. The requirement of an additional MOV or a jump ensures there
  9299. isn't performance loss, since a j(c) will permit macro-fusion
  9300. with the cmp instruction, while another MOV likely means it's
  9301. not all being executed in a single cycle due to parallelisation.
  9302. }
  9303. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9304. MatchOpType(taicpu(p), top_reg, top_reg) and
  9305. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9306. GetNextInstruction(hp1, hp2) and
  9307. MatchInstruction(hp2, A_MOV, []) and
  9308. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9309. { Registers don't have to be the same size in this case }
  9310. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9311. GetNextInstruction(hp2, hp3) and
  9312. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9313. { Make sure the operands in the camparison can be safely replaced }
  9314. (
  9315. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9316. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9317. ) and
  9318. (
  9319. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9320. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9321. ) then
  9322. begin
  9323. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9324. AsmL.Remove(hp2);
  9325. AsmL.InsertAfter(hp2, p);
  9326. Result := True;
  9327. Exit;
  9328. end;
  9329. end;
  9330. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9331. begin
  9332. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9333. further, but we can't just put this jump optimisation in pass 1
  9334. because it tends to perform worse when conditional jumps are
  9335. nearby (e.g. when converting CMOV instructions). [Kit] }
  9336. CopyUsedRegs(TempTracking);
  9337. UpdateUsedRegs(tai(p.Next));
  9338. if OptPass2JMP(hp1) then
  9339. begin
  9340. { Restore register state }
  9341. RestoreUsedRegs(TempTracking);
  9342. ReleaseUsedRegs(TempTracking);
  9343. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9344. OptPass1MOV(p);
  9345. Result := True;
  9346. Exit;
  9347. end;
  9348. { If OptPass2JMP returned False, no optimisations were done to
  9349. the jump and there are no further optimisations that can be done
  9350. to the MOV instruction on this pass other than FuncMov2Func }
  9351. { Restore register state }
  9352. RestoreUsedRegs(TempTracking);
  9353. ReleaseUsedRegs(TempTracking);
  9354. Result := FuncMov2Func(p, hp1);
  9355. Exit;
  9356. end;
  9357. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9358. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9359. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9360. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9361. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9362. begin
  9363. { Change:
  9364. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9365. addl/q $x,%reg2 subl/q $x,%reg2
  9366. To:
  9367. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9368. }
  9369. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9370. { be lazy, checking separately for sub would be slightly better }
  9371. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9372. begin
  9373. TransferUsedRegs(TmpUsedRegs);
  9374. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9375. if TryMovArith2Lea(hp1) then
  9376. begin
  9377. Result := True;
  9378. Exit;
  9379. end
  9380. end
  9381. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9382. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9383. { Same as above, but also adds or subtracts to %reg2 in between.
  9384. It's still valid as long as the flags aren't in use }
  9385. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9386. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9387. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9388. { be lazy, checking separately for sub would be slightly better }
  9389. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9390. begin
  9391. TransferUsedRegs(TmpUsedRegs);
  9392. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9394. if TryMovArith2Lea(hp2) then
  9395. begin
  9396. Result := True;
  9397. Exit;
  9398. end;
  9399. end;
  9400. end;
  9401. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9402. {$ifdef x86_64}
  9403. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9404. {$else x86_64}
  9405. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9406. {$endif x86_64}
  9407. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9408. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9409. { mov reg1, reg2 mov reg1, reg2
  9410. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9411. begin
  9412. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9413. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9414. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9415. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9416. TransferUsedRegs(TmpUsedRegs);
  9417. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9418. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9419. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9420. then
  9421. begin
  9422. RemoveCurrentP(p, hp1);
  9423. Result:=true;
  9424. end;
  9425. Exit;
  9426. end;
  9427. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9428. IsXCHGAcceptable and
  9429. { XCHG doesn't support 8-bit registers }
  9430. (taicpu(p).opsize <> S_B) and
  9431. MatchInstruction(hp1, A_MOV, []) and
  9432. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9433. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9434. GetNextInstruction(hp1, hp2) and
  9435. MatchInstruction(hp2, A_MOV, []) and
  9436. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9437. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9438. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9439. begin
  9440. { mov %reg1,%reg2
  9441. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9442. mov %reg2,%reg3
  9443. (%reg2 not used afterwards)
  9444. Note that xchg takes 3 cycles to execute, and generally mov's take
  9445. only one cycle apiece, but the first two mov's can be executed in
  9446. parallel, only taking 2 cycles overall. Older processors should
  9447. therefore only optimise for size. [Kit]
  9448. }
  9449. TransferUsedRegs(TmpUsedRegs);
  9450. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9451. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9452. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9453. begin
  9454. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9455. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9456. taicpu(hp1).opcode := A_XCHG;
  9457. RemoveCurrentP(p, hp1);
  9458. RemoveInstruction(hp2);
  9459. Result := True;
  9460. Exit;
  9461. end;
  9462. end;
  9463. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9464. MatchInstruction(hp1, A_SAR, []) then
  9465. begin
  9466. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9467. begin
  9468. { the use of %edx also covers the opsize being S_L }
  9469. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9470. begin
  9471. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9472. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9473. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9474. begin
  9475. { Change:
  9476. movl %eax,%edx
  9477. sarl $31,%edx
  9478. To:
  9479. cltd
  9480. }
  9481. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9482. RemoveInstruction(hp1);
  9483. taicpu(p).opcode := A_CDQ;
  9484. taicpu(p).opsize := S_NO;
  9485. taicpu(p).clearop(1);
  9486. taicpu(p).clearop(0);
  9487. taicpu(p).ops:=0;
  9488. Result := True;
  9489. Exit;
  9490. end
  9491. else if (cs_opt_size in current_settings.optimizerswitches) and
  9492. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9493. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9494. begin
  9495. { Change:
  9496. movl %edx,%eax
  9497. sarl $31,%edx
  9498. To:
  9499. movl %edx,%eax
  9500. cltd
  9501. Note that this creates a dependency between the two instructions,
  9502. so only perform if optimising for size.
  9503. }
  9504. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9505. taicpu(hp1).opcode := A_CDQ;
  9506. taicpu(hp1).opsize := S_NO;
  9507. taicpu(hp1).clearop(1);
  9508. taicpu(hp1).clearop(0);
  9509. taicpu(hp1).ops:=0;
  9510. Include(OptsToCheck, aoc_ForceNewIteration);
  9511. Exit;
  9512. end;
  9513. {$ifndef x86_64}
  9514. end
  9515. { Don't bother if CMOV is supported, because a more optimal
  9516. sequence would have been generated for the Abs() intrinsic }
  9517. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9518. { the use of %eax also covers the opsize being S_L }
  9519. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9520. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9521. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9522. GetNextInstruction(hp1, hp2) and
  9523. MatchInstruction(hp2, A_XOR, [S_L]) and
  9524. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9525. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9526. GetNextInstruction(hp2, hp3) and
  9527. MatchInstruction(hp3, A_SUB, [S_L]) and
  9528. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9529. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9530. begin
  9531. { Change:
  9532. movl %eax,%edx
  9533. sarl $31,%eax
  9534. xorl %eax,%edx
  9535. subl %eax,%edx
  9536. (Instruction that uses %edx)
  9537. (%eax deallocated)
  9538. (%edx deallocated)
  9539. To:
  9540. cltd
  9541. xorl %edx,%eax <-- Note the registers have swapped
  9542. subl %edx,%eax
  9543. (Instruction that uses %eax) <-- %eax rather than %edx
  9544. }
  9545. TransferUsedRegs(TmpUsedRegs);
  9546. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9547. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9548. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9549. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9550. begin
  9551. if GetNextInstruction(hp3, hp4) and
  9552. not RegModifiedByInstruction(NR_EDX, hp4) and
  9553. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9554. begin
  9555. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9556. taicpu(p).opcode := A_CDQ;
  9557. taicpu(p).clearop(1);
  9558. taicpu(p).clearop(0);
  9559. taicpu(p).ops:=0;
  9560. RemoveInstruction(hp1);
  9561. taicpu(hp2).loadreg(0, NR_EDX);
  9562. taicpu(hp2).loadreg(1, NR_EAX);
  9563. taicpu(hp3).loadreg(0, NR_EDX);
  9564. taicpu(hp3).loadreg(1, NR_EAX);
  9565. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9566. { Convert references in the following instruction (hp4) from %edx to %eax }
  9567. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9568. with taicpu(hp4).oper[OperIdx]^ do
  9569. case typ of
  9570. top_reg:
  9571. if getsupreg(reg) = RS_EDX then
  9572. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9573. top_ref:
  9574. begin
  9575. if getsupreg(reg) = RS_EDX then
  9576. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9577. if getsupreg(reg) = RS_EDX then
  9578. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9579. end;
  9580. else
  9581. ;
  9582. end;
  9583. Result := True;
  9584. Exit;
  9585. end;
  9586. end;
  9587. {$else x86_64}
  9588. end;
  9589. end
  9590. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9591. { the use of %rdx also covers the opsize being S_Q }
  9592. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9593. begin
  9594. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9595. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9596. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9597. begin
  9598. { Change:
  9599. movq %rax,%rdx
  9600. sarq $63,%rdx
  9601. To:
  9602. cqto
  9603. }
  9604. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9605. RemoveInstruction(hp1);
  9606. taicpu(p).opcode := A_CQO;
  9607. taicpu(p).opsize := S_NO;
  9608. taicpu(p).clearop(1);
  9609. taicpu(p).clearop(0);
  9610. taicpu(p).ops:=0;
  9611. Result := True;
  9612. Exit;
  9613. end
  9614. else if (cs_opt_size in current_settings.optimizerswitches) and
  9615. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9616. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9617. begin
  9618. { Change:
  9619. movq %rdx,%rax
  9620. sarq $63,%rdx
  9621. To:
  9622. movq %rdx,%rax
  9623. cqto
  9624. Note that this creates a dependency between the two instructions,
  9625. so only perform if optimising for size.
  9626. }
  9627. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9628. taicpu(hp1).opcode := A_CQO;
  9629. taicpu(hp1).opsize := S_NO;
  9630. taicpu(hp1).clearop(1);
  9631. taicpu(hp1).clearop(0);
  9632. taicpu(hp1).ops:=0;
  9633. Include(OptsToCheck, aoc_ForceNewIteration);
  9634. Exit;
  9635. {$endif x86_64}
  9636. end;
  9637. end;
  9638. end;
  9639. if MatchInstruction(hp1, A_MOV, []) and
  9640. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9641. { Though "GetNextInstruction" could be factored out, along with
  9642. the instructions that depend on hp2, it is an expensive call that
  9643. should be delayed for as long as possible, hence we do cheaper
  9644. checks first that are likely to be False. [Kit] }
  9645. begin
  9646. if (
  9647. (
  9648. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9649. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9650. (
  9651. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9652. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9653. )
  9654. ) or
  9655. (
  9656. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9657. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9658. (
  9659. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9660. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9661. )
  9662. )
  9663. ) and
  9664. GetNextInstruction(hp1, hp2) and
  9665. MatchInstruction(hp2, A_SAR, []) and
  9666. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9667. begin
  9668. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9669. begin
  9670. { Change:
  9671. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9672. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9673. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9674. To:
  9675. movl r/m,%eax <- Note the change in register
  9676. cltd
  9677. }
  9678. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9679. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9680. taicpu(p).loadreg(1, NR_EAX);
  9681. taicpu(hp1).opcode := A_CDQ;
  9682. taicpu(hp1).clearop(1);
  9683. taicpu(hp1).clearop(0);
  9684. taicpu(hp1).ops:=0;
  9685. RemoveInstruction(hp2);
  9686. Include(OptsToCheck, aoc_ForceNewIteration);
  9687. (*
  9688. {$ifdef x86_64}
  9689. end
  9690. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9691. { This code sequence does not get generated - however it might become useful
  9692. if and when 128-bit signed integer types make an appearance, so the code
  9693. is kept here for when it is eventually needed. [Kit] }
  9694. (
  9695. (
  9696. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9697. (
  9698. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9699. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9700. )
  9701. ) or
  9702. (
  9703. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9704. (
  9705. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9706. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9707. )
  9708. )
  9709. ) and
  9710. GetNextInstruction(hp1, hp2) and
  9711. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9712. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9713. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9714. begin
  9715. { Change:
  9716. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9717. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9718. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9719. To:
  9720. movq r/m,%rax <- Note the change in register
  9721. cqto
  9722. }
  9723. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9724. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9725. taicpu(p).loadreg(1, NR_RAX);
  9726. taicpu(hp1).opcode := A_CQO;
  9727. taicpu(hp1).clearop(1);
  9728. taicpu(hp1).clearop(0);
  9729. taicpu(hp1).ops:=0;
  9730. RemoveInstruction(hp2);
  9731. Include(OptsToCheck, aoc_ForceNewIteration);
  9732. {$endif x86_64}
  9733. *)
  9734. end;
  9735. end;
  9736. {$ifdef x86_64}
  9737. end;
  9738. if (taicpu(p).opsize = S_L) and
  9739. (taicpu(p).oper[1]^.typ = top_reg) and
  9740. (
  9741. MatchInstruction(hp1, A_MOV,[]) and
  9742. (taicpu(hp1).opsize = S_L) and
  9743. (taicpu(hp1).oper[1]^.typ = top_reg)
  9744. ) and (
  9745. GetNextInstruction(hp1, hp2) and
  9746. (tai(hp2).typ=ait_instruction) and
  9747. (taicpu(hp2).opsize = S_Q) and
  9748. (
  9749. (
  9750. MatchInstruction(hp2, A_ADD,[]) and
  9751. (taicpu(hp2).opsize = S_Q) and
  9752. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9753. (
  9754. (
  9755. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9756. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9757. ) or (
  9758. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9759. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9760. )
  9761. )
  9762. ) or (
  9763. MatchInstruction(hp2, A_LEA,[]) and
  9764. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9765. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9766. (
  9767. (
  9768. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9769. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9770. ) or (
  9771. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9772. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9773. )
  9774. ) and (
  9775. (
  9776. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9777. ) or (
  9778. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9779. )
  9780. )
  9781. )
  9782. )
  9783. ) and (
  9784. GetNextInstruction(hp2, hp3) and
  9785. MatchInstruction(hp3, A_SHR,[]) and
  9786. (taicpu(hp3).opsize = S_Q) and
  9787. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9788. (taicpu(hp3).oper[0]^.val = 1) and
  9789. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9790. ) then
  9791. begin
  9792. { Change movl x, reg1d movl x, reg1d
  9793. movl y, reg2d movl y, reg2d
  9794. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9795. shrq $1, reg1q shrq $1, reg1q
  9796. ( reg1d and reg2d can be switched around in the first two instructions )
  9797. To movl x, reg1d
  9798. addl y, reg1d
  9799. rcrl $1, reg1d
  9800. This corresponds to the common expression (x + y) shr 1, where
  9801. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9802. smaller code, but won't account for x + y causing an overflow). [Kit]
  9803. }
  9804. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9805. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9806. begin
  9807. { Change first MOV command to have the same register as the final output }
  9808. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9809. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9810. Result := True;
  9811. end
  9812. else
  9813. begin
  9814. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9815. Include(OptsToCheck, aoc_ForceNewIteration);
  9816. end;
  9817. { Change second MOV command to an ADD command. This is easier than
  9818. converting the existing command because it means we don't have to
  9819. touch 'y', which might be a complicated reference, and also the
  9820. fact that the third command might either be ADD or LEA. [Kit] }
  9821. taicpu(hp1).opcode := A_ADD;
  9822. { Delete old ADD/LEA instruction }
  9823. RemoveInstruction(hp2);
  9824. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9825. taicpu(hp3).opcode := A_RCR;
  9826. taicpu(hp3).changeopsize(S_L);
  9827. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9828. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9829. called, so FuncMov2Func below is safe to call }
  9830. {$endif x86_64}
  9831. end;
  9832. if FuncMov2Func(p, hp1) then
  9833. begin
  9834. Result := True;
  9835. Exit;
  9836. end;
  9837. end;
  9838. {$push}
  9839. {$q-}{$r-}
  9840. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9841. var
  9842. ThisReg: TRegister;
  9843. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9844. TargetSubReg: TSubRegister;
  9845. hp1, hp2: tai;
  9846. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9847. { Store list of found instructions so we don't have to call
  9848. GetNextInstructionUsingReg multiple times }
  9849. InstrList: array of taicpu;
  9850. InstrMax, Index: Integer;
  9851. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9852. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9853. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9854. WorkingValue: TCgInt;
  9855. PreMessage: string;
  9856. { Data flow analysis }
  9857. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9858. BitwiseOnly, OrXorUsed,
  9859. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9860. function CheckOverflowConditions: Boolean;
  9861. begin
  9862. Result := True;
  9863. if (TestValSignedMax > SignedUpperLimit) then
  9864. UpperSignedOverflow := True;
  9865. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9866. LowerSignedOverflow := True;
  9867. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9868. LowerUnsignedOverflow := True;
  9869. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9870. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9871. begin
  9872. { Absolute overflow }
  9873. Result := False;
  9874. Exit;
  9875. end;
  9876. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9877. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9878. ShiftDownOverflow := True;
  9879. if (TestValMin < 0) or (TestValMax < 0) then
  9880. begin
  9881. LowerUnsignedOverflow := True;
  9882. UpperUnsignedOverflow := True;
  9883. end;
  9884. end;
  9885. function AdjustInitialLoadAndSize: Boolean;
  9886. begin
  9887. Result := False;
  9888. if not p_removed then
  9889. begin
  9890. if TargetSize = MinSize then
  9891. begin
  9892. { Convert the input MOVZX to a MOV }
  9893. if (taicpu(p).oper[0]^.typ = top_reg) and
  9894. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9895. begin
  9896. { Or remove it completely! }
  9897. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9898. RemoveCurrentP(p);
  9899. p_removed := True;
  9900. end
  9901. else
  9902. begin
  9903. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9904. taicpu(p).opcode := A_MOV;
  9905. taicpu(p).oper[1]^.reg := ThisReg;
  9906. taicpu(p).opsize := TargetSize;
  9907. end;
  9908. Result := True;
  9909. end
  9910. else if TargetSize <> MaxSize then
  9911. begin
  9912. case MaxSize of
  9913. S_L:
  9914. if TargetSize = S_W then
  9915. begin
  9916. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9917. taicpu(p).opsize := S_BW;
  9918. taicpu(p).oper[1]^.reg := ThisReg;
  9919. Result := True;
  9920. end
  9921. else
  9922. InternalError(2020112341);
  9923. S_W:
  9924. if TargetSize = S_L then
  9925. begin
  9926. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9927. taicpu(p).opsize := S_BL;
  9928. taicpu(p).oper[1]^.reg := ThisReg;
  9929. Result := True;
  9930. end
  9931. else
  9932. InternalError(2020112342);
  9933. else
  9934. ;
  9935. end;
  9936. end
  9937. else if not hp1_removed and not RegInUse then
  9938. begin
  9939. { If we have something like:
  9940. movzbl (oper),%regd
  9941. add x, %regd
  9942. movzbl %regb, %regd
  9943. We can reduce the register size to the input of the final
  9944. movzbl instruction. Overflows won't have any effect.
  9945. }
  9946. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9947. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9948. begin
  9949. TargetSize := S_B;
  9950. setsubreg(ThisReg, R_SUBL);
  9951. Result := True;
  9952. end
  9953. else if (taicpu(p).opsize = S_WL) and
  9954. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9955. begin
  9956. TargetSize := S_W;
  9957. setsubreg(ThisReg, R_SUBW);
  9958. Result := True;
  9959. end;
  9960. if Result then
  9961. begin
  9962. { Convert the input MOVZX to a MOV }
  9963. if (taicpu(p).oper[0]^.typ = top_reg) and
  9964. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9965. begin
  9966. { Or remove it completely! }
  9967. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9968. RemoveCurrentP(p);
  9969. p_removed := True;
  9970. end
  9971. else
  9972. begin
  9973. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9974. taicpu(p).opcode := A_MOV;
  9975. taicpu(p).oper[1]^.reg := ThisReg;
  9976. taicpu(p).opsize := TargetSize;
  9977. end;
  9978. end;
  9979. end;
  9980. end;
  9981. end;
  9982. procedure AdjustFinalLoad;
  9983. begin
  9984. if not LowerUnsignedOverflow then
  9985. begin
  9986. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9987. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9988. begin
  9989. { Convert the output MOVZX to a MOV }
  9990. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9991. begin
  9992. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9993. if (MinSize = S_B) or
  9994. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9995. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9996. begin
  9997. { Remove it completely! }
  9998. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9999. { Be careful; if p = hp1 and p was also removed, p
  10000. will become a dangling pointer }
  10001. if p = hp1 then
  10002. begin
  10003. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10004. p_removed := True;
  10005. end
  10006. else
  10007. RemoveInstruction(hp1);
  10008. hp1_removed := True;
  10009. end;
  10010. end
  10011. else
  10012. begin
  10013. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10014. taicpu(hp1).opcode := A_MOV;
  10015. taicpu(hp1).oper[0]^.reg := ThisReg;
  10016. taicpu(hp1).opsize := TargetSize;
  10017. end;
  10018. end
  10019. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10020. begin
  10021. { Need to change the size of the output }
  10022. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10023. taicpu(hp1).oper[0]^.reg := ThisReg;
  10024. taicpu(hp1).opsize := S_BL;
  10025. end;
  10026. end;
  10027. end;
  10028. function CompressInstructions: Boolean;
  10029. var
  10030. LocalIndex: Integer;
  10031. begin
  10032. Result := False;
  10033. { The objective here is to try to find a combination that
  10034. removes one of the MOV/Z instructions. }
  10035. if (
  10036. (taicpu(p).oper[0]^.typ <> top_reg) or
  10037. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10038. ) and
  10039. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10040. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10041. begin
  10042. { Make a preference to remove the second MOVZX instruction }
  10043. case taicpu(hp1).opsize of
  10044. S_BL, S_WL:
  10045. begin
  10046. TargetSize := S_L;
  10047. TargetSubReg := R_SUBD;
  10048. end;
  10049. S_BW:
  10050. begin
  10051. TargetSize := S_W;
  10052. TargetSubReg := R_SUBW;
  10053. end;
  10054. else
  10055. InternalError(2020112302);
  10056. end;
  10057. end
  10058. else
  10059. begin
  10060. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10061. begin
  10062. { Exceeded lower bound but not upper bound }
  10063. TargetSize := MaxSize;
  10064. end
  10065. else if not LowerUnsignedOverflow then
  10066. begin
  10067. { Size didn't exceed lower bound }
  10068. TargetSize := MinSize;
  10069. end
  10070. else
  10071. Exit;
  10072. end;
  10073. case TargetSize of
  10074. S_B:
  10075. TargetSubReg := R_SUBL;
  10076. S_W:
  10077. TargetSubReg := R_SUBW;
  10078. S_L:
  10079. TargetSubReg := R_SUBD;
  10080. else
  10081. InternalError(2020112350);
  10082. end;
  10083. { Update the register to its new size }
  10084. setsubreg(ThisReg, TargetSubReg);
  10085. RegInUse := False;
  10086. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10087. begin
  10088. { Check to see if the active register is used afterwards;
  10089. if not, we can change it and make a saving. }
  10090. TransferUsedRegs(TmpUsedRegs);
  10091. { The target register may be marked as in use to cross
  10092. a jump to a distant label, so exclude it }
  10093. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10094. hp2 := p;
  10095. repeat
  10096. { Explicitly check for the excluded register (don't include the first
  10097. instruction as it may be reading from here }
  10098. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10099. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10100. begin
  10101. RegInUse := True;
  10102. Break;
  10103. end;
  10104. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10105. if not GetNextInstruction(hp2, hp2) then
  10106. InternalError(2020112340);
  10107. until (hp2 = hp1);
  10108. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10109. { We might still be able to get away with this }
  10110. RegInUse := not
  10111. (
  10112. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10113. (hp2.typ = ait_instruction) and
  10114. (
  10115. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10116. instruction that doesn't actually contain ThisReg }
  10117. (cs_opt_level3 in current_settings.optimizerswitches) or
  10118. RegInInstruction(ThisReg, hp2)
  10119. ) and
  10120. RegLoadedWithNewValue(ThisReg, hp2)
  10121. );
  10122. if not RegInUse then
  10123. begin
  10124. { Force the register size to the same as this instruction so it can be removed}
  10125. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10126. begin
  10127. TargetSize := S_L;
  10128. TargetSubReg := R_SUBD;
  10129. end
  10130. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10131. begin
  10132. TargetSize := S_W;
  10133. TargetSubReg := R_SUBW;
  10134. end;
  10135. ThisReg := taicpu(hp1).oper[1]^.reg;
  10136. setsubreg(ThisReg, TargetSubReg);
  10137. RegChanged := True;
  10138. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10139. TransferUsedRegs(TmpUsedRegs);
  10140. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10141. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10142. if p = hp1 then
  10143. begin
  10144. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10145. p_removed := True;
  10146. end
  10147. else
  10148. RemoveInstruction(hp1);
  10149. hp1_removed := True;
  10150. { Instruction will become "mov %reg,%reg" }
  10151. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10152. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10153. begin
  10154. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10155. RemoveCurrentP(p);
  10156. p_removed := True;
  10157. end
  10158. else
  10159. taicpu(p).oper[1]^.reg := ThisReg;
  10160. Result := True;
  10161. end
  10162. else
  10163. begin
  10164. if TargetSize <> MaxSize then
  10165. begin
  10166. { Since the register is in use, we have to force it to
  10167. MaxSize otherwise part of it may become undefined later on }
  10168. TargetSize := MaxSize;
  10169. case TargetSize of
  10170. S_B:
  10171. TargetSubReg := R_SUBL;
  10172. S_W:
  10173. TargetSubReg := R_SUBW;
  10174. S_L:
  10175. TargetSubReg := R_SUBD;
  10176. else
  10177. InternalError(2020112351);
  10178. end;
  10179. setsubreg(ThisReg, TargetSubReg);
  10180. end;
  10181. AdjustFinalLoad;
  10182. end;
  10183. end
  10184. else
  10185. AdjustFinalLoad;
  10186. Result := AdjustInitialLoadAndSize or Result;
  10187. { Now go through every instruction we found and change the
  10188. size. If TargetSize = MaxSize, then almost no changes are
  10189. needed and Result can remain False if it hasn't been set
  10190. yet.
  10191. If RegChanged is True, then the register requires changing
  10192. and so the point about TargetSize = MaxSize doesn't apply. }
  10193. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10194. begin
  10195. for LocalIndex := 0 to InstrMax do
  10196. begin
  10197. { If p_removed is true, then the original MOV/Z was removed
  10198. and removing the AND instruction may not be safe if it
  10199. appears first }
  10200. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10201. InternalError(2020112310);
  10202. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10203. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10204. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10205. InstrList[LocalIndex].opsize := TargetSize;
  10206. end;
  10207. Result := True;
  10208. end;
  10209. end;
  10210. begin
  10211. Result := False;
  10212. p_removed := False;
  10213. hp1_removed := False;
  10214. ThisReg := taicpu(p).oper[1]^.reg;
  10215. { Check for:
  10216. movs/z ###,%ecx (or %cx or %rcx)
  10217. ...
  10218. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10219. (dealloc %ecx)
  10220. Change to:
  10221. mov ###,%cl (if ### = %cl, then remove completely)
  10222. ...
  10223. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10224. }
  10225. if (getsupreg(ThisReg) = RS_ECX) and
  10226. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10227. (hp1.typ = ait_instruction) and
  10228. (
  10229. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10230. instruction that doesn't actually contain ECX }
  10231. (cs_opt_level3 in current_settings.optimizerswitches) or
  10232. RegInInstruction(NR_ECX, hp1) or
  10233. (
  10234. { It's common for the shift/rotate's read/write register to be
  10235. initialised in between, so under -O2 and under, search ahead
  10236. one more instruction
  10237. }
  10238. GetNextInstruction(hp1, hp1) and
  10239. (hp1.typ = ait_instruction) and
  10240. RegInInstruction(NR_ECX, hp1)
  10241. )
  10242. ) and
  10243. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10244. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10245. begin
  10246. TransferUsedRegs(TmpUsedRegs);
  10247. hp2 := p;
  10248. repeat
  10249. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10250. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10251. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10252. begin
  10253. case taicpu(p).opsize of
  10254. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10255. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10256. begin
  10257. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10258. RemoveCurrentP(p);
  10259. end
  10260. else
  10261. begin
  10262. taicpu(p).opcode := A_MOV;
  10263. taicpu(p).opsize := S_B;
  10264. taicpu(p).oper[1]^.reg := NR_CL;
  10265. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10266. end;
  10267. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10268. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10269. begin
  10270. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10271. RemoveCurrentP(p);
  10272. end
  10273. else
  10274. begin
  10275. taicpu(p).opcode := A_MOV;
  10276. taicpu(p).opsize := S_W;
  10277. taicpu(p).oper[1]^.reg := NR_CX;
  10278. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10279. end;
  10280. {$ifdef x86_64}
  10281. S_LQ:
  10282. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10283. begin
  10284. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10285. RemoveCurrentP(p);
  10286. end
  10287. else
  10288. begin
  10289. taicpu(p).opcode := A_MOV;
  10290. taicpu(p).opsize := S_L;
  10291. taicpu(p).oper[1]^.reg := NR_ECX;
  10292. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10293. end;
  10294. {$endif x86_64}
  10295. else
  10296. InternalError(2021120401);
  10297. end;
  10298. Result := True;
  10299. Exit;
  10300. end;
  10301. end;
  10302. { This is anything but quick! }
  10303. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10304. Exit;
  10305. SetLength(InstrList, 0);
  10306. InstrMax := -1;
  10307. case taicpu(p).opsize of
  10308. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10309. begin
  10310. {$if defined(i386) or defined(i8086)}
  10311. { If the target size is 8-bit, make sure we can actually encode it }
  10312. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10313. Exit;
  10314. {$endif i386 or i8086}
  10315. LowerLimit := $FF;
  10316. SignedLowerLimit := $7F;
  10317. SignedLowerLimitBottom := -128;
  10318. MinSize := S_B;
  10319. if taicpu(p).opsize = S_BW then
  10320. begin
  10321. MaxSize := S_W;
  10322. UpperLimit := $FFFF;
  10323. SignedUpperLimit := $7FFF;
  10324. SignedUpperLimitBottom := -32768;
  10325. end
  10326. else
  10327. begin
  10328. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10329. MaxSize := S_L;
  10330. UpperLimit := $FFFFFFFF;
  10331. SignedUpperLimit := $7FFFFFFF;
  10332. SignedUpperLimitBottom := -2147483648;
  10333. end;
  10334. end;
  10335. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10336. begin
  10337. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10338. LowerLimit := $FFFF;
  10339. SignedLowerLimit := $7FFF;
  10340. SignedLowerLimitBottom := -32768;
  10341. UpperLimit := $FFFFFFFF;
  10342. SignedUpperLimit := $7FFFFFFF;
  10343. SignedUpperLimitBottom := -2147483648;
  10344. MinSize := S_W;
  10345. MaxSize := S_L;
  10346. end;
  10347. {$ifdef x86_64}
  10348. S_LQ:
  10349. begin
  10350. { Both the lower and upper limits are set to 32-bit. If a limit
  10351. is breached, then optimisation is impossible }
  10352. LowerLimit := $FFFFFFFF;
  10353. SignedLowerLimit := $7FFFFFFF;
  10354. SignedLowerLimitBottom := -2147483648;
  10355. UpperLimit := $FFFFFFFF;
  10356. SignedUpperLimit := $7FFFFFFF;
  10357. SignedUpperLimitBottom := -2147483648;
  10358. MinSize := S_L;
  10359. MaxSize := S_L;
  10360. end;
  10361. {$endif x86_64}
  10362. else
  10363. InternalError(2020112301);
  10364. end;
  10365. TestValMin := 0;
  10366. TestValMax := LowerLimit;
  10367. TestValSignedMax := SignedLowerLimit;
  10368. TryShiftDownLimit := LowerLimit;
  10369. TryShiftDown := S_NO;
  10370. ShiftDownOverflow := False;
  10371. RegChanged := False;
  10372. BitwiseOnly := True;
  10373. OrXorUsed := False;
  10374. UpperSignedOverflow := False;
  10375. LowerSignedOverflow := False;
  10376. UpperUnsignedOverflow := False;
  10377. LowerUnsignedOverflow := False;
  10378. hp1 := p;
  10379. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10380. (hp1.typ = ait_instruction) and
  10381. (
  10382. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10383. instruction that doesn't actually contain ThisReg }
  10384. (cs_opt_level3 in current_settings.optimizerswitches) or
  10385. { This allows this Movx optimisation to work through the SETcc instructions
  10386. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10387. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10388. skip over these SETcc instructions). }
  10389. (taicpu(hp1).opcode = A_SETcc) or
  10390. RegInInstruction(ThisReg, hp1)
  10391. ) do
  10392. begin
  10393. case taicpu(hp1).opcode of
  10394. A_INC,A_DEC:
  10395. begin
  10396. { Has to be an exact match on the register }
  10397. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10398. Break;
  10399. if taicpu(hp1).opcode = A_INC then
  10400. begin
  10401. Inc(TestValMin);
  10402. Inc(TestValMax);
  10403. Inc(TestValSignedMax);
  10404. end
  10405. else
  10406. begin
  10407. Dec(TestValMin);
  10408. Dec(TestValMax);
  10409. Dec(TestValSignedMax);
  10410. end;
  10411. end;
  10412. A_TEST, A_CMP:
  10413. begin
  10414. if (
  10415. { Too high a risk of non-linear behaviour that breaks DFA
  10416. here, unless it's cmp $0,%reg, which is equivalent to
  10417. test %reg,%reg }
  10418. OrXorUsed and
  10419. (taicpu(hp1).opcode = A_CMP) and
  10420. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10421. ) or
  10422. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10423. { Has to be an exact match on the register }
  10424. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10425. (
  10426. { Permit "test %reg,%reg" }
  10427. (taicpu(hp1).opcode = A_TEST) and
  10428. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10429. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10430. ) or
  10431. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10432. { Make sure the comparison value is not smaller than the
  10433. smallest allowed signed value for the minimum size (e.g.
  10434. -128 for 8-bit) }
  10435. not (
  10436. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10437. { Is it in the negative range? }
  10438. (
  10439. (taicpu(hp1).oper[0]^.val < 0) and
  10440. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10441. )
  10442. ) then
  10443. Break;
  10444. { Check to see if the active register is used afterwards }
  10445. TransferUsedRegs(TmpUsedRegs);
  10446. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10447. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10448. begin
  10449. { Make sure the comparison or any previous instructions
  10450. hasn't pushed the test values outside of the range of
  10451. MinSize }
  10452. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10453. begin
  10454. { Exceeded lower bound but not upper bound }
  10455. Exit;
  10456. end
  10457. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10458. begin
  10459. { Size didn't exceed lower bound }
  10460. TargetSize := MinSize;
  10461. end
  10462. else
  10463. Break;
  10464. case TargetSize of
  10465. S_B:
  10466. TargetSubReg := R_SUBL;
  10467. S_W:
  10468. TargetSubReg := R_SUBW;
  10469. S_L:
  10470. TargetSubReg := R_SUBD;
  10471. else
  10472. InternalError(2021051002);
  10473. end;
  10474. if TargetSize <> MaxSize then
  10475. begin
  10476. { Update the register to its new size }
  10477. setsubreg(ThisReg, TargetSubReg);
  10478. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10479. taicpu(hp1).oper[1]^.reg := ThisReg;
  10480. taicpu(hp1).opsize := TargetSize;
  10481. { Convert the input MOVZX to a MOV if necessary }
  10482. AdjustInitialLoadAndSize;
  10483. if (InstrMax >= 0) then
  10484. begin
  10485. for Index := 0 to InstrMax do
  10486. begin
  10487. { If p_removed is true, then the original MOV/Z was removed
  10488. and removing the AND instruction may not be safe if it
  10489. appears first }
  10490. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10491. InternalError(2020112311);
  10492. if InstrList[Index].oper[0]^.typ = top_reg then
  10493. InstrList[Index].oper[0]^.reg := ThisReg;
  10494. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10495. InstrList[Index].opsize := MinSize;
  10496. end;
  10497. end;
  10498. Result := True;
  10499. end;
  10500. Exit;
  10501. end;
  10502. end;
  10503. A_SETcc:
  10504. begin
  10505. { This allows this Movx optimisation to work through the SETcc instructions
  10506. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10507. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10508. skip over these SETcc instructions). }
  10509. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10510. { Of course, break out if the current register is used }
  10511. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10512. Break
  10513. else
  10514. { We must use Continue so the instruction doesn't get added
  10515. to InstrList }
  10516. Continue;
  10517. end;
  10518. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10519. begin
  10520. if
  10521. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10522. { Has to be an exact match on the register }
  10523. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10524. (
  10525. (
  10526. (taicpu(hp1).oper[0]^.typ = top_const) and
  10527. (
  10528. (
  10529. (taicpu(hp1).opcode = A_SHL) and
  10530. (
  10531. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10532. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10533. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10534. )
  10535. ) or (
  10536. (taicpu(hp1).opcode <> A_SHL) and
  10537. (
  10538. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10539. { Is it in the negative range? }
  10540. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10541. )
  10542. )
  10543. )
  10544. ) or (
  10545. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10546. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10547. )
  10548. ) then
  10549. Break;
  10550. { Only process OR and XOR if there are only bitwise operations,
  10551. since otherwise they can too easily fool the data flow
  10552. analysis (they can cause non-linear behaviour) }
  10553. case taicpu(hp1).opcode of
  10554. A_ADD:
  10555. begin
  10556. if OrXorUsed then
  10557. { Too high a risk of non-linear behaviour that breaks DFA here }
  10558. Break
  10559. else
  10560. BitwiseOnly := False;
  10561. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10562. begin
  10563. TestValMin := TestValMin * 2;
  10564. TestValMax := TestValMax * 2;
  10565. TestValSignedMax := TestValSignedMax * 2;
  10566. end
  10567. else
  10568. begin
  10569. WorkingValue := taicpu(hp1).oper[0]^.val;
  10570. TestValMin := TestValMin + WorkingValue;
  10571. TestValMax := TestValMax + WorkingValue;
  10572. TestValSignedMax := TestValSignedMax + WorkingValue;
  10573. end;
  10574. end;
  10575. A_SUB:
  10576. begin
  10577. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10578. begin
  10579. TestValMin := 0;
  10580. TestValMax := 0;
  10581. TestValSignedMax := 0;
  10582. end
  10583. else
  10584. begin
  10585. if OrXorUsed then
  10586. { Too high a risk of non-linear behaviour that breaks DFA here }
  10587. Break
  10588. else
  10589. BitwiseOnly := False;
  10590. WorkingValue := taicpu(hp1).oper[0]^.val;
  10591. TestValMin := TestValMin - WorkingValue;
  10592. TestValMax := TestValMax - WorkingValue;
  10593. TestValSignedMax := TestValSignedMax - WorkingValue;
  10594. end;
  10595. end;
  10596. A_AND:
  10597. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10598. begin
  10599. { we might be able to go smaller if AND appears first }
  10600. if InstrMax = -1 then
  10601. case MinSize of
  10602. S_B:
  10603. ;
  10604. S_W:
  10605. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10606. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10607. begin
  10608. TryShiftDown := S_B;
  10609. TryShiftDownLimit := $FF;
  10610. end;
  10611. S_L:
  10612. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10613. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10614. begin
  10615. TryShiftDown := S_B;
  10616. TryShiftDownLimit := $FF;
  10617. end
  10618. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10619. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10620. begin
  10621. TryShiftDown := S_W;
  10622. TryShiftDownLimit := $FFFF;
  10623. end;
  10624. else
  10625. InternalError(2020112320);
  10626. end;
  10627. WorkingValue := taicpu(hp1).oper[0]^.val;
  10628. TestValMin := TestValMin and WorkingValue;
  10629. TestValMax := TestValMax and WorkingValue;
  10630. TestValSignedMax := TestValSignedMax and WorkingValue;
  10631. end;
  10632. A_OR:
  10633. begin
  10634. if not BitwiseOnly then
  10635. Break;
  10636. OrXorUsed := True;
  10637. WorkingValue := taicpu(hp1).oper[0]^.val;
  10638. TestValMin := TestValMin or WorkingValue;
  10639. TestValMax := TestValMax or WorkingValue;
  10640. TestValSignedMax := TestValSignedMax or WorkingValue;
  10641. end;
  10642. A_XOR:
  10643. begin
  10644. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10645. begin
  10646. TestValMin := 0;
  10647. TestValMax := 0;
  10648. TestValSignedMax := 0;
  10649. end
  10650. else
  10651. begin
  10652. if not BitwiseOnly then
  10653. Break;
  10654. OrXorUsed := True;
  10655. WorkingValue := taicpu(hp1).oper[0]^.val;
  10656. TestValMin := TestValMin xor WorkingValue;
  10657. TestValMax := TestValMax xor WorkingValue;
  10658. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10659. end;
  10660. end;
  10661. A_SHL:
  10662. begin
  10663. BitwiseOnly := False;
  10664. WorkingValue := taicpu(hp1).oper[0]^.val;
  10665. TestValMin := TestValMin shl WorkingValue;
  10666. TestValMax := TestValMax shl WorkingValue;
  10667. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10668. end;
  10669. A_SHR,
  10670. { The first instruction was MOVZX, so the value won't be negative }
  10671. A_SAR:
  10672. begin
  10673. if InstrMax <> -1 then
  10674. BitwiseOnly := False
  10675. else
  10676. { we might be able to go smaller if SHR appears first }
  10677. case MinSize of
  10678. S_B:
  10679. ;
  10680. S_W:
  10681. if (taicpu(hp1).oper[0]^.val >= 8) then
  10682. begin
  10683. TryShiftDown := S_B;
  10684. TryShiftDownLimit := $FF;
  10685. TryShiftDownSignedLimit := $7F;
  10686. TryShiftDownSignedLimitLower := -128;
  10687. end;
  10688. S_L:
  10689. if (taicpu(hp1).oper[0]^.val >= 24) then
  10690. begin
  10691. TryShiftDown := S_B;
  10692. TryShiftDownLimit := $FF;
  10693. TryShiftDownSignedLimit := $7F;
  10694. TryShiftDownSignedLimitLower := -128;
  10695. end
  10696. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10697. begin
  10698. TryShiftDown := S_W;
  10699. TryShiftDownLimit := $FFFF;
  10700. TryShiftDownSignedLimit := $7FFF;
  10701. TryShiftDownSignedLimitLower := -32768;
  10702. end;
  10703. else
  10704. InternalError(2020112321);
  10705. end;
  10706. WorkingValue := taicpu(hp1).oper[0]^.val;
  10707. if taicpu(hp1).opcode = A_SAR then
  10708. begin
  10709. TestValMin := SarInt64(TestValMin, WorkingValue);
  10710. TestValMax := SarInt64(TestValMax, WorkingValue);
  10711. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10712. end
  10713. else
  10714. begin
  10715. TestValMin := TestValMin shr WorkingValue;
  10716. TestValMax := TestValMax shr WorkingValue;
  10717. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10718. end;
  10719. end;
  10720. else
  10721. InternalError(2020112303);
  10722. end;
  10723. end;
  10724. (*
  10725. A_IMUL:
  10726. case taicpu(hp1).ops of
  10727. 2:
  10728. begin
  10729. if not MatchOpType(hp1, top_reg, top_reg) or
  10730. { Has to be an exact match on the register }
  10731. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10732. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10733. Break;
  10734. TestValMin := TestValMin * TestValMin;
  10735. TestValMax := TestValMax * TestValMax;
  10736. TestValSignedMax := TestValSignedMax * TestValMax;
  10737. end;
  10738. 3:
  10739. begin
  10740. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10741. { Has to be an exact match on the register }
  10742. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10743. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10744. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10745. { Is it in the negative range? }
  10746. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10747. Break;
  10748. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10749. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10750. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10751. end;
  10752. else
  10753. Break;
  10754. end;
  10755. A_IDIV:
  10756. case taicpu(hp1).ops of
  10757. 3:
  10758. begin
  10759. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10760. { Has to be an exact match on the register }
  10761. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10762. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10763. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10764. { Is it in the negative range? }
  10765. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10766. Break;
  10767. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10768. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10769. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10770. end;
  10771. else
  10772. Break;
  10773. end;
  10774. *)
  10775. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10776. begin
  10777. { If there are no instructions in between, then we might be able to make a saving }
  10778. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10779. Break;
  10780. { We have something like:
  10781. movzbw %dl,%dx
  10782. ...
  10783. movswl %dx,%edx
  10784. Change the latter to a zero-extension then enter the
  10785. A_MOVZX case branch.
  10786. }
  10787. {$ifdef x86_64}
  10788. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10789. begin
  10790. { this becomes a zero extension from 32-bit to 64-bit, but
  10791. the upper 32 bits are already zero, so just delete the
  10792. instruction }
  10793. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10794. RemoveInstruction(hp1);
  10795. Result := True;
  10796. Exit;
  10797. end
  10798. else
  10799. {$endif x86_64}
  10800. begin
  10801. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10802. taicpu(hp1).opcode := A_MOVZX;
  10803. {$ifdef x86_64}
  10804. case taicpu(hp1).opsize of
  10805. S_BQ:
  10806. begin
  10807. taicpu(hp1).opsize := S_BL;
  10808. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10809. end;
  10810. S_WQ:
  10811. begin
  10812. taicpu(hp1).opsize := S_WL;
  10813. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10814. end;
  10815. S_LQ:
  10816. begin
  10817. taicpu(hp1).opcode := A_MOV;
  10818. taicpu(hp1).opsize := S_L;
  10819. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10820. { In this instance, we need to break out because the
  10821. instruction is no longer MOVZX or MOVSXD }
  10822. Result := True;
  10823. Exit;
  10824. end;
  10825. else
  10826. ;
  10827. end;
  10828. {$endif x86_64}
  10829. Result := CompressInstructions;
  10830. Exit;
  10831. end;
  10832. end;
  10833. A_MOVZX:
  10834. begin
  10835. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10836. Break;
  10837. if (InstrMax = -1) then
  10838. begin
  10839. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10840. begin
  10841. { Optimise around i40003 }
  10842. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10843. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10844. {$ifndef x86_64}
  10845. and (
  10846. (taicpu(p).oper[0]^.typ <> top_reg) or
  10847. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10848. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10849. )
  10850. {$endif not x86_64}
  10851. then
  10852. begin
  10853. if (taicpu(p).oper[0]^.typ = top_reg) then
  10854. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10855. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10856. taicpu(p).opsize := S_BL;
  10857. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10858. RemoveInstruction(hp1);
  10859. Result := True;
  10860. Exit;
  10861. end;
  10862. end
  10863. else
  10864. begin
  10865. { Will return false if the second parameter isn't ThisReg
  10866. (can happen on -O2 and under) }
  10867. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10868. begin
  10869. { The two MOVZX instructions are adjacent, so remove the first one }
  10870. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10871. RemoveCurrentP(p);
  10872. Result := True;
  10873. Exit;
  10874. end;
  10875. Break;
  10876. end;
  10877. end;
  10878. Result := CompressInstructions;
  10879. Exit;
  10880. end;
  10881. else
  10882. { This includes ADC, SBB and IDIV }
  10883. Break;
  10884. end;
  10885. if not CheckOverflowConditions then
  10886. Break;
  10887. { Contains highest index (so instruction count - 1) }
  10888. Inc(InstrMax);
  10889. if InstrMax > High(InstrList) then
  10890. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10891. InstrList[InstrMax] := taicpu(hp1);
  10892. end;
  10893. end;
  10894. {$pop}
  10895. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10896. var
  10897. hp1 : tai;
  10898. begin
  10899. Result:=false;
  10900. if (taicpu(p).ops >= 2) and
  10901. ((taicpu(p).oper[0]^.typ = top_const) or
  10902. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10903. (taicpu(p).oper[1]^.typ = top_reg) and
  10904. ((taicpu(p).ops = 2) or
  10905. ((taicpu(p).oper[2]^.typ = top_reg) and
  10906. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10907. GetLastInstruction(p,hp1) and
  10908. MatchInstruction(hp1,A_MOV,[]) and
  10909. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10910. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10911. begin
  10912. TransferUsedRegs(TmpUsedRegs);
  10913. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10914. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10915. { change
  10916. mov reg1,reg2
  10917. imul y,reg2 to imul y,reg1,reg2 }
  10918. begin
  10919. taicpu(p).ops := 3;
  10920. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10921. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10922. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10923. RemoveInstruction(hp1);
  10924. result:=true;
  10925. end;
  10926. end;
  10927. end;
  10928. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10929. var
  10930. ThisLabel: TAsmLabel;
  10931. begin
  10932. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10933. ThisLabel.decrefs;
  10934. taicpu(p).condition := C_None;
  10935. taicpu(p).opcode := A_RET;
  10936. taicpu(p).is_jmp := false;
  10937. taicpu(p).ops := taicpu(ret_p).ops;
  10938. case taicpu(ret_p).ops of
  10939. 0:
  10940. taicpu(p).clearop(0);
  10941. 1:
  10942. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10943. else
  10944. internalerror(2016041301);
  10945. end;
  10946. { If the original label is now dead, it might turn out that the label
  10947. immediately follows p. As a result, everything beyond it, which will
  10948. be just some final register configuration and a RET instruction, is
  10949. now dead code. [Kit] }
  10950. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10951. running RemoveDeadCodeAfterJump for each RET instruction, because
  10952. this optimisation rarely happens and most RETs appear at the end of
  10953. routines where there is nothing that can be stripped. [Kit] }
  10954. if not ThisLabel.is_used then
  10955. RemoveDeadCodeAfterJump(p);
  10956. end;
  10957. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10958. var
  10959. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10960. Unconditional, PotentialModified: Boolean;
  10961. OperPtr: POper;
  10962. NewRef: TReference;
  10963. InstrList: array of taicpu;
  10964. InstrMax, Index: Integer;
  10965. const
  10966. {$ifdef DEBUG_AOPTCPU}
  10967. SNoFlags: shortstring = ' so the flags aren''t modified';
  10968. {$else DEBUG_AOPTCPU}
  10969. SNoFlags = '';
  10970. {$endif DEBUG_AOPTCPU}
  10971. begin
  10972. Result:=false;
  10973. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10974. begin
  10975. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10976. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10977. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10978. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10979. GetNextInstruction(hp1, hp2) and
  10980. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10981. { Change from: To:
  10982. set(C) %reg j(~C) label
  10983. test %reg,%reg/cmp $0,%reg
  10984. je label
  10985. set(C) %reg j(C) label
  10986. test %reg,%reg/cmp $0,%reg
  10987. jne label
  10988. (Also do something similar with sete/setne instead of je/jne)
  10989. }
  10990. begin
  10991. { Before we do anything else, we need to check the instructions
  10992. in between SETcc and TEST to make sure they don't modify the
  10993. FLAGS register - if -O2 or under, there won't be any
  10994. instructions between SET and TEST }
  10995. TransferUsedRegs(TmpUsedRegs);
  10996. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10997. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10998. begin
  10999. next := p;
  11000. SetLength(InstrList, 0);
  11001. InstrMax := -1;
  11002. PotentialModified := False;
  11003. { Make a note of every instruction that modifies the FLAGS
  11004. register }
  11005. while GetNextInstruction(next, next) and (next <> hp1) do
  11006. begin
  11007. if next.typ <> ait_instruction then
  11008. { GetNextInstructionUsingReg should have returned False }
  11009. InternalError(2021051701);
  11010. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11011. begin
  11012. case taicpu(next).opcode of
  11013. A_SETcc,
  11014. A_CMOVcc,
  11015. A_Jcc:
  11016. begin
  11017. if PotentialModified then
  11018. { Not safe because the flags were modified earlier }
  11019. Exit
  11020. else
  11021. { Condition is the same as the initial SETcc, so this is safe
  11022. (don't add to instruction list though) }
  11023. Continue;
  11024. end;
  11025. A_ADD:
  11026. begin
  11027. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11028. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11029. (taicpu(next).oper[1]^.typ <> top_reg) or
  11030. { Must write to a register }
  11031. (taicpu(next).oper[0]^.typ = top_ref) then
  11032. { Require a constant or a register }
  11033. Exit;
  11034. PotentialModified := True;
  11035. end;
  11036. A_SUB:
  11037. begin
  11038. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11039. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11040. (taicpu(next).oper[1]^.typ <> top_reg) or
  11041. { Must write to a register }
  11042. (taicpu(next).oper[0]^.typ <> top_const) or
  11043. (taicpu(next).oper[0]^.val = $80000000) then
  11044. { Can't subtract a register with LEA - also
  11045. check that the value isn't -2^31, as this
  11046. can't be negated }
  11047. Exit;
  11048. PotentialModified := True;
  11049. end;
  11050. A_SAL,
  11051. A_SHL:
  11052. begin
  11053. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11054. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11055. (taicpu(next).oper[1]^.typ <> top_reg) or
  11056. { Must write to a register }
  11057. (taicpu(next).oper[0]^.typ <> top_const) or
  11058. (taicpu(next).oper[0]^.val < 0) or
  11059. (taicpu(next).oper[0]^.val > 3) then
  11060. Exit;
  11061. PotentialModified := True;
  11062. end;
  11063. A_IMUL:
  11064. begin
  11065. if (taicpu(next).ops <> 3) or
  11066. (taicpu(next).oper[1]^.typ <> top_reg) or
  11067. { Must write to a register }
  11068. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11069. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11070. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11071. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11072. Exit
  11073. else
  11074. PotentialModified := True;
  11075. end;
  11076. else
  11077. { Don't know how to change this, so abort }
  11078. Exit;
  11079. end;
  11080. { Contains highest index (so instruction count - 1) }
  11081. Inc(InstrMax);
  11082. if InstrMax > High(InstrList) then
  11083. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11084. InstrList[InstrMax] := taicpu(next);
  11085. end;
  11086. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11087. end;
  11088. if not Assigned(next) or (next <> hp1) then
  11089. { It should be equal to hp1 }
  11090. InternalError(2021051702);
  11091. { Cycle through each instruction and check to see if we can
  11092. change them to versions that don't modify the flags }
  11093. if (InstrMax >= 0) then
  11094. begin
  11095. for Index := 0 to InstrMax do
  11096. case InstrList[Index].opcode of
  11097. A_ADD:
  11098. begin
  11099. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11100. InstrList[Index].opcode := A_LEA;
  11101. reference_reset(NewRef, 1, []);
  11102. NewRef.base := InstrList[Index].oper[1]^.reg;
  11103. if InstrList[Index].oper[0]^.typ = top_reg then
  11104. begin
  11105. NewRef.index := InstrList[Index].oper[0]^.reg;
  11106. NewRef.scalefactor := 1;
  11107. end
  11108. else
  11109. NewRef.offset := InstrList[Index].oper[0]^.val;
  11110. InstrList[Index].loadref(0, NewRef);
  11111. end;
  11112. A_SUB:
  11113. begin
  11114. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11115. InstrList[Index].opcode := A_LEA;
  11116. reference_reset(NewRef, 1, []);
  11117. NewRef.base := InstrList[Index].oper[1]^.reg;
  11118. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11119. InstrList[Index].loadref(0, NewRef);
  11120. end;
  11121. A_SHL,
  11122. A_SAL:
  11123. begin
  11124. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11125. InstrList[Index].opcode := A_LEA;
  11126. reference_reset(NewRef, 1, []);
  11127. NewRef.index := InstrList[Index].oper[1]^.reg;
  11128. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11129. InstrList[Index].loadref(0, NewRef);
  11130. end;
  11131. A_IMUL:
  11132. begin
  11133. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11134. InstrList[Index].opcode := A_LEA;
  11135. reference_reset(NewRef, 1, []);
  11136. NewRef.index := InstrList[Index].oper[1]^.reg;
  11137. case InstrList[Index].oper[0]^.val of
  11138. 2, 4, 8:
  11139. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11140. else {3, 5 and 9}
  11141. begin
  11142. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11143. NewRef.base := InstrList[Index].oper[1]^.reg;
  11144. end;
  11145. end;
  11146. InstrList[Index].loadref(0, NewRef);
  11147. end;
  11148. else
  11149. InternalError(2021051710);
  11150. end;
  11151. end;
  11152. { Mark the FLAGS register as used across this whole block }
  11153. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11154. end;
  11155. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11156. JumpC := taicpu(hp2).condition;
  11157. Unconditional := False;
  11158. if conditions_equal(JumpC, C_E) then
  11159. SetC := inverse_cond(taicpu(p).condition)
  11160. else if conditions_equal(JumpC, C_NE) then
  11161. SetC := taicpu(p).condition
  11162. else
  11163. { We've got something weird here (and inefficent) }
  11164. begin
  11165. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11166. SetC := C_NONE;
  11167. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11168. if condition_in(C_AE, JumpC) then
  11169. Unconditional := True
  11170. else
  11171. { Not sure what to do with this jump - drop out }
  11172. Exit;
  11173. end;
  11174. RemoveInstruction(hp1);
  11175. if Unconditional then
  11176. MakeUnconditional(taicpu(hp2))
  11177. else
  11178. begin
  11179. if SetC = C_NONE then
  11180. InternalError(2018061402);
  11181. taicpu(hp2).SetCondition(SetC);
  11182. end;
  11183. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11184. TmpUsedRegs }
  11185. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11186. begin
  11187. RemoveCurrentp(p, hp2);
  11188. if taicpu(hp2).opcode = A_SETcc then
  11189. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11190. else
  11191. begin
  11192. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11193. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11194. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11195. end;
  11196. end
  11197. else
  11198. if taicpu(hp2).opcode = A_SETcc then
  11199. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11200. else
  11201. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11202. Result := True;
  11203. end
  11204. else if
  11205. { Make sure the instructions are adjacent }
  11206. (
  11207. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11208. GetNextInstruction(p, hp1)
  11209. ) and
  11210. MatchInstruction(hp1, A_MOV, [S_B]) and
  11211. { Writing to memory is allowed }
  11212. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11213. begin
  11214. {
  11215. Watch out for sequences such as:
  11216. set(c)b %regb
  11217. movb %regb,(ref)
  11218. movb $0,1(ref)
  11219. movb $0,2(ref)
  11220. movb $0,3(ref)
  11221. Much more efficient to turn it into:
  11222. movl $0,%regl
  11223. set(c)b %regb
  11224. movl %regl,(ref)
  11225. Or:
  11226. set(c)b %regb
  11227. movzbl %regb,%regl
  11228. movl %regl,(ref)
  11229. }
  11230. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11231. GetNextInstruction(hp1, hp2) and
  11232. MatchInstruction(hp2, A_MOV, [S_B]) and
  11233. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11234. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11235. begin
  11236. { Don't do anything else except set Result to True }
  11237. end
  11238. else
  11239. begin
  11240. if taicpu(p).oper[0]^.typ = top_reg then
  11241. begin
  11242. TransferUsedRegs(TmpUsedRegs);
  11243. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11244. end;
  11245. { If it's not a register, it's a memory address }
  11246. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11247. begin
  11248. { Even if the register is still in use, we can minimise the
  11249. pipeline stall by changing the MOV into another SETcc. }
  11250. taicpu(hp1).opcode := A_SETcc;
  11251. taicpu(hp1).condition := taicpu(p).condition;
  11252. if taicpu(hp1).oper[1]^.typ = top_ref then
  11253. begin
  11254. { Swapping the operand pointers like this is probably a
  11255. bit naughty, but it is far faster than using loadoper
  11256. to transfer the reference from oper[1] to oper[0] if
  11257. you take into account the extra procedure calls and
  11258. the memory allocation and deallocation required }
  11259. OperPtr := taicpu(hp1).oper[1];
  11260. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11261. taicpu(hp1).oper[0] := OperPtr;
  11262. end
  11263. else
  11264. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11265. taicpu(hp1).clearop(1);
  11266. taicpu(hp1).ops := 1;
  11267. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11268. end
  11269. else
  11270. begin
  11271. if taicpu(hp1).oper[1]^.typ = top_reg then
  11272. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11273. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11274. RemoveInstruction(hp1);
  11275. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11276. end
  11277. end;
  11278. Result := True;
  11279. end;
  11280. end;
  11281. end;
  11282. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11283. var
  11284. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11285. TargetReg: TRegister;
  11286. condition, inverted_condition: TAsmCond;
  11287. FoundMOV: Boolean;
  11288. begin
  11289. Result := False;
  11290. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11291. create the most optimial instructions possible due to limited
  11292. register availability, and there are situations where two
  11293. complementary "simple" CMOV blocks are created which, after the fact
  11294. can be merged into a "double" block. For example:
  11295. movw $257,%ax
  11296. movw $2,%r8w
  11297. xorl r9d,%r9d
  11298. testw $16,18(%rcx)
  11299. cmovew %ax,%dx
  11300. cmovew %r8w,%bx
  11301. cmovel %r9d,%r14d
  11302. movw $1283,%ax
  11303. movw $4,%r8w
  11304. movl $9,%r9d
  11305. cmovnew %ax,%dx
  11306. cmovnew %r8w,%bx
  11307. cmovnel %r9d,%r14d
  11308. The CMOVNE instructions at the end can be removed, and the
  11309. destination registers copied into the MOV instructions directly
  11310. above them, before finally being moved to before the first CMOVE
  11311. instructions, to produce:
  11312. movw $257,%ax
  11313. movw $2,%r8w
  11314. xorl r9d,%r9d
  11315. testw $16,18(%rcx)
  11316. movw $1283,%dx
  11317. movw $4,%bx
  11318. movl $9,%r14d
  11319. cmovew %ax,%dx
  11320. cmovew %r8w,%bx
  11321. cmovel %r9d,%r14d
  11322. Which can then be later optimised to:
  11323. movw $257,%ax
  11324. movw $2,%r8w
  11325. xorl r9d,%r9d
  11326. movw $1283,%dx
  11327. movw $4,%bx
  11328. movl $9,%r14d
  11329. testw $16,18(%rcx)
  11330. cmovew %ax,%dx
  11331. cmovew %r8w,%bx
  11332. cmovel %r9d,%r14d
  11333. }
  11334. TargetReg := taicpu(hp1).oper[1]^.reg;
  11335. condition := taicpu(hp1).condition;
  11336. inverted_condition := inverse_cond(condition);
  11337. pFirstMov := nil;
  11338. pLastMov := nil;
  11339. pCMOV := nil;
  11340. if (p.typ = ait_instruction) then
  11341. pCond := p
  11342. else if not GetNextInstruction(p, pCond) then
  11343. InternalError(2024012501);
  11344. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11345. { We should get the CMP or TEST instructeion }
  11346. InternalError(2024012502);
  11347. if (
  11348. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11349. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11350. ) then
  11351. begin
  11352. { We have to tread carefully here, hence why we're not using
  11353. GetNextInstructionUsingReg... we can only accept MOV and other
  11354. CMOV instructions. Anything else and we must drop out}
  11355. hp2 := hp1;
  11356. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11357. begin
  11358. if (hp2.typ <> ait_instruction) then
  11359. Exit;
  11360. case taicpu(hp2).opcode of
  11361. A_MOV:
  11362. begin
  11363. if not Assigned(pFirstMov) then
  11364. pFirstMov := hp2;
  11365. pLastMOV := hp2;
  11366. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11367. { Something different - drop out }
  11368. Exit;
  11369. { Otherwise, leave it for now }
  11370. end;
  11371. A_CMOVcc:
  11372. begin
  11373. if taicpu(hp2).condition = inverted_condition then
  11374. begin
  11375. { We found what we're looking for }
  11376. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11377. begin
  11378. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11379. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11380. begin
  11381. pCMOV := hp2;
  11382. Break;
  11383. end
  11384. else
  11385. { Unsafe reference - drop out }
  11386. Exit;
  11387. end;
  11388. end
  11389. else if taicpu(hp2).condition <> condition then
  11390. { Something weird - drop out }
  11391. Exit;
  11392. end;
  11393. else
  11394. { Invalid }
  11395. Exit;
  11396. end;
  11397. end;
  11398. if not Assigned(pCMOV) then
  11399. { No complementary CMOV found }
  11400. Exit;
  11401. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11402. begin
  11403. { Don't need to do anything special or search for a matching MOV }
  11404. Asml.Remove(pCMOV);
  11405. if RegInInstruction(TargetReg, pCond) then
  11406. { Make sure we don't overwrite the register if it's being used in the condition }
  11407. Asml.InsertAfter(pCMOV, pCond)
  11408. else
  11409. Asml.InsertBefore(pCMOV, pCond);
  11410. taicpu(pCMOV).opcode := A_MOV;
  11411. taicpu(pCMOV).condition := C_None;
  11412. { Don't need to worry about allocating new registers in these cases }
  11413. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11414. Result := True;
  11415. Exit;
  11416. end
  11417. else
  11418. begin
  11419. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11420. FoundMOV := False;
  11421. { Search for the MOV that sets the target register }
  11422. hp2 := pFirstMov;
  11423. repeat
  11424. if (taicpu(hp2).opcode = A_MOV) and
  11425. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11426. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11427. begin
  11428. { Change the destination }
  11429. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11430. if not FoundMOV then
  11431. begin
  11432. FoundMOV := True;
  11433. { Make sure the register is allocated }
  11434. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11435. end;
  11436. hp1 := tai(hp2.Previous);
  11437. Asml.Remove(hp2);
  11438. if RegInInstruction(TargetReg, pCond) then
  11439. { Make sure we don't overwrite the register if it's being used in the condition }
  11440. Asml.InsertAfter(hp2, pCond)
  11441. else
  11442. Asml.InsertBefore(hp2, pCond);
  11443. if (hp2 = pLastMov) then
  11444. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11445. Break;
  11446. hp2 := hp1;
  11447. end;
  11448. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11449. if FoundMOV then
  11450. { Delete the CMOV }
  11451. RemoveInstruction(pCMOV)
  11452. else
  11453. begin
  11454. { If no MOV was found, we have to actually move and transmute the CMOV }
  11455. Asml.Remove(pCMOV);
  11456. if RegInInstruction(TargetReg, pCond) then
  11457. { Make sure we don't overwrite the register if it's being used in the condition }
  11458. Asml.InsertAfter(pCMOV, pCond)
  11459. else
  11460. Asml.InsertBefore(pCMOV, pCond);
  11461. taicpu(pCMOV).opcode := A_MOV;
  11462. taicpu(pCMOV).condition := C_None;
  11463. end;
  11464. Result := True;
  11465. Exit;
  11466. end;
  11467. end;
  11468. end;
  11469. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11470. var
  11471. hp1, hp2, pCond: tai;
  11472. begin
  11473. Result := False;
  11474. { Search ahead for CMOV instructions }
  11475. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11476. begin
  11477. hp1 := p;
  11478. hp2 := p;
  11479. pCond := nil; { To prevent compiler warnings }
  11480. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11481. DEFAULTFLAGS }
  11482. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11483. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11484. pCond := p;
  11485. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11486. begin
  11487. if (hp1.typ <> ait_instruction) then
  11488. { Break out on markers and labels etc. }
  11489. Break;
  11490. case taicpu(hp1).opcode of
  11491. A_MOV:
  11492. { Ignore regular MOVs unless they are obviously not related
  11493. to a CMOV block }
  11494. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11495. Break;
  11496. A_CMOVcc:
  11497. if TryCmpCMovOpts(pCond, hp1) then
  11498. begin
  11499. hp1 := hp2;
  11500. { p itself isn't changed, and we're still inside a
  11501. while loop to catch subsequent CMOVs, so just flag
  11502. a new iteration }
  11503. Include(OptsToCheck, aoc_ForceNewIteration);
  11504. Continue;
  11505. end;
  11506. else
  11507. { Drop out if we find anything else }
  11508. Break;
  11509. end;
  11510. hp2 := hp1;
  11511. end;
  11512. end;
  11513. end;
  11514. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11515. var
  11516. hp1, hp2, pCond: tai;
  11517. SourceReg, TargetReg: TRegister;
  11518. begin
  11519. Result := False;
  11520. { In some situations, we end up with an inefficient arrangement of
  11521. instructions in the form of:
  11522. or %reg1,%reg2
  11523. (%reg1 deallocated)
  11524. test %reg2,%reg2
  11525. mov x,%reg2
  11526. we may be able to swap and rearrange the registers to produce:
  11527. or %reg2,%reg1
  11528. mov x,%reg2
  11529. test %reg1,%reg1
  11530. (%reg1 deallocated)
  11531. }
  11532. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11533. (taicpu(p).oper[1]^.typ = top_reg) and
  11534. (
  11535. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11536. MatchOperand(taicpu(p).oper[0]^, -1)
  11537. ) and
  11538. GetNextInstruction(p, hp1) and
  11539. MatchInstruction(hp1, A_MOV, []) and
  11540. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11541. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11542. begin
  11543. TargetReg := taicpu(p).oper[1]^.reg;
  11544. { Now look backwards to find a simple commutative operation: ADD,
  11545. IMUL (2-register version), OR, AND or XOR - whose destination
  11546. register is the same as TEST }
  11547. hp2 := p;
  11548. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11549. if RegInInstruction(TargetReg, hp2) then
  11550. begin
  11551. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11552. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11553. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11554. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11555. begin
  11556. SourceReg := taicpu(hp2).oper[0]^.reg;
  11557. if
  11558. { Make sure the MOV doesn't use the other register }
  11559. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11560. { And make sure the source register is not used afterwards }
  11561. not RegInUsedRegs(SourceReg, UsedRegs) then
  11562. begin
  11563. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11564. taicpu(hp2).oper[0]^.reg := TargetReg;
  11565. taicpu(hp2).oper[1]^.reg := SourceReg;
  11566. if taicpu(p).oper[0]^.typ = top_reg then
  11567. taicpu(p).oper[0]^.reg := SourceReg;
  11568. taicpu(p).oper[1]^.reg := SourceReg;
  11569. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11570. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11571. Include(OptsToCheck, aoc_ForceNewIteration);
  11572. { We can still check the following optimisations since
  11573. the instruction is still a TEST }
  11574. end;
  11575. end;
  11576. Break;
  11577. end;
  11578. end;
  11579. { Search ahead3 for CMOV instructions }
  11580. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11581. begin
  11582. hp1 := p;
  11583. hp2 := p;
  11584. pCond := nil; { To prevent compiler warnings }
  11585. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11586. DEFAULTFLAGS }
  11587. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11588. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11589. pCond := p;
  11590. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11591. begin
  11592. if (hp1.typ <> ait_instruction) then
  11593. { Break out on markers and labels etc. }
  11594. Break;
  11595. case taicpu(hp1).opcode of
  11596. A_MOV:
  11597. { Ignore regular MOVs unless they are obviously not related
  11598. to a CMOV block }
  11599. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11600. Break;
  11601. A_CMOVcc:
  11602. if TryCmpCMovOpts(pCond, hp1) then
  11603. begin
  11604. hp1 := hp2;
  11605. { p itself isn't changed, and we're still inside a
  11606. while loop to catch subsequent CMOVs, so just flag
  11607. a new iteration }
  11608. Include(OptsToCheck, aoc_ForceNewIteration);
  11609. Continue;
  11610. end;
  11611. else
  11612. { Drop out if we find anything else }
  11613. Break;
  11614. end;
  11615. hp2 := hp1;
  11616. end;
  11617. end;
  11618. end;
  11619. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11620. var
  11621. hp1: tai;
  11622. Count: Integer;
  11623. OrigLabel: TAsmLabel;
  11624. begin
  11625. result := False;
  11626. { Sometimes, the optimisations below can permit this }
  11627. RemoveDeadCodeAfterJump(p);
  11628. 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
  11629. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11630. begin
  11631. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11632. { Also a side-effect of optimisations }
  11633. if CollapseZeroDistJump(p, OrigLabel) then
  11634. begin
  11635. Result := True;
  11636. Exit;
  11637. end;
  11638. hp1 := GetLabelWithSym(OrigLabel);
  11639. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11640. begin
  11641. if taicpu(hp1).opcode = A_RET then
  11642. begin
  11643. {
  11644. change
  11645. jmp .L1
  11646. ...
  11647. .L1:
  11648. ret
  11649. into
  11650. ret
  11651. }
  11652. begin
  11653. ConvertJumpToRET(p, hp1);
  11654. result:=true;
  11655. end;
  11656. end
  11657. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11658. not (cs_opt_size in current_settings.optimizerswitches) and
  11659. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11660. begin
  11661. Result := True;
  11662. Exit;
  11663. end;
  11664. end;
  11665. end;
  11666. end;
  11667. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11668. begin
  11669. Result := assigned(p) and
  11670. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11671. (taicpu(p).oper[1]^.typ = top_reg) and
  11672. (
  11673. (taicpu(p).oper[0]^.typ = top_reg) or
  11674. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11675. it is not expected that this can cause a seg. violation }
  11676. (
  11677. (taicpu(p).oper[0]^.typ = top_ref) and
  11678. { TODO: Can we detect which references become constants at this
  11679. stage so we don't have to do a blanket ban? }
  11680. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11681. (
  11682. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11683. (
  11684. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11685. not RefModified and
  11686. { If the reference also appears in the condition, then we know it's safe, otherwise
  11687. any kind of access violation would have occurred already }
  11688. Assigned(cond_p) and
  11689. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11690. (cond_p.typ = ait_instruction) and
  11691. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11692. { Just consider 2-operand comparison instructions for now to be safe }
  11693. (taicpu(cond_p).ops = 2) and
  11694. (
  11695. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11696. (
  11697. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11698. { Don't risk identical registers but different offsets, as we may have constructs
  11699. such as buffer streams with things like length fields that indicate whether
  11700. any more data follows. And there are probably some contrived examples where
  11701. writing to offsets behind the one being read also lead to access violations }
  11702. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11703. (
  11704. { Check that we're not modifying a register that appears in the reference }
  11705. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11706. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11707. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11708. )
  11709. )
  11710. )
  11711. )
  11712. )
  11713. )
  11714. );
  11715. end;
  11716. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11717. begin
  11718. { Update integer registers, ignoring deallocations }
  11719. repeat
  11720. while assigned(p) and
  11721. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11722. (p.typ = ait_label) or
  11723. ((p.typ = ait_marker) and
  11724. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11725. p := tai(p.next);
  11726. while assigned(p) and
  11727. (p.typ=ait_RegAlloc) Do
  11728. begin
  11729. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11730. begin
  11731. case tai_regalloc(p).ratype of
  11732. ra_alloc :
  11733. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11734. else
  11735. ;
  11736. end;
  11737. end;
  11738. p := tai(p.next);
  11739. end;
  11740. until not(assigned(p)) or
  11741. (not(p.typ in SkipInstr) and
  11742. not((p.typ = ait_label) and
  11743. labelCanBeSkipped(tai_label(p))));
  11744. end;
  11745. {$ifndef 8086}
  11746. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11747. begin
  11748. Result := False;
  11749. EndJump := nil;
  11750. BlockStop := nil;
  11751. while (BlockStart <> fOptimizer.BlockEnd) and
  11752. { stop on labels }
  11753. (BlockStart.typ <> ait_label) do
  11754. begin
  11755. { Keep track of all integer registers that are used }
  11756. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11757. if BlockStart.typ = ait_instruction then
  11758. begin
  11759. if (taicpu(BlockStart).opcode = A_JMP) then
  11760. begin
  11761. if not IsJumpToLabel(taicpu(BlockStart)) or
  11762. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11763. Exit;
  11764. EndJump := BlockStart;
  11765. Break;
  11766. end
  11767. { Check to see if we have a valid MOV instruction instead }
  11768. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11769. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11770. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11771. begin
  11772. Exit;
  11773. end
  11774. else
  11775. { This will be a valid MOV }
  11776. fAllocationRange := BlockStart;
  11777. end;
  11778. OneBeforeBlock := BlockStart;
  11779. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11780. end;
  11781. if (BlockStart = fOptimizer.BlockEnd) then
  11782. Exit;
  11783. BlockStop := BlockStart;
  11784. Result := True;
  11785. end;
  11786. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11787. var
  11788. hp1: tai;
  11789. RefModified: Boolean;
  11790. begin
  11791. Result := 0;
  11792. hp1 := BlockStart;
  11793. RefModified := False; { As long as the condition is inverted, this can be reset }
  11794. while assigned(hp1) and
  11795. (hp1 <> BlockStop) do
  11796. begin
  11797. case hp1.typ of
  11798. ait_instruction:
  11799. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11800. begin
  11801. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11802. begin
  11803. Inc(Result);
  11804. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11805. Assigned(fCondition) and
  11806. { Will have 2 operands }
  11807. (
  11808. (
  11809. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11810. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11811. ) or
  11812. (
  11813. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11814. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11815. )
  11816. ) then
  11817. { It is no longer safe to use the reference in the condition.
  11818. this prevents problems such as:
  11819. mov (%reg),%reg
  11820. mov (%reg),...
  11821. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11822. (fixes #40165)
  11823. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11824. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11825. }
  11826. RefModified := True;
  11827. end
  11828. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11829. { CMOV with constants grows the code size }
  11830. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11831. begin
  11832. { Register was reserved by TryCMOVConst and
  11833. stored on ConstRegs }
  11834. end
  11835. else
  11836. begin
  11837. Result := -1;
  11838. Exit;
  11839. end;
  11840. end
  11841. else
  11842. begin
  11843. Result := -1;
  11844. Exit;
  11845. end;
  11846. else
  11847. { Most likely an align };
  11848. end;
  11849. fOptimizer.GetNextInstruction(hp1, hp1);
  11850. end;
  11851. end;
  11852. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11853. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11854. (this is done as a separate stage because the double types are extensions of the branching type,
  11855. but we can't discount the conditional jump until the last step) }
  11856. procedure EvaluateBranchingType;
  11857. begin
  11858. Inc(CMOVScore);
  11859. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11860. { Too many instructions to be worthwhile }
  11861. fState := tsInvalid;
  11862. end;
  11863. var
  11864. hp1: tai;
  11865. Count: Integer;
  11866. begin
  11867. { Table of valid CMOV block types
  11868. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11869. ---------- --------- --------- --------- --------- ---------
  11870. tsSimple X Yes X X X
  11871. tsDetour = 1st X X X X
  11872. tsBranching <> Mid Yes X X X
  11873. tsDouble End-label Yes * Yes X Yes
  11874. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11875. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11876. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11877. * Only one reference allowed
  11878. }
  11879. hp1 := nil; { To prevent compiler warnings }
  11880. Optimizer.CopyUsedRegs(RegisterTracking);
  11881. fOptimizer := Optimizer;
  11882. fLabel := AFirstLabel;
  11883. CMOVScore := 0;
  11884. ConstCount := 0;
  11885. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11886. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11887. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11888. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11889. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11890. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11891. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11892. fInsertionPoint := p_initialjump;
  11893. fCondition := nil;
  11894. fInitialJump := p_initialjump;
  11895. fFirstMovBlock := p_initialmov;
  11896. fFirstMovBlockStop := nil;
  11897. fSecondJump := nil;
  11898. fSecondMovBlock := nil;
  11899. fSecondMovBlockStop := nil;
  11900. fMidLabel := nil;
  11901. fSecondJump := nil;
  11902. fSecondMovBlock := nil;
  11903. fEndLabel := nil;
  11904. fAllocationRange := nil;
  11905. { Assume it all goes horribly wrong! }
  11906. fState := tsInvalid;
  11907. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11908. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11909. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11910. begin
  11911. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11912. for Count := 0 to 1 do
  11913. with taicpu(fCondition).oper[Count]^ do
  11914. case typ of
  11915. top_reg:
  11916. if getregtype(reg) = R_INTREGISTER then
  11917. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11918. top_ref:
  11919. begin
  11920. if
  11921. {$ifdef x86_64}
  11922. (ref^.base <> NR_RIP) and
  11923. {$endif x86_64}
  11924. (ref^.base <> NR_NO) then
  11925. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11926. if (ref^.index <> NR_NO) then
  11927. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11928. end
  11929. else
  11930. ;
  11931. end;
  11932. { When inserting instructions before hp_prev, try to insert them
  11933. before the allocation of the FLAGS register }
  11934. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11935. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11936. { If not found, set it equal to the condition so it's something sensible }
  11937. fInsertionPoint := fCondition;
  11938. { When dealing with a comparison against zero, take note of the
  11939. instruction before it to see if we can move instructions further
  11940. back in order to benefit PostPeepholeOptTestOr.
  11941. }
  11942. if (
  11943. (
  11944. (taicpu(fCondition).opcode = A_CMP) and
  11945. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11946. ) or
  11947. (
  11948. (taicpu(fCondition).opcode = A_TEST) and
  11949. (
  11950. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11951. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11952. )
  11953. )
  11954. ) and
  11955. Optimizer.GetLastInstruction(fCondition, hp1) then
  11956. begin
  11957. { These instructions set the zero flag if the result is zero }
  11958. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11959. begin
  11960. fInsertionPoint := hp1;
  11961. { Also mark all the registers in this previous instruction
  11962. as 'in use', even if they've just been deallocated }
  11963. for Count := 0 to 1 do
  11964. with taicpu(hp1).oper[Count]^ do
  11965. case typ of
  11966. top_reg:
  11967. if getregtype(reg) = R_INTREGISTER then
  11968. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11969. top_ref:
  11970. begin
  11971. if
  11972. {$ifdef x86_64}
  11973. (ref^.base <> NR_RIP) and
  11974. {$endif x86_64}
  11975. (ref^.base <> NR_NO) then
  11976. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11977. if (ref^.index <> NR_NO) then
  11978. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11979. end
  11980. else
  11981. ;
  11982. end;
  11983. end;
  11984. end;
  11985. end
  11986. else
  11987. fCondition := nil;
  11988. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11989. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11990. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11991. { If not found, set it equal to p so it's something sensible }
  11992. fInsertionPoint := hp1;
  11993. hp1 := p_initialmov;
  11994. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11995. Exit;
  11996. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11997. if (hp1.typ <> ait_label) then { should be on a jump }
  11998. begin
  11999. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12000. { Need a label afterwards }
  12001. Exit;
  12002. end
  12003. else
  12004. fMidLabel := hp1;
  12005. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12006. { Not the correct label }
  12007. fMidLabel := nil;
  12008. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12009. { If there's neither a 2nd jump nor correct label, then it's invalid
  12010. (see above table) }
  12011. Exit;
  12012. { Analyse the first block of MOVs more closely }
  12013. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12014. if Assigned(fSecondJump) then
  12015. begin
  12016. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12017. begin
  12018. fState := tsDetour
  12019. end
  12020. else
  12021. begin
  12022. { Need the correct mid-label for this one }
  12023. if not Assigned(fMidLabel) then
  12024. Exit;
  12025. fState := tsBranching;
  12026. end;
  12027. end
  12028. else
  12029. { No jump. but mid-label is present }
  12030. fState := tsSimple;
  12031. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12032. begin
  12033. { Invalid or too many instructions to be worthwhile }
  12034. fState := tsInvalid;
  12035. Exit;
  12036. end;
  12037. { check further for
  12038. jCC xxx
  12039. <several movs 1>
  12040. jmp yyy
  12041. xxx:
  12042. <several movs 2>
  12043. yyy:
  12044. etc.
  12045. }
  12046. if (fState = tsBranching) and
  12047. { Estimate for required savings for extra jump }
  12048. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12049. { Only one reference is allowed for double blocks }
  12050. (AFirstLabel.getrefs = 1) then
  12051. begin
  12052. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12053. fSecondMovBlock := hp1;
  12054. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12055. begin
  12056. EvaluateBranchingType;
  12057. Exit;
  12058. end;
  12059. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12060. if (hp1.typ <> ait_label) then { should be on a jump }
  12061. begin
  12062. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12063. begin
  12064. { Need a label afterwards }
  12065. EvaluateBranchingType;
  12066. Exit;
  12067. end;
  12068. end
  12069. else
  12070. fEndLabel := hp1;
  12071. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12072. { Second jump doesn't go to the end }
  12073. fEndLabel := nil;
  12074. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12075. begin
  12076. { If there's neither a 3rd jump nor correct end label, then it's
  12077. not a invalid double block, but is a valid single branching
  12078. block (see above table) }
  12079. EvaluateBranchingType;
  12080. Exit;
  12081. end;
  12082. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12083. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12084. { Invalid or too many instructions to be worthwhile }
  12085. Exit;
  12086. Inc(CMOVScore, Count);
  12087. if Assigned(fThirdJump) then
  12088. begin
  12089. if not Assigned(fSecondJump) then
  12090. fState := tsDoubleSecondBranching
  12091. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12092. fState := tsDoubleBranchSame
  12093. else
  12094. fState := tsDoubleBranchDifferent;
  12095. end
  12096. else
  12097. fState := tsDouble;
  12098. end;
  12099. if fState = tsBranching then
  12100. EvaluateBranchingType;
  12101. end;
  12102. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12103. new register to store the constant }
  12104. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12105. var
  12106. RegSize: TSubRegister;
  12107. CurrentVal: TCGInt;
  12108. ANewReg: TRegister;
  12109. X: ShortInt;
  12110. begin
  12111. Result := False;
  12112. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12113. Exit;
  12114. if ConstCount >= MAX_CMOV_REGISTERS then
  12115. { Arrays are full }
  12116. Exit;
  12117. { Remember that CMOV can't encode 8-bit registers }
  12118. case taicpu(p).opsize of
  12119. S_W:
  12120. RegSize := R_SUBW;
  12121. S_L:
  12122. RegSize := R_SUBD;
  12123. {$ifdef x86_64}
  12124. S_Q:
  12125. RegSize := R_SUBQ;
  12126. {$endif x86_64}
  12127. else
  12128. InternalError(2021100401);
  12129. end;
  12130. { See if the value has already been reserved for another CMOV instruction }
  12131. CurrentVal := taicpu(p).oper[0]^.val;
  12132. for X := 0 to ConstCount - 1 do
  12133. if ConstVals[X] = CurrentVal then
  12134. begin
  12135. ConstRegs[ConstCount] := ConstRegs[X];
  12136. ConstSizes[ConstCount] := RegSize;
  12137. ConstVals[ConstCount] := CurrentVal;
  12138. Inc(ConstCount);
  12139. Inc(Count);
  12140. Result := True;
  12141. Exit;
  12142. end;
  12143. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12144. if ANewReg = NR_NO then
  12145. { No free registers }
  12146. Exit;
  12147. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12148. up vying for the same register }
  12149. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12150. ConstRegs[ConstCount] := ANewReg;
  12151. ConstSizes[ConstCount] := RegSize;
  12152. ConstVals[ConstCount] := CurrentVal;
  12153. Inc(ConstCount);
  12154. Inc(Count);
  12155. Result := True;
  12156. end;
  12157. destructor TCMOVTracking.Done;
  12158. begin
  12159. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12160. end;
  12161. procedure TCMOVTracking.Process(out new_p: tai);
  12162. var
  12163. Count, Writes: LongInt;
  12164. RegMatch: Boolean;
  12165. hp1, hp_new: tai;
  12166. inverted_condition, condition: TAsmCond;
  12167. begin
  12168. if (fState in [tsInvalid, tsProcessed]) then
  12169. InternalError(2023110701);
  12170. { Repurpose RegisterTracking to mark registers that we've defined }
  12171. RegisterTracking[R_INTREGISTER].Clear;
  12172. Count := 0;
  12173. Writes := 0;
  12174. condition := taicpu(fInitialJump).condition;
  12175. inverted_condition := inverse_cond(condition);
  12176. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12177. doesn't get CMOVs in this case }
  12178. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12179. begin
  12180. { Include the jump in the flag tracking }
  12181. if Assigned(fThirdJump) then
  12182. begin
  12183. if (fState = tsDoubleBranchSame) then
  12184. begin
  12185. { Will be an unconditional jump, so track to the instruction before it }
  12186. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12187. InternalError(2023110710);
  12188. end
  12189. else
  12190. hp1 := fThirdJump;
  12191. end
  12192. else
  12193. hp1 := fSecondMovBlockStop;
  12194. end
  12195. else
  12196. begin
  12197. { Include a conditional jump in the flag tracking }
  12198. if Assigned(fSecondJump) then
  12199. begin
  12200. if (fState = tsDetour) then
  12201. begin
  12202. { Will be an unconditional jump, so track to the instruction before it }
  12203. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12204. InternalError(2023110711);
  12205. end
  12206. else
  12207. hp1 := fSecondJump;
  12208. end
  12209. else
  12210. hp1 := fFirstMovBlockStop;
  12211. end;
  12212. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12213. { Process the second set of MOVs first, because if a destination
  12214. register is shared between the first and second MOV sets, it is more
  12215. efficient to turn the first one into a MOV instruction and place it
  12216. before the CMP if possible, but we won't know which registers are
  12217. shared until we've processed at least one list, so we might as well
  12218. make it the second one since that won't be modified again. }
  12219. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12220. begin
  12221. hp1 := fSecondMovBlock;
  12222. repeat
  12223. if not Assigned(hp1) then
  12224. InternalError(2018062902);
  12225. if (hp1.typ = ait_instruction) then
  12226. begin
  12227. { Extra safeguard }
  12228. if (taicpu(hp1).opcode <> A_MOV) then
  12229. InternalError(2018062903);
  12230. { Note: tsDoubleBranchDifferent is essentially identical to
  12231. tsBranching and the 2nd block is best left largely
  12232. untouched, but we need to evaluate which registers the MOVs
  12233. write to in order to track what would be complementary CMOV
  12234. pairs that can be further optimised. [Kit] }
  12235. if fState <> tsDoubleBranchDifferent then
  12236. begin
  12237. if taicpu(hp1).oper[0]^.typ = top_const then
  12238. begin
  12239. RegMatch := False;
  12240. for Count := 0 to ConstCount - 1 do
  12241. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12242. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12243. begin
  12244. RegMatch := True;
  12245. { If it's in RegisterTracking, then this register
  12246. is being used more than once and hence has
  12247. already had its value defined (it gets added to
  12248. UsedRegs through AllocRegBetween below) }
  12249. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12250. begin
  12251. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12252. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12253. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12254. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12255. ConstMovs[Count] := hp_new;
  12256. end
  12257. else
  12258. { We just need an instruction between hp_prev and hp1
  12259. where we know the register is marked as in use }
  12260. hp_new := fSecondMovBlock;
  12261. { Keep track of largest write for this register so it can be optimised later }
  12262. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12263. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12264. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12265. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12266. Break;
  12267. end;
  12268. if not RegMatch then
  12269. InternalError(2021100411);
  12270. end;
  12271. taicpu(hp1).opcode := A_CMOVcc;
  12272. taicpu(hp1).condition := condition;
  12273. end;
  12274. { Store these writes to search for duplicates later on }
  12275. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12276. Inc(Writes);
  12277. end;
  12278. fOptimizer.GetNextInstruction(hp1, hp1);
  12279. until (hp1 = fSecondMovBlockStop);
  12280. end;
  12281. { Now do the first set of MOVs }
  12282. hp1 := fFirstMovBlock;
  12283. repeat
  12284. if not Assigned(hp1) then
  12285. InternalError(2018062904);
  12286. if (hp1.typ = ait_instruction) then
  12287. begin
  12288. RegMatch := False;
  12289. { Extra safeguard }
  12290. if (taicpu(hp1).opcode <> A_MOV) then
  12291. InternalError(2018062905);
  12292. { Search through the RegWrites list to see if there are any
  12293. opposing CMOV pairs that write to the same register }
  12294. for Count := 0 to Writes - 1 do
  12295. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12296. begin
  12297. { We have a match. Keep this as a MOV }
  12298. { Move ahead in preparation }
  12299. fOptimizer.GetNextInstruction(hp1, hp1);
  12300. RegMatch := True;
  12301. Break;
  12302. end;
  12303. if RegMatch then
  12304. Continue;
  12305. if taicpu(hp1).oper[0]^.typ = top_const then
  12306. begin
  12307. for Count := 0 to ConstCount - 1 do
  12308. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12309. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12310. begin
  12311. RegMatch := True;
  12312. { If it's in RegisterTracking, then this register is
  12313. being used more than once and hence has already had
  12314. its value defined (it gets added to UsedRegs through
  12315. AllocRegBetween below) }
  12316. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12317. begin
  12318. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12319. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12320. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12321. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12322. ConstMovs[Count] := hp_new;
  12323. end
  12324. else
  12325. { We just need an instruction between hp_prev and hp1
  12326. where we know the register is marked as in use }
  12327. hp_new := fFirstMovBlock;
  12328. { Keep track of largest write for this register so it can be optimised later }
  12329. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12330. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12331. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12332. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12333. Break;
  12334. end;
  12335. if not RegMatch then
  12336. InternalError(2021100412);
  12337. end;
  12338. taicpu(hp1).opcode := A_CMOVcc;
  12339. taicpu(hp1).condition := inverted_condition;
  12340. if (fState = tsDoubleBranchDifferent) then
  12341. begin
  12342. { Store these writes to search for duplicates later on }
  12343. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12344. Inc(Writes);
  12345. end;
  12346. end;
  12347. fOptimizer.GetNextInstruction(hp1, hp1);
  12348. until (hp1 = fFirstMovBlockStop);
  12349. { Update initialisation MOVs to the smallest possible size }
  12350. for Count := 0 to ConstCount - 1 do
  12351. if Assigned(ConstMovs[Count]) then
  12352. begin
  12353. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12354. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12355. end;
  12356. case fState of
  12357. tsSimple:
  12358. begin
  12359. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12360. { No branch to delete }
  12361. end;
  12362. tsDetour:
  12363. begin
  12364. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12365. { Preserve jump }
  12366. end;
  12367. tsBranching, tsDoubleBranchDifferent:
  12368. begin
  12369. if (fState = tsBranching) then
  12370. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12371. else
  12372. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12373. taicpu(fSecondJump).opcode := A_JCC;
  12374. taicpu(fSecondJump).condition := inverted_condition;
  12375. end;
  12376. tsDouble, tsDoubleBranchSame:
  12377. begin
  12378. if (fState = tsDouble) then
  12379. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12380. else
  12381. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12382. { Delete second jump }
  12383. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12384. fOptimizer.RemoveInstruction(fSecondJump);
  12385. end;
  12386. tsDoubleSecondBranching:
  12387. begin
  12388. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12389. { Delete second jump, preserve third jump as conditional }
  12390. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12391. fOptimizer.RemoveInstruction(fSecondJump);
  12392. taicpu(fThirdJump).opcode := A_JCC;
  12393. taicpu(fThirdJump).condition := condition;
  12394. end;
  12395. else
  12396. InternalError(2023110720);
  12397. end;
  12398. { Now we can safely decrement the reference count }
  12399. tasmlabel(fLabel).decrefs;
  12400. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12401. { Remove the original jump }
  12402. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12403. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12404. fState := tsProcessed;
  12405. end;
  12406. {$endif 8086}
  12407. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12408. var
  12409. hp1,hp2: tai;
  12410. carryadd_opcode : TAsmOp;
  12411. symbol: TAsmSymbol;
  12412. increg, tmpreg: TRegister;
  12413. {$ifndef i8086}
  12414. CMOVTracking: PCMOVTracking;
  12415. hp3,hp4,hp5: tai;
  12416. {$endif i8086}
  12417. TempBool: Boolean;
  12418. begin
  12419. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12420. DoJumpOptimizations(p, TempBool) then
  12421. Exit(True);
  12422. result:=false;
  12423. if GetNextInstruction(p,hp1) then
  12424. begin
  12425. if (hp1.typ=ait_label) then
  12426. begin
  12427. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12428. Exit;
  12429. end
  12430. else if (hp1.typ<>ait_instruction) then
  12431. Exit;
  12432. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12433. if (
  12434. (
  12435. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12436. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12437. (Taicpu(hp1).oper[0]^.val=1)
  12438. ) or
  12439. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12440. ) and
  12441. GetNextInstruction(hp1,hp2) and
  12442. FindLabel(TAsmLabel(symbol), hp2) then
  12443. { jb @@1 cmc
  12444. inc/dec operand --> adc/sbb operand,0
  12445. @@1:
  12446. ... and ...
  12447. jnb @@1
  12448. inc/dec operand --> adc/sbb operand,0
  12449. @@1: }
  12450. begin
  12451. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12452. begin
  12453. case taicpu(hp1).opcode of
  12454. A_INC,
  12455. A_ADD:
  12456. carryadd_opcode:=A_ADC;
  12457. A_DEC,
  12458. A_SUB:
  12459. carryadd_opcode:=A_SBB;
  12460. else
  12461. InternalError(2021011001);
  12462. end;
  12463. Taicpu(p).clearop(0);
  12464. Taicpu(p).ops:=0;
  12465. Taicpu(p).is_jmp:=false;
  12466. Taicpu(p).opcode:=A_CMC;
  12467. Taicpu(p).condition:=C_NONE;
  12468. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12469. Taicpu(hp1).ops:=2;
  12470. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12471. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12472. else
  12473. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12474. Taicpu(hp1).loadconst(0,0);
  12475. Taicpu(hp1).opcode:=carryadd_opcode;
  12476. result:=true;
  12477. exit;
  12478. end
  12479. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12480. begin
  12481. case taicpu(hp1).opcode of
  12482. A_INC,
  12483. A_ADD:
  12484. carryadd_opcode:=A_ADC;
  12485. A_DEC,
  12486. A_SUB:
  12487. carryadd_opcode:=A_SBB;
  12488. else
  12489. InternalError(2021011002);
  12490. end;
  12491. Taicpu(hp1).ops:=2;
  12492. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12493. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12494. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12495. else
  12496. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12497. Taicpu(hp1).loadconst(0,0);
  12498. Taicpu(hp1).opcode:=carryadd_opcode;
  12499. RemoveCurrentP(p, hp1);
  12500. result:=true;
  12501. exit;
  12502. end
  12503. {
  12504. jcc @@1 setcc tmpreg
  12505. inc/dec/add/sub operand -> (movzx tmpreg)
  12506. @@1: add/sub tmpreg,operand
  12507. While this increases code size slightly, it makes the code much faster if the
  12508. jump is unpredictable
  12509. }
  12510. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12511. begin
  12512. { search for an available register which is volatile }
  12513. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12514. if increg <> NR_NO then
  12515. begin
  12516. { We don't need to check if tmpreg is in hp1 or not, because
  12517. it will be marked as in use at p (if not, this is
  12518. indictive of a compiler bug). }
  12519. TAsmLabel(symbol).decrefs;
  12520. Taicpu(p).clearop(0);
  12521. Taicpu(p).ops:=1;
  12522. Taicpu(p).is_jmp:=false;
  12523. Taicpu(p).opcode:=A_SETcc;
  12524. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12525. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12526. Taicpu(p).loadreg(0,increg);
  12527. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12528. begin
  12529. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12530. R_SUBW:
  12531. begin
  12532. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12533. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12534. end;
  12535. R_SUBD:
  12536. begin
  12537. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12538. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12539. end;
  12540. {$ifdef x86_64}
  12541. R_SUBQ:
  12542. begin
  12543. { MOVZX doesn't have a 64-bit variant, because
  12544. the 32-bit version implicitly zeroes the
  12545. upper 32-bits of the destination register }
  12546. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12547. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12548. setsubreg(tmpreg, R_SUBQ);
  12549. end;
  12550. {$endif x86_64}
  12551. else
  12552. Internalerror(2020030601);
  12553. end;
  12554. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12555. asml.InsertAfter(hp2,p);
  12556. end
  12557. else
  12558. tmpreg := increg;
  12559. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12560. begin
  12561. Taicpu(hp1).ops:=2;
  12562. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12563. end;
  12564. Taicpu(hp1).loadreg(0,tmpreg);
  12565. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12566. Result := True;
  12567. { p is no longer a Jcc instruction, so exit }
  12568. Exit;
  12569. end;
  12570. end;
  12571. end;
  12572. { Detect the following:
  12573. jmp<cond> @Lbl1
  12574. jmp @Lbl2
  12575. ...
  12576. @Lbl1:
  12577. ret
  12578. Change to:
  12579. jmp<inv_cond> @Lbl2
  12580. ret
  12581. }
  12582. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12583. begin
  12584. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12585. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12586. MatchInstruction(hp2,A_RET,[S_NO]) then
  12587. begin
  12588. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12589. { Change label address to that of the unconditional jump }
  12590. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12591. TAsmLabel(symbol).DecRefs;
  12592. taicpu(hp1).opcode := A_RET;
  12593. taicpu(hp1).is_jmp := false;
  12594. taicpu(hp1).ops := taicpu(hp2).ops;
  12595. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12596. case taicpu(hp2).ops of
  12597. 0:
  12598. taicpu(hp1).clearop(0);
  12599. 1:
  12600. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12601. else
  12602. internalerror(2016041302);
  12603. end;
  12604. end;
  12605. {$ifndef i8086}
  12606. end
  12607. {
  12608. convert
  12609. j<c> .L1
  12610. mov 1,reg
  12611. jmp .L2
  12612. .L1
  12613. mov 0,reg
  12614. .L2
  12615. into
  12616. mov 0,reg
  12617. set<not(c)> reg
  12618. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12619. would destroy the flag contents
  12620. }
  12621. else if MatchInstruction(hp1,A_MOV,[]) and
  12622. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12623. {$ifdef i386}
  12624. (
  12625. { Under i386, ESI, EDI, EBP and ESP
  12626. don't have an 8-bit representation }
  12627. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12628. ) and
  12629. {$endif i386}
  12630. (taicpu(hp1).oper[0]^.val=1) and
  12631. GetNextInstruction(hp1,hp2) and
  12632. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12633. GetNextInstruction(hp2,hp3) and
  12634. (hp3.typ=ait_label) and
  12635. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12636. (tai_label(hp3).labsym.getrefs=1) and
  12637. GetNextInstruction(hp3,hp4) and
  12638. MatchInstruction(hp4,A_MOV,[]) and
  12639. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12640. (taicpu(hp4).oper[0]^.val=0) and
  12641. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12642. GetNextInstruction(hp4,hp5) and
  12643. (hp5.typ=ait_label) and
  12644. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12645. (tai_label(hp5).labsym.getrefs=1) then
  12646. begin
  12647. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12648. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12649. { remove last label }
  12650. RemoveInstruction(hp5);
  12651. { remove second label }
  12652. RemoveInstruction(hp3);
  12653. { remove jmp }
  12654. RemoveInstruction(hp2);
  12655. if taicpu(hp1).opsize=S_B then
  12656. RemoveInstruction(hp1)
  12657. else
  12658. taicpu(hp1).loadconst(0,0);
  12659. taicpu(hp4).opcode:=A_SETcc;
  12660. taicpu(hp4).opsize:=S_B;
  12661. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12662. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12663. taicpu(hp4).opercnt:=1;
  12664. taicpu(hp4).ops:=1;
  12665. taicpu(hp4).freeop(1);
  12666. RemoveCurrentP(p);
  12667. Result:=true;
  12668. exit;
  12669. end
  12670. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12671. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12672. begin
  12673. { check for
  12674. jCC xxx
  12675. <several movs>
  12676. xxx:
  12677. Also spot:
  12678. Jcc xxx
  12679. <several movs>
  12680. jmp xxx
  12681. Change to:
  12682. <several cmovs with inverted condition>
  12683. jmp xxx (only for the 2nd case)
  12684. }
  12685. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12686. if CMOVTracking^.State <> tsInvalid then
  12687. begin
  12688. CMovTracking^.Process(p);
  12689. Result := True;
  12690. end;
  12691. CMOVTracking^.Done;
  12692. {$endif i8086}
  12693. end;
  12694. end;
  12695. end;
  12696. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12697. var
  12698. hp1,hp2,hp3: tai;
  12699. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12700. NewSize: TOpSize;
  12701. NewRegSize: TSubRegister;
  12702. Limit: TCgInt;
  12703. SwapOper: POper;
  12704. begin
  12705. result:=false;
  12706. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12707. GetNextInstruction(p,hp1) and
  12708. (hp1.typ = ait_instruction);
  12709. if reg_and_hp1_is_instr and
  12710. (
  12711. (taicpu(hp1).opcode <> A_LEA) or
  12712. { If the LEA instruction can be converted into an arithmetic instruction,
  12713. it may be possible to then fold it. }
  12714. (
  12715. { If the flags register is in use, don't change the instruction
  12716. to an ADD otherwise this will scramble the flags. [Kit] }
  12717. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12718. ConvertLEA(taicpu(hp1))
  12719. )
  12720. ) and
  12721. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12722. GetNextInstruction(hp1,hp2) and
  12723. MatchInstruction(hp2,A_MOV,[]) and
  12724. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12725. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12726. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12727. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12728. {$ifdef i386}
  12729. { not all registers have byte size sub registers on i386 }
  12730. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12731. {$endif i386}
  12732. (((taicpu(hp1).ops=2) and
  12733. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12734. ((taicpu(hp1).ops=1) and
  12735. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12736. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12737. begin
  12738. { change movsX/movzX reg/ref, reg2
  12739. add/sub/or/... reg3/$const, reg2
  12740. mov reg2 reg/ref
  12741. to add/sub/or/... reg3/$const, reg/ref }
  12742. { by example:
  12743. movswl %si,%eax movswl %si,%eax p
  12744. decl %eax addl %edx,%eax hp1
  12745. movw %ax,%si movw %ax,%si hp2
  12746. ->
  12747. movswl %si,%eax movswl %si,%eax p
  12748. decw %eax addw %edx,%eax hp1
  12749. movw %ax,%si movw %ax,%si hp2
  12750. }
  12751. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12752. {
  12753. ->
  12754. movswl %si,%eax movswl %si,%eax p
  12755. decw %si addw %dx,%si hp1
  12756. movw %ax,%si movw %ax,%si hp2
  12757. }
  12758. case taicpu(hp1).ops of
  12759. 1:
  12760. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12761. 2:
  12762. begin
  12763. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12764. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12765. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12766. end;
  12767. else
  12768. internalerror(2008042702);
  12769. end;
  12770. {
  12771. ->
  12772. decw %si addw %dx,%si p
  12773. }
  12774. DebugMsg(SPeepholeOptimization + 'var3',p);
  12775. RemoveCurrentP(p, hp1);
  12776. RemoveInstruction(hp2);
  12777. Result := True;
  12778. Exit;
  12779. end;
  12780. if reg_and_hp1_is_instr and
  12781. (taicpu(hp1).opcode = A_MOV) and
  12782. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12783. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12784. {$ifdef x86_64}
  12785. { check for implicit extension to 64 bit }
  12786. or
  12787. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12788. (taicpu(hp1).opsize=S_Q) and
  12789. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12790. )
  12791. {$endif x86_64}
  12792. )
  12793. then
  12794. begin
  12795. { change
  12796. movx %reg1,%reg2
  12797. mov %reg2,%reg3
  12798. dealloc %reg2
  12799. into
  12800. movx %reg,%reg3
  12801. }
  12802. TransferUsedRegs(TmpUsedRegs);
  12803. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12804. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12805. begin
  12806. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12807. {$ifdef x86_64}
  12808. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12809. (taicpu(hp1).opsize=S_Q) then
  12810. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12811. else
  12812. {$endif x86_64}
  12813. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12814. RemoveInstruction(hp1);
  12815. Result := True;
  12816. Exit;
  12817. end;
  12818. end;
  12819. if reg_and_hp1_is_instr and
  12820. ((taicpu(hp1).opcode=A_MOV) or
  12821. (taicpu(hp1).opcode=A_ADD) or
  12822. (taicpu(hp1).opcode=A_SUB) or
  12823. (taicpu(hp1).opcode=A_CMP) or
  12824. (taicpu(hp1).opcode=A_OR) or
  12825. (taicpu(hp1).opcode=A_XOR) or
  12826. (taicpu(hp1).opcode=A_AND)
  12827. ) and
  12828. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12829. begin
  12830. AndTest := (taicpu(hp1).opcode=A_AND) and
  12831. GetNextInstruction(hp1, hp2) and
  12832. (hp2.typ = ait_instruction) and
  12833. (
  12834. (
  12835. (taicpu(hp2).opcode=A_TEST) and
  12836. (
  12837. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12838. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12839. (
  12840. { If the AND and TEST instructions share a constant, this is also valid }
  12841. (taicpu(hp1).oper[0]^.typ = top_const) and
  12842. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12843. )
  12844. ) and
  12845. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12846. ) or
  12847. (
  12848. (taicpu(hp2).opcode=A_CMP) and
  12849. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12850. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12851. )
  12852. );
  12853. { change
  12854. movx (oper),%reg2
  12855. and $x,%reg2
  12856. test %reg2,%reg2
  12857. dealloc %reg2
  12858. into
  12859. op %reg1,%reg3
  12860. if the second op accesses only the bits stored in reg1
  12861. }
  12862. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12863. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12864. (taicpu(hp1).oper[0]^.typ = top_const) and
  12865. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12866. AndTest then
  12867. begin
  12868. { Check if the AND constant is in range }
  12869. case taicpu(p).opsize of
  12870. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12871. begin
  12872. NewSize := S_B;
  12873. Limit := $FF;
  12874. end;
  12875. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12876. begin
  12877. NewSize := S_W;
  12878. Limit := $FFFF;
  12879. end;
  12880. {$ifdef x86_64}
  12881. S_LQ:
  12882. begin
  12883. NewSize := S_L;
  12884. Limit := $FFFFFFFF;
  12885. end;
  12886. {$endif x86_64}
  12887. else
  12888. InternalError(2021120303);
  12889. end;
  12890. if (
  12891. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12892. { Check for negative operands }
  12893. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12894. ) and
  12895. GetNextInstruction(hp2,hp3) and
  12896. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12897. (taicpu(hp3).condition in [C_E,C_NE]) then
  12898. begin
  12899. TransferUsedRegs(TmpUsedRegs);
  12900. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12901. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12902. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12903. begin
  12904. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12905. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12906. taicpu(hp1).opcode := A_TEST;
  12907. taicpu(hp1).opsize := NewSize;
  12908. RemoveInstruction(hp2);
  12909. RemoveCurrentP(p, hp1);
  12910. Result:=true;
  12911. exit;
  12912. end;
  12913. end;
  12914. end;
  12915. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12916. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12917. (taicpu(hp1).opsize=S_B)) or
  12918. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12919. (taicpu(hp1).opsize=S_W))
  12920. {$ifdef x86_64}
  12921. or ((taicpu(p).opsize=S_LQ) and
  12922. (taicpu(hp1).opsize=S_L))
  12923. {$endif x86_64}
  12924. ) and
  12925. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12926. begin
  12927. { change
  12928. movx %reg1,%reg2
  12929. op %reg2,%reg3
  12930. dealloc %reg2
  12931. into
  12932. op %reg1,%reg3
  12933. if the second op accesses only the bits stored in reg1
  12934. }
  12935. TransferUsedRegs(TmpUsedRegs);
  12936. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12937. if AndTest then
  12938. begin
  12939. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12940. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12941. end
  12942. else
  12943. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12944. if not RegUsed then
  12945. begin
  12946. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12947. if taicpu(p).oper[0]^.typ=top_reg then
  12948. begin
  12949. case taicpu(hp1).opsize of
  12950. S_B:
  12951. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12952. S_W:
  12953. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12954. S_L:
  12955. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12956. else
  12957. Internalerror(2020102301);
  12958. end;
  12959. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12960. end
  12961. else
  12962. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12963. RemoveCurrentP(p);
  12964. if AndTest then
  12965. RemoveInstruction(hp2);
  12966. result:=true;
  12967. exit;
  12968. end;
  12969. end
  12970. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12971. (
  12972. { Bitwise operations only }
  12973. (taicpu(hp1).opcode=A_AND) or
  12974. (taicpu(hp1).opcode=A_TEST) or
  12975. (
  12976. (taicpu(hp1).oper[0]^.typ = top_const) and
  12977. (
  12978. (taicpu(hp1).opcode=A_OR) or
  12979. (taicpu(hp1).opcode=A_XOR)
  12980. )
  12981. )
  12982. ) and
  12983. (
  12984. (taicpu(hp1).oper[0]^.typ = top_const) or
  12985. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12986. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12987. ) then
  12988. begin
  12989. { change
  12990. movx %reg2,%reg2
  12991. op const,%reg2
  12992. into
  12993. op const,%reg2 (smaller version)
  12994. movx %reg2,%reg2
  12995. also change
  12996. movx %reg1,%reg2
  12997. and/test (oper),%reg2
  12998. dealloc %reg2
  12999. into
  13000. and/test (oper),%reg1
  13001. }
  13002. case taicpu(p).opsize of
  13003. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13004. begin
  13005. NewSize := S_B;
  13006. NewRegSize := R_SUBL;
  13007. Limit := $FF;
  13008. end;
  13009. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13010. begin
  13011. NewSize := S_W;
  13012. NewRegSize := R_SUBW;
  13013. Limit := $FFFF;
  13014. end;
  13015. {$ifdef x86_64}
  13016. S_LQ:
  13017. begin
  13018. NewSize := S_L;
  13019. NewRegSize := R_SUBD;
  13020. Limit := $FFFFFFFF;
  13021. end;
  13022. {$endif x86_64}
  13023. else
  13024. Internalerror(2021120302);
  13025. end;
  13026. TransferUsedRegs(TmpUsedRegs);
  13027. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13028. if AndTest then
  13029. begin
  13030. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13031. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13032. end
  13033. else
  13034. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13035. if
  13036. (
  13037. (taicpu(p).opcode = A_MOVZX) and
  13038. (
  13039. (taicpu(hp1).opcode=A_AND) or
  13040. (taicpu(hp1).opcode=A_TEST)
  13041. ) and
  13042. not (
  13043. { If both are references, then the final instruction will have
  13044. both operands as references, which is not allowed }
  13045. (taicpu(p).oper[0]^.typ = top_ref) and
  13046. (taicpu(hp1).oper[0]^.typ = top_ref)
  13047. ) and
  13048. not RegUsed
  13049. ) or
  13050. (
  13051. (
  13052. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13053. not RegUsed
  13054. ) and
  13055. (taicpu(p).oper[0]^.typ = top_reg) and
  13056. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13057. (taicpu(hp1).oper[0]^.typ = top_const) and
  13058. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13059. ) then
  13060. begin
  13061. {$if defined(i386) or defined(i8086)}
  13062. { If the target size is 8-bit, make sure we can actually encode it }
  13063. 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
  13064. Exit;
  13065. {$endif i386 or i8086}
  13066. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13067. taicpu(hp1).opsize := NewSize;
  13068. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13069. if AndTest then
  13070. begin
  13071. RemoveInstruction(hp2);
  13072. if not RegUsed then
  13073. begin
  13074. taicpu(hp1).opcode := A_TEST;
  13075. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13076. begin
  13077. { Make sure the reference is the second operand }
  13078. SwapOper := taicpu(hp1).oper[0];
  13079. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13080. taicpu(hp1).oper[1] := SwapOper;
  13081. end;
  13082. end;
  13083. end;
  13084. case taicpu(hp1).oper[0]^.typ of
  13085. top_reg:
  13086. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13087. top_const:
  13088. { For the AND/TEST case }
  13089. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13090. else
  13091. ;
  13092. end;
  13093. if RegUsed then
  13094. begin
  13095. AsmL.Remove(p);
  13096. AsmL.InsertAfter(p, hp1);
  13097. p := hp1;
  13098. end
  13099. else
  13100. RemoveCurrentP(p, hp1);
  13101. result:=true;
  13102. exit;
  13103. end;
  13104. end;
  13105. end;
  13106. if reg_and_hp1_is_instr and
  13107. (taicpu(p).oper[0]^.typ = top_reg) and
  13108. (
  13109. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13110. ) and
  13111. (taicpu(hp1).oper[0]^.typ = top_const) and
  13112. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13113. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13114. { Minimum shift value allowed is the bit difference between the sizes }
  13115. (taicpu(hp1).oper[0]^.val >=
  13116. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13117. 8 * (
  13118. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13119. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13120. )
  13121. ) then
  13122. begin
  13123. { For:
  13124. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13125. shl/sal ##, %reg1
  13126. Remove the movsx/movzx instruction if the shift overwrites the
  13127. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13128. }
  13129. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13130. RemoveCurrentP(p, hp1);
  13131. Result := True;
  13132. Exit;
  13133. end
  13134. else if reg_and_hp1_is_instr and
  13135. (taicpu(p).oper[0]^.typ = top_reg) and
  13136. (
  13137. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13138. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13139. ) and
  13140. (taicpu(hp1).oper[0]^.typ = top_const) and
  13141. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13142. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13143. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13144. (taicpu(hp1).oper[0]^.val <
  13145. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13146. 8 * (
  13147. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13148. )
  13149. ) then
  13150. begin
  13151. { For:
  13152. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13153. sar ##, %reg1 shr ##, %reg1
  13154. Move the shift to before the movx instruction if the shift value
  13155. is not too large.
  13156. }
  13157. asml.Remove(hp1);
  13158. asml.InsertBefore(hp1, p);
  13159. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13160. case taicpu(p).opsize of
  13161. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13162. taicpu(hp1).opsize := S_B;
  13163. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13164. taicpu(hp1).opsize := S_W;
  13165. {$ifdef x86_64}
  13166. S_LQ:
  13167. taicpu(hp1).opsize := S_L;
  13168. {$endif}
  13169. else
  13170. InternalError(2020112401);
  13171. end;
  13172. if (taicpu(hp1).opcode = A_SHR) then
  13173. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13174. else
  13175. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13176. Result := True;
  13177. end;
  13178. if reg_and_hp1_is_instr and
  13179. (taicpu(p).oper[0]^.typ = top_reg) and
  13180. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13181. (
  13182. (taicpu(hp1).opcode = taicpu(p).opcode)
  13183. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13184. {$ifdef x86_64}
  13185. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13186. {$endif x86_64}
  13187. ) then
  13188. begin
  13189. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13190. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13191. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13192. begin
  13193. {
  13194. For example:
  13195. movzbw %al,%ax
  13196. movzwl %ax,%eax
  13197. Compress into:
  13198. movzbl %al,%eax
  13199. }
  13200. RegUsed := False;
  13201. case taicpu(p).opsize of
  13202. S_BW:
  13203. case taicpu(hp1).opsize of
  13204. S_WL:
  13205. begin
  13206. taicpu(p).opsize := S_BL;
  13207. RegUsed := True;
  13208. end;
  13209. {$ifdef x86_64}
  13210. S_WQ:
  13211. begin
  13212. if taicpu(p).opcode = A_MOVZX then
  13213. begin
  13214. taicpu(p).opsize := S_BL;
  13215. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13216. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13217. end
  13218. else
  13219. taicpu(p).opsize := S_BQ;
  13220. RegUsed := True;
  13221. end;
  13222. {$endif x86_64}
  13223. else
  13224. ;
  13225. end;
  13226. {$ifdef x86_64}
  13227. S_BL:
  13228. case taicpu(hp1).opsize of
  13229. S_LQ:
  13230. begin
  13231. if taicpu(p).opcode = A_MOVZX then
  13232. begin
  13233. taicpu(p).opsize := S_BL;
  13234. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13235. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13236. end
  13237. else
  13238. taicpu(p).opsize := S_BQ;
  13239. RegUsed := True;
  13240. end;
  13241. else
  13242. ;
  13243. end;
  13244. S_WL:
  13245. case taicpu(hp1).opsize of
  13246. S_LQ:
  13247. begin
  13248. if taicpu(p).opcode = A_MOVZX then
  13249. begin
  13250. taicpu(p).opsize := S_WL;
  13251. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13252. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13253. end
  13254. else
  13255. taicpu(p).opsize := S_WQ;
  13256. RegUsed := True;
  13257. end;
  13258. else
  13259. ;
  13260. end;
  13261. {$endif x86_64}
  13262. else
  13263. ;
  13264. end;
  13265. if RegUsed then
  13266. begin
  13267. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13268. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13269. RemoveInstruction(hp1);
  13270. Result := True;
  13271. Exit;
  13272. end;
  13273. end;
  13274. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13275. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13276. GetNextInstruction(hp1, hp2) and
  13277. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13278. (
  13279. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13280. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13281. {$ifdef x86_64}
  13282. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13283. {$endif x86_64}
  13284. ) and
  13285. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13286. (
  13287. (
  13288. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13289. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13290. ) or
  13291. (
  13292. { Only allow the operands in reverse order for TEST instructions }
  13293. (taicpu(hp2).opcode = A_TEST) and
  13294. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13295. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13296. )
  13297. ) then
  13298. begin
  13299. {
  13300. For example:
  13301. movzbl %al,%eax
  13302. movzbl (ref),%edx
  13303. andl %edx,%eax
  13304. (%edx deallocated)
  13305. Change to:
  13306. andb (ref),%al
  13307. movzbl %al,%eax
  13308. Rules are:
  13309. - First two instructions have the same opcode and opsize
  13310. - First instruction's operands are the same super-register
  13311. - Second instruction operates on a different register
  13312. - Third instruction is AND, OR, XOR or TEST
  13313. - Third instruction's operands are the destination registers of the first two instructions
  13314. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13315. - Second instruction's destination register is deallocated afterwards
  13316. }
  13317. TransferUsedRegs(TmpUsedRegs);
  13318. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13319. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13320. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13321. begin
  13322. case taicpu(p).opsize of
  13323. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13324. NewSize := S_B;
  13325. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13326. NewSize := S_W;
  13327. {$ifdef x86_64}
  13328. S_LQ:
  13329. NewSize := S_L;
  13330. {$endif x86_64}
  13331. else
  13332. InternalError(2021120301);
  13333. end;
  13334. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13335. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13336. taicpu(hp2).opsize := NewSize;
  13337. RemoveInstruction(hp1);
  13338. { With TEST, it's best to keep the MOVX instruction at the top }
  13339. if (taicpu(hp2).opcode <> A_TEST) then
  13340. begin
  13341. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13342. asml.Remove(p);
  13343. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13344. asml.InsertAfter(p, hp2);
  13345. p := hp2;
  13346. end
  13347. else
  13348. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13349. Result := True;
  13350. Exit;
  13351. end;
  13352. end;
  13353. end;
  13354. if taicpu(p).opcode=A_MOVZX then
  13355. begin
  13356. { removes superfluous And's after movzx's }
  13357. if reg_and_hp1_is_instr and
  13358. (taicpu(hp1).opcode = A_AND) and
  13359. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13360. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13361. {$ifdef x86_64}
  13362. { check for implicit extension to 64 bit }
  13363. or
  13364. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13365. (taicpu(hp1).opsize=S_Q) and
  13366. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13367. )
  13368. {$endif x86_64}
  13369. )
  13370. then
  13371. begin
  13372. case taicpu(p).opsize Of
  13373. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13374. if (taicpu(hp1).oper[0]^.val = $ff) then
  13375. begin
  13376. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13377. RemoveInstruction(hp1);
  13378. Result:=true;
  13379. exit;
  13380. end;
  13381. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13382. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13383. begin
  13384. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13385. RemoveInstruction(hp1);
  13386. Result:=true;
  13387. exit;
  13388. end;
  13389. {$ifdef x86_64}
  13390. S_LQ:
  13391. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13392. begin
  13393. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13394. RemoveInstruction(hp1);
  13395. Result:=true;
  13396. exit;
  13397. end;
  13398. {$endif x86_64}
  13399. else
  13400. ;
  13401. end;
  13402. { we cannot get rid of the and, but can we get rid of the movz ?}
  13403. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13404. begin
  13405. case taicpu(p).opsize Of
  13406. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13407. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13408. begin
  13409. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13410. RemoveCurrentP(p,hp1);
  13411. Result:=true;
  13412. exit;
  13413. end;
  13414. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13415. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13416. begin
  13417. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13418. RemoveCurrentP(p,hp1);
  13419. Result:=true;
  13420. exit;
  13421. end;
  13422. {$ifdef x86_64}
  13423. S_LQ:
  13424. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13425. begin
  13426. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13427. RemoveCurrentP(p,hp1);
  13428. Result:=true;
  13429. exit;
  13430. end;
  13431. {$endif x86_64}
  13432. else
  13433. ;
  13434. end;
  13435. end;
  13436. end;
  13437. { changes some movzx constructs to faster synonyms (all examples
  13438. are given with eax/ax, but are also valid for other registers)}
  13439. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13440. begin
  13441. case taicpu(p).opsize of
  13442. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13443. (the machine code is equivalent to movzbl %al,%eax), but the
  13444. code generator still generates that assembler instruction and
  13445. it is silently converted. This should probably be checked.
  13446. [Kit] }
  13447. S_BW:
  13448. begin
  13449. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13450. (
  13451. not IsMOVZXAcceptable
  13452. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13453. or (
  13454. (cs_opt_size in current_settings.optimizerswitches) and
  13455. (taicpu(p).oper[1]^.reg = NR_AX)
  13456. )
  13457. ) then
  13458. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13459. begin
  13460. DebugMsg(SPeepholeOptimization + 'var7',p);
  13461. taicpu(p).opcode := A_AND;
  13462. taicpu(p).changeopsize(S_W);
  13463. taicpu(p).loadConst(0,$ff);
  13464. Result := True;
  13465. end
  13466. else if not IsMOVZXAcceptable and
  13467. GetNextInstruction(p, hp1) and
  13468. (tai(hp1).typ = ait_instruction) and
  13469. (taicpu(hp1).opcode = A_AND) and
  13470. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13471. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13472. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13473. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13474. begin
  13475. DebugMsg(SPeepholeOptimization + 'var8',p);
  13476. taicpu(p).opcode := A_MOV;
  13477. taicpu(p).changeopsize(S_W);
  13478. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13479. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13480. Result := True;
  13481. end;
  13482. end;
  13483. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13484. S_BL:
  13485. if not IsMOVZXAcceptable then
  13486. begin
  13487. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13488. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13489. begin
  13490. DebugMsg(SPeepholeOptimization + 'var9',p);
  13491. taicpu(p).opcode := A_AND;
  13492. taicpu(p).changeopsize(S_L);
  13493. taicpu(p).loadConst(0,$ff);
  13494. Result := True;
  13495. end
  13496. else if GetNextInstruction(p, hp1) and
  13497. (tai(hp1).typ = ait_instruction) and
  13498. (taicpu(hp1).opcode = A_AND) and
  13499. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13500. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13501. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13502. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13503. begin
  13504. DebugMsg(SPeepholeOptimization + 'var10',p);
  13505. taicpu(p).opcode := A_MOV;
  13506. taicpu(p).changeopsize(S_L);
  13507. { do not use R_SUBWHOLE
  13508. as movl %rdx,%eax
  13509. is invalid in assembler PM }
  13510. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13511. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13512. Result := True;
  13513. end;
  13514. end;
  13515. {$endif i8086}
  13516. S_WL:
  13517. if not IsMOVZXAcceptable then
  13518. begin
  13519. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13520. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13521. begin
  13522. DebugMsg(SPeepholeOptimization + 'var11',p);
  13523. taicpu(p).opcode := A_AND;
  13524. taicpu(p).changeopsize(S_L);
  13525. taicpu(p).loadConst(0,$ffff);
  13526. Result := True;
  13527. end
  13528. else if GetNextInstruction(p, hp1) and
  13529. (tai(hp1).typ = ait_instruction) and
  13530. (taicpu(hp1).opcode = A_AND) and
  13531. (taicpu(hp1).oper[0]^.typ = top_const) and
  13532. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13533. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13534. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13535. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13536. begin
  13537. DebugMsg(SPeepholeOptimization + 'var12',p);
  13538. taicpu(p).opcode := A_MOV;
  13539. taicpu(p).changeopsize(S_L);
  13540. { do not use R_SUBWHOLE
  13541. as movl %rdx,%eax
  13542. is invalid in assembler PM }
  13543. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13544. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13545. Result := True;
  13546. end;
  13547. end;
  13548. else
  13549. InternalError(2017050705);
  13550. end;
  13551. end
  13552. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13553. begin
  13554. if GetNextInstruction(p, hp1) and
  13555. (tai(hp1).typ = ait_instruction) and
  13556. (taicpu(hp1).opcode = A_AND) and
  13557. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13558. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13559. begin
  13560. case taicpu(p).opsize Of
  13561. S_BL:
  13562. if (taicpu(hp1).opsize <> S_L) or
  13563. (taicpu(hp1).oper[0]^.val > $FF) then
  13564. begin
  13565. DebugMsg(SPeepholeOptimization + 'var13',p);
  13566. taicpu(hp1).changeopsize(S_L);
  13567. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13568. Include(OptsToCheck, aoc_ForceNewIteration);
  13569. end;
  13570. S_WL:
  13571. if (taicpu(hp1).opsize <> S_L) or
  13572. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13573. begin
  13574. DebugMsg(SPeepholeOptimization + 'var14',p);
  13575. taicpu(hp1).changeopsize(S_L);
  13576. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13577. Include(OptsToCheck, aoc_ForceNewIteration);
  13578. end;
  13579. S_BW:
  13580. if (taicpu(hp1).opsize <> S_W) or
  13581. (taicpu(hp1).oper[0]^.val > $FF) then
  13582. begin
  13583. DebugMsg(SPeepholeOptimization + 'var15',p);
  13584. taicpu(hp1).changeopsize(S_W);
  13585. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13586. Include(OptsToCheck, aoc_ForceNewIteration);
  13587. end;
  13588. else
  13589. Internalerror(2017050704)
  13590. end;
  13591. end;
  13592. end;
  13593. end;
  13594. end;
  13595. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13596. var
  13597. hp1, hp2 : tai;
  13598. MaskLength : Cardinal;
  13599. MaskedBits : TCgInt;
  13600. ActiveReg : TRegister;
  13601. begin
  13602. Result:=false;
  13603. { There are no optimisations for reference targets }
  13604. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13605. Exit;
  13606. while GetNextInstruction(p, hp1) and
  13607. (hp1.typ = ait_instruction) do
  13608. begin
  13609. if (taicpu(p).oper[0]^.typ = top_const) then
  13610. begin
  13611. case taicpu(hp1).opcode of
  13612. A_AND:
  13613. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13614. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13615. { the second register must contain the first one, so compare their subreg types }
  13616. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13617. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13618. { change
  13619. and const1, reg
  13620. and const2, reg
  13621. to
  13622. and (const1 and const2), reg
  13623. }
  13624. begin
  13625. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13626. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13627. RemoveCurrentP(p, hp1);
  13628. Result:=true;
  13629. exit;
  13630. end;
  13631. A_CMP:
  13632. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13633. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13634. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13635. { Just check that the condition on the next instruction is compatible }
  13636. GetNextInstruction(hp1, hp2) and
  13637. (hp2.typ = ait_instruction) and
  13638. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13639. then
  13640. { change
  13641. and 2^n, reg
  13642. cmp 2^n, reg
  13643. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13644. to
  13645. and 2^n, reg
  13646. test reg, reg
  13647. j(~c) / set(~c) / cmov(~c)
  13648. }
  13649. begin
  13650. { Keep TEST instruction in, rather than remove it, because
  13651. it may trigger other optimisations such as MovAndTest2Test }
  13652. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13653. taicpu(hp1).opcode := A_TEST;
  13654. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13655. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13656. Result := True;
  13657. Exit;
  13658. end
  13659. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13660. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13661. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13662. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13663. { change
  13664. and $ff/$ff/$ffff, reg
  13665. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13666. dealloc reg
  13667. to
  13668. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13669. }
  13670. begin
  13671. TransferUsedRegs(TmpUsedRegs);
  13672. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13673. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13674. begin
  13675. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13676. case taicpu(p).oper[0]^.val of
  13677. $ff:
  13678. begin
  13679. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13680. taicpu(hp1).opsize:=S_B;
  13681. end;
  13682. $ffff:
  13683. begin
  13684. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13685. taicpu(hp1).opsize:=S_W;
  13686. end;
  13687. $ffffffff:
  13688. begin
  13689. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13690. taicpu(hp1).opsize:=S_L;
  13691. end;
  13692. else
  13693. Internalerror(2023030401);
  13694. end;
  13695. RemoveCurrentP(p);
  13696. Result := True;
  13697. Exit;
  13698. end;
  13699. end;
  13700. A_MOVZX:
  13701. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13702. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13703. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13704. (
  13705. (
  13706. (taicpu(p).opsize=S_W) and
  13707. (taicpu(hp1).opsize=S_BW)
  13708. ) or
  13709. (
  13710. (taicpu(p).opsize=S_L) and
  13711. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13712. )
  13713. {$ifdef x86_64}
  13714. or
  13715. (
  13716. (taicpu(p).opsize=S_Q) and
  13717. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13718. )
  13719. {$endif x86_64}
  13720. ) then
  13721. begin
  13722. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13723. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13724. ) or
  13725. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13726. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13727. then
  13728. begin
  13729. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13730. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13731. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13732. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13733. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13734. }
  13735. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13736. RemoveInstruction(hp1);
  13737. { See if there are other optimisations possible }
  13738. Continue;
  13739. end;
  13740. end;
  13741. A_SHL:
  13742. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13743. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13744. begin
  13745. {$ifopt R+}
  13746. {$define RANGE_WAS_ON}
  13747. {$R-}
  13748. {$endif}
  13749. { get length of potential and mask }
  13750. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13751. { really a mask? }
  13752. {$ifdef RANGE_WAS_ON}
  13753. {$R+}
  13754. {$endif}
  13755. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13756. { unmasked part shifted out? }
  13757. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13758. begin
  13759. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13760. RemoveCurrentP(p, hp1);
  13761. Result:=true;
  13762. exit;
  13763. end;
  13764. end;
  13765. A_SHR:
  13766. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13767. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13768. (taicpu(hp1).oper[0]^.val <= 63) then
  13769. begin
  13770. { Does SHR combined with the AND cover all the bits?
  13771. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13772. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13773. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13774. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13775. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13776. begin
  13777. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13778. RemoveCurrentP(p, hp1);
  13779. Result := True;
  13780. Exit;
  13781. end;
  13782. end;
  13783. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13784. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13785. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13786. begin
  13787. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13788. (
  13789. (
  13790. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13791. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13792. ) or (
  13793. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13794. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13795. {$ifdef x86_64}
  13796. ) or (
  13797. (taicpu(hp1).opsize = S_LQ) and
  13798. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13799. {$endif x86_64}
  13800. )
  13801. ) then
  13802. begin
  13803. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13804. begin
  13805. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13806. RemoveInstruction(hp1);
  13807. { See if there are other optimisations possible }
  13808. Continue;
  13809. end;
  13810. { The super-registers are the same though.
  13811. Note that this change by itself doesn't improve
  13812. code speed, but it opens up other optimisations. }
  13813. {$ifdef x86_64}
  13814. { Convert 64-bit register to 32-bit }
  13815. case taicpu(hp1).opsize of
  13816. S_BQ:
  13817. begin
  13818. taicpu(hp1).opsize := S_BL;
  13819. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13820. end;
  13821. S_WQ:
  13822. begin
  13823. taicpu(hp1).opsize := S_WL;
  13824. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13825. end
  13826. else
  13827. ;
  13828. end;
  13829. {$endif x86_64}
  13830. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13831. taicpu(hp1).opcode := A_MOVZX;
  13832. { See if there are other optimisations possible }
  13833. Continue;
  13834. end;
  13835. end;
  13836. else
  13837. ;
  13838. end;
  13839. end
  13840. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13841. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13842. begin
  13843. {$ifdef x86_64}
  13844. if (taicpu(p).opsize = S_Q) then
  13845. begin
  13846. { Never necessary }
  13847. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13848. RemoveCurrentP(p, hp1);
  13849. Result := True;
  13850. Exit;
  13851. end;
  13852. {$endif x86_64}
  13853. { Forward check to determine necessity of and %reg,%reg }
  13854. TransferUsedRegs(TmpUsedRegs);
  13855. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13856. { Saves on a bunch of dereferences }
  13857. ActiveReg := taicpu(p).oper[1]^.reg;
  13858. case taicpu(hp1).opcode of
  13859. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13860. if (
  13861. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13862. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13863. ) and
  13864. (
  13865. (taicpu(hp1).opcode <> A_MOV) or
  13866. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13867. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13868. ) and
  13869. not (
  13870. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13871. (taicpu(hp1).opcode = A_MOV) and
  13872. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13873. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13874. ) and
  13875. (
  13876. (
  13877. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13878. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13879. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13880. ) or
  13881. (
  13882. {$ifdef x86_64}
  13883. (
  13884. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13885. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13886. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13887. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13888. ) and
  13889. {$endif x86_64}
  13890. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13891. )
  13892. ) then
  13893. begin
  13894. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13895. RemoveCurrentP(p, hp1);
  13896. Result := True;
  13897. Exit;
  13898. end;
  13899. A_ADD,
  13900. A_AND,
  13901. A_BSF,
  13902. A_BSR,
  13903. A_BTC,
  13904. A_BTR,
  13905. A_BTS,
  13906. A_OR,
  13907. A_SUB,
  13908. A_XOR:
  13909. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13910. if (
  13911. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13912. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13913. ) and
  13914. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13915. begin
  13916. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13917. RemoveCurrentP(p, hp1);
  13918. Result := True;
  13919. Exit;
  13920. end;
  13921. A_CMP,
  13922. A_TEST:
  13923. if (
  13924. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13925. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13926. ) and
  13927. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13928. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13929. begin
  13930. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13931. RemoveCurrentP(p, hp1);
  13932. Result := True;
  13933. Exit;
  13934. end;
  13935. A_BSWAP,
  13936. A_NEG,
  13937. A_NOT:
  13938. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13939. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13940. begin
  13941. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13942. RemoveCurrentP(p, hp1);
  13943. Result := True;
  13944. Exit;
  13945. end;
  13946. else
  13947. ;
  13948. end;
  13949. end;
  13950. if (taicpu(hp1).is_jmp) and
  13951. (taicpu(hp1).opcode<>A_JMP) and
  13952. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13953. begin
  13954. { change
  13955. and x, reg
  13956. jxx
  13957. to
  13958. test x, reg
  13959. jxx
  13960. if reg is deallocated before the
  13961. jump, but only if it's a conditional jump (PFV)
  13962. }
  13963. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13964. taicpu(p).opcode := A_TEST;
  13965. Exit;
  13966. end;
  13967. Break;
  13968. end;
  13969. { Lone AND tests }
  13970. if (taicpu(p).oper[0]^.typ = top_const) then
  13971. begin
  13972. {
  13973. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13974. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13975. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13976. }
  13977. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13978. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13979. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13980. begin
  13981. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13982. if taicpu(p).opsize = S_L then
  13983. begin
  13984. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13985. Result := True;
  13986. end;
  13987. end;
  13988. end;
  13989. { Backward check to determine necessity of and %reg,%reg }
  13990. if (taicpu(p).oper[0]^.typ = top_reg) and
  13991. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13992. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13993. GetLastInstruction(p, hp2) and
  13994. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13995. { Check size of adjacent instruction to determine if the AND is
  13996. effectively a null operation }
  13997. (
  13998. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13999. { Note: Don't include S_Q }
  14000. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14001. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14002. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14003. ) then
  14004. begin
  14005. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14006. { If GetNextInstruction returned False, hp1 will be nil }
  14007. RemoveCurrentP(p, hp1);
  14008. Result := True;
  14009. Exit;
  14010. end;
  14011. end;
  14012. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14013. var
  14014. hp1, hp2: tai;
  14015. NewRef: TReference;
  14016. Distance: Cardinal;
  14017. TempTracking: TAllUsedRegs;
  14018. { This entire nested function is used in an if-statement below, but we
  14019. want to avoid all the used reg transfers and GetNextInstruction calls
  14020. until we really have to check }
  14021. function MemRegisterNotUsedLater: Boolean; inline;
  14022. var
  14023. hp2: tai;
  14024. begin
  14025. TransferUsedRegs(TmpUsedRegs);
  14026. hp2 := p;
  14027. repeat
  14028. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14029. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14030. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14031. end;
  14032. begin
  14033. Result := False;
  14034. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14035. (taicpu(p).oper[1]^.typ = top_reg) then
  14036. begin
  14037. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14038. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14039. (hp1.typ <> ait_instruction) or
  14040. not
  14041. (
  14042. (cs_opt_level3 in current_settings.optimizerswitches) or
  14043. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14044. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14045. ) then
  14046. Exit;
  14047. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14048. addq $x, %rax
  14049. movq %rax, %rdx
  14050. sarq $63, %rdx
  14051. (%rax still in use)
  14052. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14053. leaq $x(%rax),%rdx
  14054. addq $x, %rax
  14055. sarq $63, %rdx
  14056. ...which is okay since it breaks the dependency chain between
  14057. addq and movq, but if OptPass2MOV is called first:
  14058. addq $x, %rax
  14059. cqto
  14060. ...which is better in all ways, taking only 2 cycles to execute
  14061. and much smaller in code size.
  14062. }
  14063. { The extra register tracking is quite strenuous }
  14064. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14065. MatchInstruction(hp1, A_MOV, []) then
  14066. begin
  14067. { Update the register tracking to the MOV instruction }
  14068. CopyUsedRegs(TempTracking);
  14069. hp2 := p;
  14070. repeat
  14071. UpdateUsedRegs(tai(hp2.Next));
  14072. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14073. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14074. OptPass2ADD get called again }
  14075. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14076. begin
  14077. { Reset the tracking to the current instruction }
  14078. RestoreUsedRegs(TempTracking);
  14079. ReleaseUsedRegs(TempTracking);
  14080. Result := True;
  14081. Exit;
  14082. end;
  14083. { Reset the tracking to the current instruction }
  14084. RestoreUsedRegs(TempTracking);
  14085. ReleaseUsedRegs(TempTracking);
  14086. { If OptPass2MOV returned True, we don't need to set Result to
  14087. True if hp1 didn't change because the ADD instruction didn't
  14088. get modified and we'll be evaluating hp1 again when the
  14089. peephole optimizer reaches it }
  14090. end;
  14091. { Change:
  14092. add %reg2,%reg1
  14093. (%reg2 not modified in between)
  14094. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14095. To:
  14096. mov/s/z #(%reg1,%reg2),%reg1
  14097. }
  14098. if (taicpu(p).oper[0]^.typ = top_reg) and
  14099. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14100. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14101. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14102. (
  14103. (
  14104. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14105. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14106. { r/esp cannot be an index }
  14107. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14108. ) or (
  14109. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14110. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14111. )
  14112. ) and (
  14113. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14114. (
  14115. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14116. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14117. MemRegisterNotUsedLater
  14118. )
  14119. ) then
  14120. begin
  14121. if (
  14122. { Instructions are guaranteed to be adjacent on -O2 and under }
  14123. (cs_opt_level3 in current_settings.optimizerswitches) and
  14124. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14125. ) then
  14126. begin
  14127. { If the other register is used in between, move the MOV
  14128. instruction to right after the ADD instruction so a
  14129. saving can still be made }
  14130. Asml.Remove(hp1);
  14131. Asml.InsertAfter(hp1, p);
  14132. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14133. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14134. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14135. RemoveCurrentp(p, hp1);
  14136. end
  14137. else
  14138. begin
  14139. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14140. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14141. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14142. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14143. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14144. { hp1 may not be the immediate next instruction under -O3 }
  14145. RemoveCurrentp(p)
  14146. else
  14147. RemoveCurrentp(p, hp1);
  14148. end;
  14149. Result := True;
  14150. Exit;
  14151. end;
  14152. { Change:
  14153. addl/q $x,%reg1
  14154. movl/q %reg1,%reg2
  14155. To:
  14156. leal/q $x(%reg1),%reg2
  14157. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14158. Breaks the dependency chain.
  14159. }
  14160. if (taicpu(p).oper[0]^.typ = top_const) and
  14161. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14162. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14163. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14164. (
  14165. { Instructions are guaranteed to be adjacent on -O2 and under }
  14166. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14167. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14168. ) then
  14169. begin
  14170. TransferUsedRegs(TmpUsedRegs);
  14171. hp2 := p;
  14172. repeat
  14173. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14174. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14175. if (
  14176. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14177. not (cs_opt_size in current_settings.optimizerswitches) or
  14178. (
  14179. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14180. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14181. )
  14182. ) then
  14183. begin
  14184. { Change the MOV instruction to a LEA instruction, and update the
  14185. first operand }
  14186. reference_reset(NewRef, 1, []);
  14187. NewRef.base := taicpu(p).oper[1]^.reg;
  14188. NewRef.scalefactor := 1;
  14189. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14190. taicpu(hp1).opcode := A_LEA;
  14191. taicpu(hp1).loadref(0, NewRef);
  14192. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14193. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14194. begin
  14195. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14196. { Move what is now the LEA instruction to before the ADD instruction }
  14197. Asml.Remove(hp1);
  14198. Asml.InsertBefore(hp1, p);
  14199. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14200. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14201. p := hp1;
  14202. end
  14203. else
  14204. begin
  14205. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14206. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14207. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14208. { hp1 may not be the immediate next instruction under -O3 }
  14209. RemoveCurrentp(p)
  14210. else
  14211. RemoveCurrentp(p, hp1);
  14212. end;
  14213. Result := True;
  14214. end;
  14215. end;
  14216. end;
  14217. end;
  14218. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14219. var
  14220. SubReg: TSubRegister;
  14221. hp1, hp2: tai;
  14222. CallJmp: Boolean;
  14223. begin
  14224. Result := False;
  14225. CallJmp := False;
  14226. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14227. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14228. with taicpu(p).oper[0]^.ref^ do
  14229. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14230. if (offset = 0) then
  14231. begin
  14232. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14233. begin
  14234. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14235. taicpu(p).opcode := A_ADD;
  14236. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14237. Result := True;
  14238. end
  14239. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14240. begin
  14241. if (base <> NR_NO) then
  14242. begin
  14243. if (scalefactor <= 1) then
  14244. begin
  14245. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14246. taicpu(p).opcode := A_ADD;
  14247. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14248. Result := True;
  14249. end;
  14250. end
  14251. else
  14252. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14253. if (scalefactor in [2, 4, 8]) then
  14254. begin
  14255. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14256. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14257. taicpu(p).opcode := A_SHL;
  14258. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14259. Result := True;
  14260. end;
  14261. end;
  14262. end
  14263. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14264. lot of latency, so break off the offset if %reg3 is used soon
  14265. afterwards }
  14266. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14267. { If 3-component addresses don't have additional latency, don't
  14268. perform this optimisation }
  14269. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14270. GetNextInstruction(p, hp1) and
  14271. (hp1.typ = ait_instruction) and
  14272. (
  14273. (
  14274. { Permit jumps and calls since they have a larger degree of overhead }
  14275. (
  14276. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14277. (
  14278. { ... unless the register specifies the location }
  14279. (taicpu(hp1).ops > 0) and
  14280. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14281. )
  14282. ) and
  14283. (
  14284. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14285. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14286. )
  14287. )
  14288. or
  14289. (
  14290. { Check up to two instructions ahead }
  14291. GetNextInstruction(hp1, hp2) and
  14292. (hp2.typ = ait_instruction) and
  14293. (
  14294. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14295. (
  14296. { Same as above }
  14297. (taicpu(hp2).ops > 0) and
  14298. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14299. )
  14300. ) and
  14301. (
  14302. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14303. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14304. )
  14305. )
  14306. ) then
  14307. begin
  14308. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14309. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14310. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14311. offset := 0;
  14312. if Assigned(symbol) or Assigned(relsymbol) then
  14313. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14314. else
  14315. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14316. { Inserting before the next instruction rather than after the
  14317. current instruction gives more accurate register tracking }
  14318. asml.InsertBefore(hp2, hp1);
  14319. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14320. Result := True;
  14321. end;
  14322. end;
  14323. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14324. var
  14325. hp1, hp2: tai;
  14326. NewRef: TReference;
  14327. Distance: Cardinal;
  14328. TempTracking: TAllUsedRegs;
  14329. begin
  14330. Result := False;
  14331. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14332. MatchOpType(taicpu(p),top_const,top_reg) then
  14333. begin
  14334. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14335. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14336. (hp1.typ <> ait_instruction) or
  14337. not
  14338. (
  14339. (cs_opt_level3 in current_settings.optimizerswitches) or
  14340. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14341. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14342. ) then
  14343. Exit;
  14344. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14345. subq $x, %rax
  14346. movq %rax, %rdx
  14347. sarq $63, %rdx
  14348. (%rax still in use)
  14349. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14350. leaq $-x(%rax),%rdx
  14351. movq $x, %rax
  14352. sarq $63, %rdx
  14353. ...which is okay since it breaks the dependency chain between
  14354. subq and movq, but if OptPass2MOV is called first:
  14355. subq $x, %rax
  14356. cqto
  14357. ...which is better in all ways, taking only 2 cycles to execute
  14358. and much smaller in code size.
  14359. }
  14360. { The extra register tracking is quite strenuous }
  14361. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14362. MatchInstruction(hp1, A_MOV, []) then
  14363. begin
  14364. { Update the register tracking to the MOV instruction }
  14365. CopyUsedRegs(TempTracking);
  14366. hp2 := p;
  14367. repeat
  14368. UpdateUsedRegs(tai(hp2.Next));
  14369. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14370. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14371. OptPass2SUB get called again }
  14372. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14373. begin
  14374. { Reset the tracking to the current instruction }
  14375. RestoreUsedRegs(TempTracking);
  14376. ReleaseUsedRegs(TempTracking);
  14377. Result := True;
  14378. Exit;
  14379. end;
  14380. { Reset the tracking to the current instruction }
  14381. RestoreUsedRegs(TempTracking);
  14382. ReleaseUsedRegs(TempTracking);
  14383. { If OptPass2MOV returned True, we don't need to set Result to
  14384. True if hp1 didn't change because the SUB instruction didn't
  14385. get modified and we'll be evaluating hp1 again when the
  14386. peephole optimizer reaches it }
  14387. end;
  14388. { Change:
  14389. subl/q $x,%reg1
  14390. movl/q %reg1,%reg2
  14391. To:
  14392. leal/q $-x(%reg1),%reg2
  14393. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14394. Breaks the dependency chain and potentially permits the removal of
  14395. a CMP instruction if one follows.
  14396. }
  14397. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14398. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14399. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14400. (
  14401. { Instructions are guaranteed to be adjacent on -O2 and under }
  14402. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14403. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14404. ) then
  14405. begin
  14406. TransferUsedRegs(TmpUsedRegs);
  14407. hp2 := p;
  14408. repeat
  14409. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14410. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14411. if (
  14412. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14413. not (cs_opt_size in current_settings.optimizerswitches) or
  14414. (
  14415. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14416. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14417. )
  14418. ) then
  14419. begin
  14420. { Change the MOV instruction to a LEA instruction, and update the
  14421. first operand }
  14422. reference_reset(NewRef, 1, []);
  14423. NewRef.base := taicpu(p).oper[1]^.reg;
  14424. NewRef.scalefactor := 1;
  14425. NewRef.offset := -taicpu(p).oper[0]^.val;
  14426. taicpu(hp1).opcode := A_LEA;
  14427. taicpu(hp1).loadref(0, NewRef);
  14428. TransferUsedRegs(TmpUsedRegs);
  14429. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14430. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14431. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14432. begin
  14433. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14434. { Move what is now the LEA instruction to before the SUB instruction }
  14435. Asml.Remove(hp1);
  14436. Asml.InsertBefore(hp1, p);
  14437. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14438. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14439. p := hp1;
  14440. end
  14441. else
  14442. begin
  14443. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14444. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14445. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14446. { hp1 may not be the immediate next instruction under -O3 }
  14447. RemoveCurrentp(p)
  14448. else
  14449. RemoveCurrentp(p, hp1);
  14450. end;
  14451. Result := True;
  14452. end;
  14453. end;
  14454. end;
  14455. end;
  14456. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14457. begin
  14458. { we can skip all instructions not messing with the stack pointer }
  14459. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14460. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14461. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14462. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14463. ({(taicpu(hp1).ops=0) or }
  14464. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14465. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14466. ) and }
  14467. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14468. )
  14469. ) do
  14470. GetNextInstruction(hp1,hp1);
  14471. Result:=assigned(hp1);
  14472. end;
  14473. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14474. var
  14475. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14476. begin
  14477. Result:=false;
  14478. hp5:=nil;
  14479. hp6:=nil;
  14480. hp7:=nil;
  14481. hp8:=nil;
  14482. { replace
  14483. leal(q) x(<stackpointer>),<stackpointer>
  14484. <optional .seh_stackalloc ...>
  14485. <optional .seh_endprologue ...>
  14486. call procname
  14487. <optional NOP>
  14488. leal(q) -x(<stackpointer>),<stackpointer>
  14489. <optional VZEROUPPER>
  14490. ret
  14491. by
  14492. jmp procname
  14493. but do it only on level 4 because it destroys stack back traces
  14494. }
  14495. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14496. MatchOpType(taicpu(p),top_ref,top_reg) and
  14497. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14498. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14499. { the -8, -24, -40 are not required, but bail out early if possible,
  14500. higher values are unlikely }
  14501. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14502. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14503. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14504. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14505. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14506. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14507. GetNextInstruction(p, hp1) and
  14508. { Take a copy of hp1 }
  14509. SetAndTest(hp1, hp4) and
  14510. { trick to skip label }
  14511. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14512. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14513. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14514. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14515. SkipSimpleInstructions(hp1) and
  14516. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14517. GetNextInstruction(hp1, hp2) and
  14518. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14519. { skip nop instruction on win64 }
  14520. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14521. SetAndTest(hp2,hp6) and
  14522. GetNextInstruction(hp2,hp2) and
  14523. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14524. ) and
  14525. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14526. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14527. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14528. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14529. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14530. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14531. { Segment register will be NR_NO }
  14532. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14533. GetNextInstruction(hp2, hp3) and
  14534. { trick to skip label }
  14535. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14536. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14537. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14538. SetAndTest(hp3,hp5) and
  14539. GetNextInstruction(hp3,hp3) and
  14540. MatchInstruction(hp3,A_RET,[S_NO])
  14541. )
  14542. ) and
  14543. (taicpu(hp3).ops=0) then
  14544. begin
  14545. taicpu(hp1).opcode := A_JMP;
  14546. taicpu(hp1).is_jmp := true;
  14547. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14548. { search for the stackalloc directive and remove it }
  14549. hp7:=tai(p.next);
  14550. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14551. begin
  14552. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14553. begin
  14554. { sanity check }
  14555. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14556. Internalerror(2024012201);
  14557. hp8:=tai(hp7.next);
  14558. RemoveInstruction(tai(hp7));
  14559. hp7:=hp8;
  14560. break;
  14561. end
  14562. else
  14563. hp7:=tai(hp7.next);
  14564. end;
  14565. RemoveCurrentP(p, hp4);
  14566. RemoveInstruction(hp2);
  14567. RemoveInstruction(hp3);
  14568. { if there is a vzeroupper instruction then move it before the jmp }
  14569. if Assigned(hp5) then
  14570. begin
  14571. AsmL.Remove(hp5);
  14572. ASmL.InsertBefore(hp5,hp1)
  14573. end;
  14574. { remove nop on win64 }
  14575. if Assigned(hp6) then
  14576. RemoveInstruction(hp6);
  14577. Result:=true;
  14578. end;
  14579. end;
  14580. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14581. {$ifdef x86_64}
  14582. var
  14583. hp1, hp2, hp3, hp4, hp5: tai;
  14584. {$endif x86_64}
  14585. begin
  14586. Result:=false;
  14587. {$ifdef x86_64}
  14588. hp5:=nil;
  14589. { replace
  14590. push %rax
  14591. call procname
  14592. pop %rcx
  14593. ret
  14594. by
  14595. jmp procname
  14596. but do it only on level 4 because it destroys stack back traces
  14597. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14598. for all supported calling conventions
  14599. }
  14600. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14601. MatchOpType(taicpu(p),top_reg) and
  14602. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14603. GetNextInstruction(p, hp1) and
  14604. { Take a copy of hp1 }
  14605. SetAndTest(hp1, hp4) and
  14606. { trick to skip label }
  14607. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14608. SkipSimpleInstructions(hp1) and
  14609. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14610. GetNextInstruction(hp1, hp2) and
  14611. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14612. MatchOpType(taicpu(hp2),top_reg) and
  14613. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14614. GetNextInstruction(hp2, hp3) and
  14615. { trick to skip label }
  14616. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14617. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14618. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14619. SetAndTest(hp3,hp5) and
  14620. GetNextInstruction(hp3,hp3) and
  14621. MatchInstruction(hp3,A_RET,[S_NO])
  14622. )
  14623. ) and
  14624. (taicpu(hp3).ops=0) then
  14625. begin
  14626. taicpu(hp1).opcode := A_JMP;
  14627. taicpu(hp1).is_jmp := true;
  14628. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14629. RemoveCurrentP(p, hp4);
  14630. RemoveInstruction(hp2);
  14631. RemoveInstruction(hp3);
  14632. if Assigned(hp5) then
  14633. begin
  14634. AsmL.Remove(hp5);
  14635. ASmL.InsertBefore(hp5,hp1)
  14636. end;
  14637. Result:=true;
  14638. end;
  14639. {$endif x86_64}
  14640. end;
  14641. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14642. var
  14643. Value, RegName: string;
  14644. hp1: tai;
  14645. begin
  14646. Result:=false;
  14647. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14648. begin
  14649. case taicpu(p).oper[0]^.val of
  14650. 0:
  14651. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14652. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14653. (
  14654. { See if we can still convert the instruction }
  14655. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14656. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14657. ) then
  14658. begin
  14659. { change "mov $0,%reg" into "xor %reg,%reg" }
  14660. taicpu(p).opcode := A_XOR;
  14661. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14662. Result := True;
  14663. {$ifdef x86_64}
  14664. end
  14665. else if (taicpu(p).opsize = S_Q) then
  14666. begin
  14667. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14668. { The actual optimization }
  14669. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14670. taicpu(p).changeopsize(S_L);
  14671. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14672. Result := True;
  14673. end;
  14674. $1..$FFFFFFFF:
  14675. begin
  14676. { Code size reduction by J. Gareth "Kit" Moreton }
  14677. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14678. case taicpu(p).opsize of
  14679. S_Q:
  14680. begin
  14681. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14682. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14683. { The actual optimization }
  14684. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14685. taicpu(p).changeopsize(S_L);
  14686. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14687. Result := True;
  14688. end;
  14689. else
  14690. { Do nothing };
  14691. end;
  14692. {$endif x86_64}
  14693. end;
  14694. -1:
  14695. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14696. if (cs_opt_size in current_settings.optimizerswitches) and
  14697. (taicpu(p).opsize <> S_B) and
  14698. (
  14699. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14700. (
  14701. { See if we can still convert the instruction }
  14702. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14703. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14704. )
  14705. ) then
  14706. begin
  14707. { change "mov $-1,%reg" into "or $-1,%reg" }
  14708. { NOTES:
  14709. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14710. - This operation creates a false dependency on the register, so only do it when optimising for size
  14711. - 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
  14712. }
  14713. taicpu(p).opcode := A_OR;
  14714. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14715. Result := True;
  14716. end;
  14717. else
  14718. { Do nothing };
  14719. end;
  14720. end;
  14721. end;
  14722. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14723. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14724. begin
  14725. Result := False;
  14726. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14727. Exit;
  14728. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14729. so don't bother optimising }
  14730. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14731. Exit;
  14732. if (taicpu(p).oper[0]^.typ <> top_const) or
  14733. { If the value can fit into an 8-bit signed integer, a smaller
  14734. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14735. falls within this range }
  14736. (
  14737. (taicpu(p).oper[0]^.val > -128) and
  14738. (taicpu(p).oper[0]^.val <= 127)
  14739. ) then
  14740. Exit;
  14741. { If we're optimising for size, this is acceptable }
  14742. if (cs_opt_size in current_settings.optimizerswitches) then
  14743. Exit(True);
  14744. if (taicpu(p).oper[1]^.typ = top_reg) and
  14745. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14746. Exit(True);
  14747. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14748. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14749. Exit(True);
  14750. end;
  14751. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14752. var
  14753. hp1: tai;
  14754. Value: TCGInt;
  14755. begin
  14756. Result := False;
  14757. if MatchOpType(taicpu(p), top_const, top_reg) then
  14758. begin
  14759. { Detect:
  14760. andw x, %ax (0 <= x < $8000)
  14761. ...
  14762. movzwl %ax,%eax
  14763. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14764. }
  14765. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14766. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14767. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14768. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14769. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14770. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14771. begin
  14772. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14773. taicpu(hp1).opcode := A_CWDE;
  14774. taicpu(hp1).clearop(0);
  14775. taicpu(hp1).clearop(1);
  14776. taicpu(hp1).ops := 0;
  14777. { A change was made, but not with p, so don't set Result, but
  14778. notify the compiler that a change was made }
  14779. Include(OptsToCheck, aoc_ForceNewIteration);
  14780. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14781. end;
  14782. end;
  14783. { If "not x" is a power of 2 (popcnt = 1), change:
  14784. and $x, %reg/ref
  14785. To:
  14786. btr lb(x), %reg/ref
  14787. }
  14788. if IsBTXAcceptable(p) and
  14789. (
  14790. { Make sure a TEST doesn't follow that plays with the register }
  14791. not GetNextInstruction(p, hp1) or
  14792. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14793. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14794. ) then
  14795. begin
  14796. {$push}{$R-}{$Q-}
  14797. { Value is a sign-extended 32-bit integer - just correct it
  14798. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14799. checks to see if this operand is an immediate. }
  14800. Value := not taicpu(p).oper[0]^.val;
  14801. {$pop}
  14802. {$ifdef x86_64}
  14803. if taicpu(p).opsize = S_L then
  14804. {$endif x86_64}
  14805. Value := Value and $FFFFFFFF;
  14806. if (PopCnt(QWord(Value)) = 1) then
  14807. begin
  14808. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14809. taicpu(p).opcode := A_BTR;
  14810. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14811. Result := True;
  14812. Exit;
  14813. end;
  14814. end;
  14815. end;
  14816. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14817. begin
  14818. Result := False;
  14819. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14820. Exit;
  14821. { Convert:
  14822. movswl %ax,%eax -> cwtl
  14823. movslq %eax,%rax -> cdqe
  14824. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14825. refer to the same opcode and depends only on the assembler's
  14826. current operand-size attribute. [Kit]
  14827. }
  14828. with taicpu(p) do
  14829. case opsize of
  14830. S_WL:
  14831. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14832. begin
  14833. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14834. opcode := A_CWDE;
  14835. clearop(0);
  14836. clearop(1);
  14837. ops := 0;
  14838. Result := True;
  14839. end;
  14840. {$ifdef x86_64}
  14841. S_LQ:
  14842. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14843. begin
  14844. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14845. opcode := A_CDQE;
  14846. clearop(0);
  14847. clearop(1);
  14848. ops := 0;
  14849. Result := True;
  14850. end;
  14851. {$endif x86_64}
  14852. else
  14853. ;
  14854. end;
  14855. end;
  14856. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14857. var
  14858. hp1, hp2: tai;
  14859. IdentityMask, Shift: TCGInt;
  14860. LimitSize: Topsize;
  14861. DoNotMerge: Boolean;
  14862. begin
  14863. Result := False;
  14864. { All these optimisations work on "shr const,%reg" }
  14865. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14866. Exit;
  14867. DoNotMerge := False;
  14868. Shift := taicpu(p).oper[0]^.val;
  14869. LimitSize := taicpu(p).opsize;
  14870. hp1 := p;
  14871. repeat
  14872. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14873. Break;
  14874. { Detect:
  14875. shr x, %reg
  14876. and y, %reg
  14877. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14878. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14879. }
  14880. case taicpu(hp1).opcode of
  14881. A_AND:
  14882. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14883. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14884. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14885. begin
  14886. { Make sure the FLAGS register isn't in use }
  14887. TransferUsedRegs(TmpUsedRegs);
  14888. hp2 := p;
  14889. repeat
  14890. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14891. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14892. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14893. begin
  14894. { Generate the identity mask }
  14895. case taicpu(p).opsize of
  14896. S_B:
  14897. IdentityMask := $FF shr Shift;
  14898. S_W:
  14899. IdentityMask := $FFFF shr Shift;
  14900. S_L:
  14901. IdentityMask := $FFFFFFFF shr Shift;
  14902. {$ifdef x86_64}
  14903. S_Q:
  14904. { We need to force the operands to be unsigned 64-bit
  14905. integers otherwise the wrong value is generated }
  14906. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14907. {$endif x86_64}
  14908. else
  14909. InternalError(2022081501);
  14910. end;
  14911. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14912. begin
  14913. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14914. { All the possible 1 bits are covered, so we can remove the AND }
  14915. hp2 := tai(hp1.Previous);
  14916. RemoveInstruction(hp1);
  14917. { p wasn't actually changed, so don't set Result to True,
  14918. but a change was nonetheless made elsewhere }
  14919. Include(OptsToCheck, aoc_ForceNewIteration);
  14920. { Do another pass in case other AND or MOVZX instructions
  14921. follow }
  14922. hp1 := hp2;
  14923. Continue;
  14924. end;
  14925. end;
  14926. end;
  14927. A_TEST, A_CMP, A_Jcc:
  14928. { Skip over conditional jumps and relevant comparisons }
  14929. Continue;
  14930. A_MOVZX:
  14931. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14932. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14933. begin
  14934. { Since the original register is being read as is, subsequent
  14935. SHRs must not be merged at this point }
  14936. DoNotMerge := True;
  14937. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14938. begin
  14939. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14940. begin
  14941. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14942. { All the possible 1 bits are covered, so we can remove the AND }
  14943. hp2 := tai(hp1.Previous);
  14944. RemoveInstruction(hp1);
  14945. hp1 := hp2;
  14946. end
  14947. else { Different register target }
  14948. begin
  14949. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14950. taicpu(hp1).opcode := A_MOV;
  14951. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14952. case taicpu(hp1).opsize of
  14953. S_BW:
  14954. taicpu(hp1).opsize := S_W;
  14955. S_BL, S_WL:
  14956. taicpu(hp1).opsize := S_L;
  14957. else
  14958. InternalError(2022081503);
  14959. end;
  14960. end;
  14961. end
  14962. else if (Shift > 0) and
  14963. (taicpu(p).opsize = S_W) and
  14964. (taicpu(hp1).opsize = S_WL) and
  14965. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14966. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14967. begin
  14968. { Detect:
  14969. shr x, %ax (x > 0)
  14970. ...
  14971. movzwl %ax,%eax
  14972. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14973. }
  14974. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14975. taicpu(hp1).opcode := A_CWDE;
  14976. taicpu(hp1).clearop(0);
  14977. taicpu(hp1).clearop(1);
  14978. taicpu(hp1).ops := 0;
  14979. end;
  14980. { Move onto the next instruction }
  14981. Continue;
  14982. end;
  14983. A_SHL, A_SAL, A_SHR:
  14984. if (taicpu(hp1).opsize <= LimitSize) and
  14985. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14986. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14987. begin
  14988. { Make sure the sizes don't exceed the register size limit
  14989. (measured by the shift value falling below the limit) }
  14990. if taicpu(hp1).opsize < LimitSize then
  14991. LimitSize := taicpu(hp1).opsize;
  14992. if taicpu(hp1).opcode = A_SHR then
  14993. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14994. else
  14995. begin
  14996. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14997. DoNotMerge := True;
  14998. end;
  14999. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  15000. Break;
  15001. { Since we've established that the combined shift is within
  15002. limits, we can actually combine the adjacent SHR
  15003. instructions even if they're different sizes }
  15004. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  15005. begin
  15006. hp2 := tai(hp1.Previous);
  15007. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  15008. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  15009. RemoveInstruction(hp1);
  15010. hp1 := hp2;
  15011. end;
  15012. { Move onto the next instruction }
  15013. Continue;
  15014. end;
  15015. else
  15016. ;
  15017. end;
  15018. Break;
  15019. until False;
  15020. { Detect the following (looking backwards):
  15021. shr %cl,%reg
  15022. shr x, %reg
  15023. Swap the two SHR instructions to minimise a pipeline stall.
  15024. }
  15025. if GetLastInstruction(p, hp1) and
  15026. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15027. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15028. { First operand will be %cl }
  15029. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15030. { Just to be sure }
  15031. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15032. begin
  15033. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15034. { Moving the entries this way ensures the register tracking remains correct }
  15035. Asml.Remove(p);
  15036. Asml.InsertBefore(p, hp1);
  15037. p := hp1;
  15038. { Don't set Result to True because the current instruction is now
  15039. "shr %cl,%reg" and there's nothing more we can do with it }
  15040. end;
  15041. end;
  15042. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15043. var
  15044. hp1, hp2: tai;
  15045. Opposite, SecondOpposite: TAsmOp;
  15046. NewCond: TAsmCond;
  15047. begin
  15048. Result := False;
  15049. { Change:
  15050. add/sub 128,(dest)
  15051. To:
  15052. sub/add -128,(dest)
  15053. This generaally takes fewer bytes to encode because -128 can be stored
  15054. in a signed byte, whereas +128 cannot.
  15055. }
  15056. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15057. begin
  15058. if taicpu(p).opcode = A_ADD then
  15059. Opposite := A_SUB
  15060. else
  15061. Opposite := A_ADD;
  15062. { Be careful if the flags are in use, because the CF flag inverts
  15063. when changing from ADD to SUB and vice versa }
  15064. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15065. GetNextInstruction(p, hp1) then
  15066. begin
  15067. TransferUsedRegs(TmpUsedRegs);
  15068. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15069. hp2 := hp1;
  15070. { Scan ahead to check if everything's safe }
  15071. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15072. begin
  15073. if (hp1.typ <> ait_instruction) then
  15074. { Probably unsafe since the flags are still in use }
  15075. Exit;
  15076. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15077. { Stop searching at an unconditional jump }
  15078. Break;
  15079. if not
  15080. (
  15081. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15082. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15083. ) and
  15084. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15085. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15086. Exit;
  15087. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15088. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15089. { Move to the next instruction }
  15090. GetNextInstruction(hp1, hp1);
  15091. end;
  15092. while Assigned(hp2) and (hp2 <> hp1) do
  15093. begin
  15094. NewCond := C_None;
  15095. case taicpu(hp2).condition of
  15096. C_A, C_NBE:
  15097. NewCond := C_BE;
  15098. C_B, C_C, C_NAE:
  15099. NewCond := C_AE;
  15100. C_AE, C_NB, C_NC:
  15101. NewCond := C_B;
  15102. C_BE, C_NA:
  15103. NewCond := C_A;
  15104. else
  15105. { No change needed };
  15106. end;
  15107. if NewCond <> C_None then
  15108. begin
  15109. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15110. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15111. taicpu(hp2).condition := NewCond;
  15112. end
  15113. else
  15114. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15115. begin
  15116. { Because of the flipping of the carry bit, to ensure
  15117. the operation remains equivalent, ADC becomes SBB
  15118. and vice versa, and the constant is not-inverted.
  15119. If multiple ADCs or SBBs appear in a row, each one
  15120. changed causes the carry bit to invert, so they all
  15121. need to be flipped }
  15122. if taicpu(hp2).opcode = A_ADC then
  15123. SecondOpposite := A_SBB
  15124. else
  15125. SecondOpposite := A_ADC;
  15126. if taicpu(hp2).oper[0]^.typ <> top_const then
  15127. { Should have broken out of this optimisation already }
  15128. InternalError(2021112901);
  15129. 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]^) + ' -> ' +
  15130. 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);
  15131. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15132. taicpu(hp2).opcode := SecondOpposite;
  15133. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15134. end;
  15135. { Move to the next instruction }
  15136. GetNextInstruction(hp2, hp2);
  15137. end;
  15138. if (hp2 <> hp1) then
  15139. InternalError(2021111501);
  15140. end;
  15141. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15142. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15143. taicpu(p).opcode := Opposite;
  15144. taicpu(p).oper[0]^.val := -128;
  15145. { No further optimisations can be made on this instruction, so move
  15146. onto the next one to save time }
  15147. p := tai(p.Next);
  15148. UpdateUsedRegs(p);
  15149. Result := True;
  15150. Exit;
  15151. end;
  15152. { Detect:
  15153. add/sub %reg2,(dest)
  15154. add/sub x, (dest)
  15155. (dest can be a register or a reference)
  15156. Swap the instructions to minimise a pipeline stall. This reverses the
  15157. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15158. optimisations could be made.
  15159. }
  15160. if (taicpu(p).oper[0]^.typ = top_reg) and
  15161. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15162. (
  15163. (
  15164. (taicpu(p).oper[1]^.typ = top_reg) and
  15165. { We can try searching further ahead if we're writing to a register }
  15166. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15167. ) or
  15168. (
  15169. (taicpu(p).oper[1]^.typ = top_ref) and
  15170. GetNextInstruction(p, hp1)
  15171. )
  15172. ) and
  15173. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15174. (taicpu(hp1).oper[0]^.typ = top_const) and
  15175. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15176. begin
  15177. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15178. TransferUsedRegs(TmpUsedRegs);
  15179. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15180. hp2 := p;
  15181. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15182. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15183. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15184. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15185. begin
  15186. asml.remove(hp1);
  15187. asml.InsertBefore(hp1, p);
  15188. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15189. Result := True;
  15190. end;
  15191. end;
  15192. end;
  15193. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15194. var
  15195. hp1: tai;
  15196. begin
  15197. Result:=false;
  15198. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15199. while GetNextInstruction(p, hp1) and
  15200. TrySwapMovCmp(p, hp1) do
  15201. begin
  15202. if MatchInstruction(hp1, A_MOV, []) then
  15203. begin
  15204. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15205. begin
  15206. { A little hacky, but since CMP doesn't read the flags, only
  15207. modify them, it's safe if they get scrambled by MOV -> XOR }
  15208. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15209. Result := PostPeepholeOptMov(hp1);
  15210. {$ifdef x86_64}
  15211. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15212. { Used to shrink instruction size }
  15213. PostPeepholeOptXor(hp1);
  15214. {$endif x86_64}
  15215. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15216. end
  15217. else
  15218. begin
  15219. Result := PostPeepholeOptMov(hp1);
  15220. {$ifdef x86_64}
  15221. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15222. { Used to shrink instruction size }
  15223. PostPeepholeOptXor(hp1);
  15224. {$endif x86_64}
  15225. end;
  15226. end;
  15227. { Enabling this flag is actually a null operation, but it marks
  15228. the code as 'modified' during this pass }
  15229. Include(OptsToCheck, aoc_ForceNewIteration);
  15230. end;
  15231. { change "cmp $0, %reg" to "test %reg, %reg" }
  15232. if MatchOpType(taicpu(p),top_const,top_reg) and
  15233. (taicpu(p).oper[0]^.val = 0) then
  15234. begin
  15235. taicpu(p).opcode := A_TEST;
  15236. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15237. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15238. Result:=true;
  15239. end;
  15240. end;
  15241. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15242. var
  15243. IsTestConstX, IsValid : Boolean;
  15244. hp1,hp2 : tai;
  15245. begin
  15246. Result:=false;
  15247. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15248. if (taicpu(p).opcode = A_TEST) then
  15249. while GetNextInstruction(p, hp1) and
  15250. TrySwapMovCmp(p, hp1) do
  15251. begin
  15252. if MatchInstruction(hp1, A_MOV, []) then
  15253. begin
  15254. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15255. begin
  15256. { A little hacky, but since TEST doesn't read the flags, only
  15257. modify them, it's safe if they get scrambled by MOV -> XOR }
  15258. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15259. Result := PostPeepholeOptMov(hp1);
  15260. {$ifdef x86_64}
  15261. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15262. { Used to shrink instruction size }
  15263. PostPeepholeOptXor(hp1);
  15264. {$endif x86_64}
  15265. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15266. end
  15267. else
  15268. begin
  15269. Result := PostPeepholeOptMov(hp1);
  15270. {$ifdef x86_64}
  15271. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15272. { Used to shrink instruction size }
  15273. PostPeepholeOptXor(hp1);
  15274. {$endif x86_64}
  15275. end;
  15276. end;
  15277. { Enabling this flag is actually a null operation, but it marks
  15278. the code as 'modified' during this pass }
  15279. Include(OptsToCheck, aoc_ForceNewIteration);
  15280. end;
  15281. { If x is a power of 2 (popcnt = 1), change:
  15282. or $x, %reg/ref
  15283. To:
  15284. bts lb(x), %reg/ref
  15285. }
  15286. if (taicpu(p).opcode = A_OR) and
  15287. IsBTXAcceptable(p) and
  15288. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15289. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15290. (
  15291. { Don't optimise if a test instruction follows }
  15292. not GetNextInstruction(p, hp1) or
  15293. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15294. ) then
  15295. begin
  15296. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  15297. taicpu(p).opcode := A_BTS;
  15298. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15299. Result := True;
  15300. Exit;
  15301. end;
  15302. { If x is a power of 2 (popcnt = 1), change:
  15303. test $x, %reg/ref
  15304. je / sete / cmove (or jne / setne)
  15305. To:
  15306. bt lb(x), %reg/ref
  15307. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15308. }
  15309. if (taicpu(p).opcode = A_TEST) and
  15310. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15311. (taicpu(p).oper[0]^.typ = top_const) and
  15312. (
  15313. (cs_opt_size in current_settings.optimizerswitches) or
  15314. (
  15315. (taicpu(p).oper[1]^.typ = top_reg) and
  15316. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15317. ) or
  15318. (
  15319. (taicpu(p).oper[1]^.typ <> top_reg) and
  15320. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15321. )
  15322. ) and
  15323. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15324. { For sizes less than S_L, the byte size is equal or larger with BT,
  15325. so don't bother optimising }
  15326. (taicpu(p).opsize >= S_L) then
  15327. begin
  15328. IsValid := True;
  15329. { Check the next set of instructions, watching the FLAGS register
  15330. and the conditions used }
  15331. TransferUsedRegs(TmpUsedRegs);
  15332. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15333. hp1 := p;
  15334. hp2 := nil;
  15335. while GetNextInstruction(hp1, hp1) do
  15336. begin
  15337. if not Assigned(hp2) then
  15338. { The first instruction after TEST }
  15339. hp2 := hp1;
  15340. if (hp1.typ <> ait_instruction) then
  15341. begin
  15342. { If the flags are no longer in use, everything is fine }
  15343. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15344. IsValid := False;
  15345. Break;
  15346. end;
  15347. case taicpu(hp1).condition of
  15348. C_None:
  15349. begin
  15350. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15351. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15352. { Something is not quite normal, so play safe and don't change }
  15353. IsValid := False;
  15354. Break;
  15355. end;
  15356. C_E, C_Z, C_NE, C_NZ:
  15357. { This is fine };
  15358. else
  15359. begin
  15360. { Unsupported condition }
  15361. IsValid := False;
  15362. Break;
  15363. end;
  15364. end;
  15365. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15366. end;
  15367. if IsValid then
  15368. begin
  15369. while hp2 <> hp1 do
  15370. begin
  15371. case taicpu(hp2).condition of
  15372. C_Z, C_E:
  15373. taicpu(hp2).condition := C_NC;
  15374. C_NZ, C_NE:
  15375. taicpu(hp2).condition := C_C;
  15376. else
  15377. { Should not get this by this point }
  15378. InternalError(2022110701);
  15379. end;
  15380. GetNextInstruction(hp2, hp2);
  15381. end;
  15382. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  15383. taicpu(p).opcode := A_BT;
  15384. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15385. Result := True;
  15386. Exit;
  15387. end;
  15388. end;
  15389. { removes the line marked with (x) from the sequence
  15390. and/or/xor/add/sub/... $x, %y
  15391. test/or %y, %y | test $-1, %y (x)
  15392. j(n)z _Label
  15393. as the first instruction already adjusts the ZF
  15394. %y operand may also be a reference }
  15395. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15396. MatchOperand(taicpu(p).oper[0]^,-1);
  15397. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15398. GetLastInstruction(p, hp1) and
  15399. (tai(hp1).typ = ait_instruction) and
  15400. GetNextInstruction(p,hp2) and
  15401. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15402. case taicpu(hp1).opcode Of
  15403. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15404. { These two instructions set the zero flag if the result is zero }
  15405. A_POPCNT, A_LZCNT:
  15406. begin
  15407. if (
  15408. { With POPCNT, an input of zero will set the zero flag
  15409. because the population count of zero is zero }
  15410. (taicpu(hp1).opcode = A_POPCNT) and
  15411. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15412. (
  15413. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15414. { Faster than going through the second half of the 'or'
  15415. condition below }
  15416. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15417. )
  15418. ) or (
  15419. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15420. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15421. { and in case of carry for A(E)/B(E)/C/NC }
  15422. (
  15423. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15424. (
  15425. (taicpu(hp1).opcode <> A_ADD) and
  15426. (taicpu(hp1).opcode <> A_SUB) and
  15427. (taicpu(hp1).opcode <> A_LZCNT)
  15428. )
  15429. )
  15430. ) then
  15431. begin
  15432. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15433. RemoveCurrentP(p, hp2);
  15434. Result:=true;
  15435. Exit;
  15436. end;
  15437. end;
  15438. A_SHL, A_SAL, A_SHR, A_SAR:
  15439. begin
  15440. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15441. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15442. { therefore, it's only safe to do this optimization for }
  15443. { shifts by a (nonzero) constant }
  15444. (taicpu(hp1).oper[0]^.typ = top_const) and
  15445. (taicpu(hp1).oper[0]^.val <> 0) and
  15446. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15447. { and in case of carry for A(E)/B(E)/C/NC }
  15448. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15449. begin
  15450. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15451. RemoveCurrentP(p, hp2);
  15452. Result:=true;
  15453. Exit;
  15454. end;
  15455. end;
  15456. A_DEC, A_INC, A_NEG:
  15457. begin
  15458. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15459. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15460. { and in case of carry for A(E)/B(E)/C/NC }
  15461. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15462. begin
  15463. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15464. RemoveCurrentP(p, hp2);
  15465. Result:=true;
  15466. Exit;
  15467. end;
  15468. end;
  15469. A_ANDN, A_BZHI:
  15470. begin
  15471. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15472. { Only the zero and sign flags are consistent with what the result is }
  15473. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15474. begin
  15475. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15476. RemoveCurrentP(p, hp2);
  15477. Result:=true;
  15478. Exit;
  15479. end;
  15480. end;
  15481. A_BEXTR:
  15482. begin
  15483. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15484. { Only the zero flag is set }
  15485. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15486. begin
  15487. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15488. RemoveCurrentP(p, hp2);
  15489. Result:=true;
  15490. Exit;
  15491. end;
  15492. end;
  15493. else
  15494. ;
  15495. end; { case }
  15496. { change "test $-1,%reg" into "test %reg,%reg" }
  15497. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15498. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15499. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15500. if MatchInstruction(p, A_OR, []) and
  15501. { Can only match if they're both registers }
  15502. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15503. begin
  15504. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15505. taicpu(p).opcode := A_TEST;
  15506. { No need to set Result to True, as we've done all the optimisations we can }
  15507. end;
  15508. end;
  15509. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15510. var
  15511. hp1,hp3 : tai;
  15512. {$ifndef x86_64}
  15513. hp2 : taicpu;
  15514. {$endif x86_64}
  15515. begin
  15516. Result:=false;
  15517. hp3:=nil;
  15518. {$ifndef x86_64}
  15519. { don't do this on modern CPUs, this really hurts them due to
  15520. broken call/ret pairing }
  15521. if (current_settings.optimizecputype < cpu_Pentium2) and
  15522. not(cs_create_pic in current_settings.moduleswitches) and
  15523. GetNextInstruction(p, hp1) and
  15524. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15525. MatchOpType(taicpu(hp1),top_ref) and
  15526. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15527. begin
  15528. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15529. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15530. InsertLLItem(p.previous, p, hp2);
  15531. taicpu(p).opcode := A_JMP;
  15532. taicpu(p).is_jmp := true;
  15533. RemoveInstruction(hp1);
  15534. Result:=true;
  15535. end
  15536. else
  15537. {$endif x86_64}
  15538. { replace
  15539. call procname
  15540. ret
  15541. by
  15542. jmp procname
  15543. but do it only on level 4 because it destroys stack back traces
  15544. else if the subroutine is marked as no return, remove the ret
  15545. }
  15546. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15547. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15548. GetNextInstruction(p, hp1) and
  15549. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15550. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15551. SetAndTest(hp1,hp3) and
  15552. GetNextInstruction(hp1,hp1) and
  15553. MatchInstruction(hp1,A_RET,[S_NO])
  15554. )
  15555. ) and
  15556. (taicpu(hp1).ops=0) then
  15557. begin
  15558. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15559. { we might destroy stack alignment here if we do not do a call }
  15560. (target_info.stackalign<=sizeof(SizeUInt)) then
  15561. begin
  15562. taicpu(p).opcode := A_JMP;
  15563. taicpu(p).is_jmp := true;
  15564. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15565. end
  15566. else
  15567. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15568. RemoveInstruction(hp1);
  15569. if Assigned(hp3) then
  15570. begin
  15571. AsmL.Remove(hp3);
  15572. AsmL.InsertBefore(hp3,p)
  15573. end;
  15574. Result:=true;
  15575. end;
  15576. end;
  15577. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15578. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15579. begin
  15580. case OpSize of
  15581. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15582. Result := (Val <= $FF) and (Val >= -128);
  15583. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15584. Result := (Val <= $FFFF) and (Val >= -32768);
  15585. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15586. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15587. else
  15588. Result := True;
  15589. end;
  15590. end;
  15591. var
  15592. hp1, hp2 : tai;
  15593. SizeChange: Boolean;
  15594. PreMessage: string;
  15595. begin
  15596. Result := False;
  15597. if (taicpu(p).oper[0]^.typ = top_reg) and
  15598. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15599. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15600. begin
  15601. { Change (using movzbl %al,%eax as an example):
  15602. movzbl %al, %eax movzbl %al, %eax
  15603. cmpl x, %eax testl %eax,%eax
  15604. To:
  15605. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15606. movzbl %al, %eax movzbl %al, %eax
  15607. Smaller instruction and minimises pipeline stall as the CPU
  15608. doesn't have to wait for the register to get zero-extended. [Kit]
  15609. Also allow if the smaller of the two registers is being checked,
  15610. as this still removes the false dependency.
  15611. }
  15612. if
  15613. (
  15614. (
  15615. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15616. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15617. ) or (
  15618. { If MatchOperand returns True, they must both be registers }
  15619. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15620. )
  15621. ) and
  15622. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15623. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15624. begin
  15625. 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);
  15626. asml.Remove(hp1);
  15627. asml.InsertBefore(hp1, p);
  15628. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15629. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15630. begin
  15631. taicpu(hp1).opcode := A_TEST;
  15632. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15633. end;
  15634. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15635. case taicpu(p).opsize of
  15636. S_BW, S_BL:
  15637. begin
  15638. SizeChange := taicpu(hp1).opsize <> S_B;
  15639. taicpu(hp1).changeopsize(S_B);
  15640. end;
  15641. S_WL:
  15642. begin
  15643. SizeChange := taicpu(hp1).opsize <> S_W;
  15644. taicpu(hp1).changeopsize(S_W);
  15645. end
  15646. else
  15647. InternalError(2020112701);
  15648. end;
  15649. UpdateUsedRegs(tai(p.Next));
  15650. { Check if the register is used aferwards - if not, we can
  15651. remove the movzx instruction completely }
  15652. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15653. begin
  15654. { Hp1 is a better position than p for debugging purposes }
  15655. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15656. RemoveCurrentp(p, hp1);
  15657. Result := True;
  15658. end;
  15659. if SizeChange then
  15660. DebugMsg(SPeepholeOptimization + PreMessage +
  15661. 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)
  15662. else
  15663. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15664. Exit;
  15665. end;
  15666. { Change (using movzwl %ax,%eax as an example):
  15667. movzwl %ax, %eax
  15668. movb %al, (dest) (Register is smaller than read register in movz)
  15669. To:
  15670. movb %al, (dest) (Move one back to avoid a false dependency)
  15671. movzwl %ax, %eax
  15672. }
  15673. if (taicpu(hp1).opcode = A_MOV) and
  15674. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15675. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15676. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15677. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15678. begin
  15679. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15680. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15681. asml.Remove(hp1);
  15682. asml.InsertBefore(hp1, p);
  15683. if taicpu(hp1).oper[1]^.typ = top_reg then
  15684. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15685. { Check if the register is used aferwards - if not, we can
  15686. remove the movzx instruction completely }
  15687. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15688. begin
  15689. { Hp1 is a better position than p for debugging purposes }
  15690. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15691. RemoveCurrentp(p, hp1);
  15692. Result := True;
  15693. end;
  15694. Exit;
  15695. end;
  15696. end;
  15697. end;
  15698. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15699. var
  15700. hp1: tai;
  15701. {$ifdef x86_64}
  15702. PreMessage, RegName: string;
  15703. {$endif x86_64}
  15704. begin
  15705. Result := False;
  15706. { If x is a power of 2 (popcnt = 1), change:
  15707. xor $x, %reg/ref
  15708. To:
  15709. btc lb(x), %reg/ref
  15710. }
  15711. if IsBTXAcceptable(p) and
  15712. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15713. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15714. (
  15715. { Don't optimise if a test instruction follows }
  15716. not GetNextInstruction(p, hp1) or
  15717. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15718. ) then
  15719. begin
  15720. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  15721. taicpu(p).opcode := A_BTC;
  15722. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15723. Result := True;
  15724. Exit;
  15725. end;
  15726. {$ifdef x86_64}
  15727. { Code size reduction by J. Gareth "Kit" Moreton }
  15728. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15729. as this removes the REX prefix }
  15730. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15731. Exit;
  15732. if taicpu(p).oper[0]^.typ <> top_reg then
  15733. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15734. InternalError(2018011500);
  15735. case taicpu(p).opsize of
  15736. S_Q:
  15737. begin
  15738. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15739. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15740. { The actual optimization }
  15741. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15742. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15743. taicpu(p).changeopsize(S_L);
  15744. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15745. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15746. end;
  15747. else
  15748. ;
  15749. end;
  15750. {$endif x86_64}
  15751. end;
  15752. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15753. var
  15754. XReg: TRegister;
  15755. begin
  15756. Result := False;
  15757. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15758. Smaller encoding and slightly faster on some platforms (also works for
  15759. ZMM-sized registers) }
  15760. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15761. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15762. begin
  15763. XReg := taicpu(p).oper[0]^.reg;
  15764. if (taicpu(p).oper[1]^.reg = XReg) then
  15765. begin
  15766. taicpu(p).changeopsize(S_XMM);
  15767. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15768. if (cs_opt_size in current_settings.optimizerswitches) then
  15769. begin
  15770. { Change input registers to %xmm0 to reduce size. Note that
  15771. there's a risk of a false dependency doing this, so only
  15772. optimise for size here }
  15773. XReg := NR_XMM0;
  15774. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15775. end
  15776. else
  15777. begin
  15778. setsubreg(XReg, R_SUBMMX);
  15779. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15780. end;
  15781. taicpu(p).oper[0]^.reg := XReg;
  15782. taicpu(p).oper[1]^.reg := XReg;
  15783. Result := True;
  15784. end;
  15785. end;
  15786. end;
  15787. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15788. var
  15789. OperIdx: Integer;
  15790. begin
  15791. for OperIdx := 0 to p.ops - 1 do
  15792. if p.oper[OperIdx]^.typ = top_ref then
  15793. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15794. end;
  15795. end.