aoptx86.pas 398 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375
  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. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  42. potentially allowing further optimisation (although it might need to know if
  43. it crossed a conditional jump. }
  44. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  45. {
  46. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  47. the use of a register by allocs/dealloc, so it can ignore calls.
  48. In the following example, GetNextInstructionUsingReg will return the second movq,
  49. GetNextInstructionUsingRegTrackingUse won't.
  50. movq %rdi,%rax
  51. # Register rdi released
  52. # Register rdi allocated
  53. movq %rax,%rdi
  54. While in this example:
  55. movq %rdi,%rax
  56. call proc
  57. movq %rdi,%rax
  58. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  59. won't.
  60. }
  61. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  62. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  63. private
  64. function SkipSimpleInstructions(var hp1: tai): Boolean;
  65. protected
  66. class function IsMOVZXAcceptable: Boolean; static; inline;
  67. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  68. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  69. { checks whether reading the value in reg1 depends on the value of reg2. This
  70. is very similar to SuperRegisterEquals, except it takes into account that
  71. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  72. depend on the value in AH). }
  73. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  74. { Replaces all references to AOldReg in a memory reference to ANewReg }
  75. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  76. { Replaces all references to AOldReg in an operand to ANewReg }
  77. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  78. { Replaces all references to AOldReg in an instruction to ANewReg,
  79. except where the register is being written }
  80. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  81. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  82. or writes to a global symbol }
  83. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  84. { Returns true if the given MOV instruction can be safely converted to CMOV }
  85. class function CanBeCMOV(p : tai) : boolean; static;
  86. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  87. conversion was successful }
  88. function ConvertLEA(const p : taicpu): Boolean;
  89. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  90. procedure DebugMsg(const s : string; p : tai);inline;
  91. class function IsExitCode(p : tai) : boolean; static;
  92. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  93. procedure RemoveLastDeallocForFuncRes(p : tai);
  94. function DoSubAddOpt(var p : tai) : Boolean;
  95. function PrePeepholeOptSxx(var p : tai) : boolean;
  96. function PrePeepholeOptIMUL(var p : tai) : boolean;
  97. function OptPass1Test(var p: tai): boolean;
  98. function OptPass1Add(var p: tai): boolean;
  99. function OptPass1AND(var p : tai) : boolean;
  100. function OptPass1_V_MOVAP(var p : tai) : boolean;
  101. function OptPass1VOP(var p : tai) : boolean;
  102. function OptPass1MOV(var p : tai) : boolean;
  103. function OptPass1Movx(var p : tai) : boolean;
  104. function OptPass1MOVXX(var p : tai) : boolean;
  105. function OptPass1OP(var p : tai) : boolean;
  106. function OptPass1LEA(var p : tai) : boolean;
  107. function OptPass1Sub(var p : tai) : boolean;
  108. function OptPass1SHLSAL(var p : tai) : boolean;
  109. function OptPass1FSTP(var p : tai) : boolean;
  110. function OptPass1FLD(var p : tai) : boolean;
  111. function OptPass1Cmp(var p : tai) : boolean;
  112. function OptPass1PXor(var p : tai) : boolean;
  113. function OptPass1VPXor(var p: tai): boolean;
  114. function OptPass1Imul(var p : tai) : boolean;
  115. function OptPass1Jcc(var p : tai) : boolean;
  116. function OptPass1SHXX(var p: tai): boolean;
  117. function OptPass2Movx(var p : tai): Boolean;
  118. function OptPass2MOV(var p : tai) : boolean;
  119. function OptPass2Imul(var p : tai) : boolean;
  120. function OptPass2Jmp(var p : tai) : boolean;
  121. function OptPass2Jcc(var p : tai) : boolean;
  122. function OptPass2Lea(var p: tai): Boolean;
  123. function OptPass2SUB(var p: tai): Boolean;
  124. function OptPass2ADD(var p : tai): Boolean;
  125. function OptPass2SETcc(var p : tai) : boolean;
  126. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  127. function PostPeepholeOptMov(var p : tai) : Boolean;
  128. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  129. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  130. function PostPeepholeOptXor(var p : tai) : Boolean;
  131. {$endif}
  132. function PostPeepholeOptAnd(var p : tai) : boolean;
  133. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  134. function PostPeepholeOptCmp(var p : tai) : Boolean;
  135. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  136. function PostPeepholeOptCall(var p : tai) : Boolean;
  137. function PostPeepholeOptLea(var p : tai) : Boolean;
  138. function PostPeepholeOptPush(var p: tai): Boolean;
  139. function PostPeepholeOptShr(var p : tai) : boolean;
  140. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  141. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  142. procedure SwapMovCmp(var p, hp1: tai);
  143. { Processor-dependent reference optimisation }
  144. class procedure OptimizeRefs(var p: taicpu); static;
  145. end;
  146. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  147. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  148. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  149. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  150. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  151. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  152. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  153. {$if max_operands>2}
  154. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  155. {$endif max_operands>2}
  156. function RefsEqual(const r1, r2: treference): boolean;
  157. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  158. { returns true, if ref is a reference using only the registers passed as base and index
  159. and having an offset }
  160. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  161. implementation
  162. uses
  163. cutils,verbose,
  164. systems,
  165. globals,
  166. cpuinfo,
  167. procinfo,
  168. paramgr,
  169. aasmbase,
  170. aoptbase,aoptutils,
  171. symconst,symsym,
  172. cgx86,
  173. itcpugas;
  174. {$ifdef DEBUG_AOPTCPU}
  175. const
  176. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  177. {$else DEBUG_AOPTCPU}
  178. { Empty strings help the optimizer to remove string concatenations that won't
  179. ever appear to the user on release builds. [Kit] }
  180. const
  181. SPeepholeOptimization = '';
  182. {$endif DEBUG_AOPTCPU}
  183. LIST_STEP_SIZE = 4;
  184. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  185. begin
  186. result :=
  187. (instr.typ = ait_instruction) and
  188. (taicpu(instr).opcode = op) and
  189. ((opsize = []) or (taicpu(instr).opsize in opsize));
  190. end;
  191. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  192. begin
  193. result :=
  194. (instr.typ = ait_instruction) and
  195. ((taicpu(instr).opcode = op1) or
  196. (taicpu(instr).opcode = op2)
  197. ) and
  198. ((opsize = []) or (taicpu(instr).opsize in opsize));
  199. end;
  200. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. ((taicpu(instr).opcode = op1) or
  205. (taicpu(instr).opcode = op2) or
  206. (taicpu(instr).opcode = op3)
  207. ) and
  208. ((opsize = []) or (taicpu(instr).opsize in opsize));
  209. end;
  210. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  211. const opsize : topsizes) : boolean;
  212. var
  213. op : TAsmOp;
  214. begin
  215. result:=false;
  216. for op in ops do
  217. begin
  218. if (instr.typ = ait_instruction) and
  219. (taicpu(instr).opcode = op) and
  220. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  221. begin
  222. result:=true;
  223. exit;
  224. end;
  225. end;
  226. end;
  227. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  228. begin
  229. result := (oper.typ = top_reg) and (oper.reg = reg);
  230. end;
  231. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  232. begin
  233. result := (oper.typ = top_const) and (oper.val = a);
  234. end;
  235. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  236. begin
  237. result := oper1.typ = oper2.typ;
  238. if result then
  239. case oper1.typ of
  240. top_const:
  241. Result:=oper1.val = oper2.val;
  242. top_reg:
  243. Result:=oper1.reg = oper2.reg;
  244. top_ref:
  245. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  246. else
  247. internalerror(2013102801);
  248. end
  249. end;
  250. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  251. begin
  252. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  253. if result then
  254. case oper1.typ of
  255. top_const:
  256. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  257. top_reg:
  258. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  259. top_ref:
  260. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  261. else
  262. internalerror(2020052401);
  263. end
  264. end;
  265. function RefsEqual(const r1, r2: treference): boolean;
  266. begin
  267. RefsEqual :=
  268. (r1.offset = r2.offset) and
  269. (r1.segment = r2.segment) and (r1.base = r2.base) and
  270. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  271. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  272. (r1.relsymbol = r2.relsymbol) and
  273. (r1.volatility=[]) and
  274. (r2.volatility=[]);
  275. end;
  276. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  277. begin
  278. Result:=(ref.offset=0) and
  279. (ref.scalefactor in [0,1]) and
  280. (ref.segment=NR_NO) and
  281. (ref.symbol=nil) and
  282. (ref.relsymbol=nil) and
  283. ((base=NR_INVALID) or
  284. (ref.base=base)) and
  285. ((index=NR_INVALID) or
  286. (ref.index=index)) and
  287. (ref.volatility=[]);
  288. end;
  289. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  290. begin
  291. Result:=(ref.scalefactor in [0,1]) and
  292. (ref.segment=NR_NO) and
  293. (ref.symbol=nil) and
  294. (ref.relsymbol=nil) and
  295. ((base=NR_INVALID) or
  296. (ref.base=base)) and
  297. ((index=NR_INVALID) or
  298. (ref.index=index)) and
  299. (ref.volatility=[]);
  300. end;
  301. function InstrReadsFlags(p: tai): boolean;
  302. begin
  303. InstrReadsFlags := true;
  304. case p.typ of
  305. ait_instruction:
  306. if InsProp[taicpu(p).opcode].Ch*
  307. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  308. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  309. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  310. exit;
  311. ait_label:
  312. exit;
  313. else
  314. ;
  315. end;
  316. InstrReadsFlags := false;
  317. end;
  318. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  319. begin
  320. Next:=Current;
  321. repeat
  322. Result:=GetNextInstruction(Next,Next);
  323. until not (Result) or
  324. not(cs_opt_level3 in current_settings.optimizerswitches) or
  325. (Next.typ<>ait_instruction) or
  326. RegInInstruction(reg,Next) or
  327. is_calljmp(taicpu(Next).opcode);
  328. end;
  329. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  330. begin
  331. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  332. Next := Current;
  333. repeat
  334. Result := GetNextInstruction(Next,Next);
  335. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  336. if is_calljmpuncond(taicpu(Next).opcode) then
  337. begin
  338. Result := False;
  339. Exit;
  340. end
  341. else
  342. CrossJump := True;
  343. until not Result or
  344. not (cs_opt_level3 in current_settings.optimizerswitches) or
  345. (Next.typ <> ait_instruction) or
  346. RegInInstruction(reg,Next);
  347. end;
  348. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  349. begin
  350. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  351. begin
  352. Result:=GetNextInstruction(Current,Next);
  353. exit;
  354. end;
  355. Next:=tai(Current.Next);
  356. Result:=false;
  357. while assigned(Next) do
  358. begin
  359. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  360. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  361. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  362. exit
  363. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  364. begin
  365. Result:=true;
  366. exit;
  367. end;
  368. Next:=tai(Next.Next);
  369. end;
  370. end;
  371. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  372. begin
  373. Result:=RegReadByInstruction(reg,hp);
  374. end;
  375. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  376. var
  377. p: taicpu;
  378. opcount: longint;
  379. begin
  380. RegReadByInstruction := false;
  381. if hp.typ <> ait_instruction then
  382. exit;
  383. p := taicpu(hp);
  384. case p.opcode of
  385. A_CALL:
  386. regreadbyinstruction := true;
  387. A_IMUL:
  388. case p.ops of
  389. 1:
  390. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  391. (
  392. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  393. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  394. );
  395. 2,3:
  396. regReadByInstruction :=
  397. reginop(reg,p.oper[0]^) or
  398. reginop(reg,p.oper[1]^);
  399. else
  400. InternalError(2019112801);
  401. end;
  402. A_MUL:
  403. begin
  404. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  405. (
  406. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  407. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  408. );
  409. end;
  410. A_IDIV,A_DIV:
  411. begin
  412. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  413. (
  414. (getregtype(reg)=R_INTREGISTER) and
  415. (
  416. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  417. )
  418. );
  419. end;
  420. else
  421. begin
  422. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  423. begin
  424. RegReadByInstruction := false;
  425. exit;
  426. end;
  427. for opcount := 0 to p.ops-1 do
  428. if (p.oper[opCount]^.typ = top_ref) and
  429. RegInRef(reg,p.oper[opcount]^.ref^) then
  430. begin
  431. RegReadByInstruction := true;
  432. exit
  433. end;
  434. { special handling for SSE MOVSD }
  435. if (p.opcode=A_MOVSD) and (p.ops>0) then
  436. begin
  437. if p.ops<>2 then
  438. internalerror(2017042702);
  439. regReadByInstruction := reginop(reg,p.oper[0]^) or
  440. (
  441. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  442. );
  443. exit;
  444. end;
  445. with insprop[p.opcode] do
  446. begin
  447. if getregtype(reg)=R_INTREGISTER then
  448. begin
  449. case getsupreg(reg) of
  450. RS_EAX:
  451. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  452. begin
  453. RegReadByInstruction := true;
  454. exit
  455. end;
  456. RS_ECX:
  457. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  458. begin
  459. RegReadByInstruction := true;
  460. exit
  461. end;
  462. RS_EDX:
  463. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  464. begin
  465. RegReadByInstruction := true;
  466. exit
  467. end;
  468. RS_EBX:
  469. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  470. begin
  471. RegReadByInstruction := true;
  472. exit
  473. end;
  474. RS_ESP:
  475. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  476. begin
  477. RegReadByInstruction := true;
  478. exit
  479. end;
  480. RS_EBP:
  481. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  482. begin
  483. RegReadByInstruction := true;
  484. exit
  485. end;
  486. RS_ESI:
  487. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  488. begin
  489. RegReadByInstruction := true;
  490. exit
  491. end;
  492. RS_EDI:
  493. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  494. begin
  495. RegReadByInstruction := true;
  496. exit
  497. end;
  498. end;
  499. end;
  500. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  501. begin
  502. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  503. begin
  504. case p.condition of
  505. C_A,C_NBE, { CF=0 and ZF=0 }
  506. C_BE,C_NA: { CF=1 or ZF=1 }
  507. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  508. C_AE,C_NB,C_NC, { CF=0 }
  509. C_B,C_NAE,C_C: { CF=1 }
  510. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  511. C_NE,C_NZ, { ZF=0 }
  512. C_E,C_Z: { ZF=1 }
  513. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  514. C_G,C_NLE, { ZF=0 and SF=OF }
  515. C_LE,C_NG: { ZF=1 or SF<>OF }
  516. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  517. C_GE,C_NL, { SF=OF }
  518. C_L,C_NGE: { SF<>OF }
  519. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  520. C_NO, { OF=0 }
  521. C_O: { OF=1 }
  522. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  523. C_NP,C_PO, { PF=0 }
  524. C_P,C_PE: { PF=1 }
  525. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  526. C_NS, { SF=0 }
  527. C_S: { SF=1 }
  528. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  529. else
  530. internalerror(2017042701);
  531. end;
  532. if RegReadByInstruction then
  533. exit;
  534. end;
  535. case getsubreg(reg) of
  536. R_SUBW,R_SUBD,R_SUBQ:
  537. RegReadByInstruction :=
  538. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  539. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  540. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  541. R_SUBFLAGCARRY:
  542. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  543. R_SUBFLAGPARITY:
  544. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  545. R_SUBFLAGAUXILIARY:
  546. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  547. R_SUBFLAGZERO:
  548. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  549. R_SUBFLAGSIGN:
  550. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  551. R_SUBFLAGOVERFLOW:
  552. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  553. R_SUBFLAGINTERRUPT:
  554. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  555. R_SUBFLAGDIRECTION:
  556. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  557. else
  558. internalerror(2017042601);
  559. end;
  560. exit;
  561. end;
  562. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  563. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  564. (p.oper[0]^.reg=p.oper[1]^.reg) then
  565. exit;
  566. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  567. begin
  568. RegReadByInstruction := true;
  569. exit
  570. end;
  571. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  572. begin
  573. RegReadByInstruction := true;
  574. exit
  575. end;
  576. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  577. begin
  578. RegReadByInstruction := true;
  579. exit
  580. end;
  581. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  582. begin
  583. RegReadByInstruction := true;
  584. exit
  585. end;
  586. end;
  587. end;
  588. end;
  589. end;
  590. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  591. begin
  592. result:=false;
  593. if p1.typ<>ait_instruction then
  594. exit;
  595. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  596. exit(true);
  597. if (getregtype(reg)=R_INTREGISTER) and
  598. { change information for xmm movsd are not correct }
  599. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  600. begin
  601. case getsupreg(reg) of
  602. { RS_EAX = RS_RAX on x86-64 }
  603. RS_EAX:
  604. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  605. RS_ECX:
  606. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  607. RS_EDX:
  608. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  609. RS_EBX:
  610. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  611. RS_ESP:
  612. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  613. RS_EBP:
  614. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  615. RS_ESI:
  616. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  617. RS_EDI:
  618. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  619. else
  620. ;
  621. end;
  622. if result then
  623. exit;
  624. end
  625. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  626. begin
  627. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  628. exit(true);
  629. case getsubreg(reg) of
  630. R_SUBFLAGCARRY:
  631. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  632. R_SUBFLAGPARITY:
  633. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  634. R_SUBFLAGAUXILIARY:
  635. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  636. R_SUBFLAGZERO:
  637. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. R_SUBFLAGSIGN:
  639. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. R_SUBFLAGOVERFLOW:
  641. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. R_SUBFLAGINTERRUPT:
  643. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. R_SUBFLAGDIRECTION:
  645. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. else
  647. ;
  648. end;
  649. if result then
  650. exit;
  651. end
  652. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  653. exit(true);
  654. Result:=inherited RegInInstruction(Reg, p1);
  655. end;
  656. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  657. begin
  658. Result := False;
  659. if p1.typ <> ait_instruction then
  660. exit;
  661. with insprop[taicpu(p1).opcode] do
  662. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  663. begin
  664. case getsubreg(reg) of
  665. R_SUBW,R_SUBD,R_SUBQ:
  666. Result :=
  667. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  668. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  669. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  670. R_SUBFLAGCARRY:
  671. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  672. R_SUBFLAGPARITY:
  673. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  674. R_SUBFLAGAUXILIARY:
  675. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  676. R_SUBFLAGZERO:
  677. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  678. R_SUBFLAGSIGN:
  679. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  680. R_SUBFLAGOVERFLOW:
  681. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  682. R_SUBFLAGINTERRUPT:
  683. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  684. R_SUBFLAGDIRECTION:
  685. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  686. else
  687. internalerror(2017042602);
  688. end;
  689. exit;
  690. end;
  691. case taicpu(p1).opcode of
  692. A_CALL:
  693. { We could potentially set Result to False if the register in
  694. question is non-volatile for the subroutine's calling convention,
  695. but this would require detecting the calling convention in use and
  696. also assuming that the routine doesn't contain malformed assembly
  697. language, for example... so it could only be done under -O4 as it
  698. would be considered a side-effect. [Kit] }
  699. Result := True;
  700. A_MOVSD:
  701. { special handling for SSE MOVSD }
  702. if (taicpu(p1).ops>0) then
  703. begin
  704. if taicpu(p1).ops<>2 then
  705. internalerror(2017042703);
  706. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  707. end;
  708. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  709. so fix it here (FK)
  710. }
  711. A_VMOVSS,
  712. A_VMOVSD:
  713. begin
  714. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  715. exit;
  716. end;
  717. A_IMUL:
  718. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  719. else
  720. ;
  721. end;
  722. if Result then
  723. exit;
  724. with insprop[taicpu(p1).opcode] do
  725. begin
  726. if getregtype(reg)=R_INTREGISTER then
  727. begin
  728. case getsupreg(reg) of
  729. RS_EAX:
  730. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  731. begin
  732. Result := True;
  733. exit
  734. end;
  735. RS_ECX:
  736. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  737. begin
  738. Result := True;
  739. exit
  740. end;
  741. RS_EDX:
  742. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  743. begin
  744. Result := True;
  745. exit
  746. end;
  747. RS_EBX:
  748. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  749. begin
  750. Result := True;
  751. exit
  752. end;
  753. RS_ESP:
  754. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  755. begin
  756. Result := True;
  757. exit
  758. end;
  759. RS_EBP:
  760. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  761. begin
  762. Result := True;
  763. exit
  764. end;
  765. RS_ESI:
  766. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  767. begin
  768. Result := True;
  769. exit
  770. end;
  771. RS_EDI:
  772. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  773. begin
  774. Result := True;
  775. exit
  776. end;
  777. end;
  778. end;
  779. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  780. begin
  781. Result := true;
  782. exit
  783. end;
  784. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  785. begin
  786. Result := true;
  787. exit
  788. end;
  789. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  790. begin
  791. Result := true;
  792. exit
  793. end;
  794. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  795. begin
  796. Result := true;
  797. exit
  798. end;
  799. end;
  800. end;
  801. {$ifdef DEBUG_AOPTCPU}
  802. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  803. begin
  804. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  805. end;
  806. function debug_tostr(i: tcgint): string; inline;
  807. begin
  808. Result := tostr(i);
  809. end;
  810. function debug_regname(r: TRegister): string; inline;
  811. begin
  812. Result := '%' + std_regname(r);
  813. end;
  814. { Debug output function - creates a string representation of an operator }
  815. function debug_operstr(oper: TOper): string;
  816. begin
  817. case oper.typ of
  818. top_const:
  819. Result := '$' + debug_tostr(oper.val);
  820. top_reg:
  821. Result := debug_regname(oper.reg);
  822. top_ref:
  823. begin
  824. if oper.ref^.offset <> 0 then
  825. Result := debug_tostr(oper.ref^.offset) + '('
  826. else
  827. Result := '(';
  828. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  829. begin
  830. Result := Result + debug_regname(oper.ref^.base);
  831. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  832. Result := Result + ',' + debug_regname(oper.ref^.index);
  833. end
  834. else
  835. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  836. Result := Result + debug_regname(oper.ref^.index);
  837. if (oper.ref^.scalefactor > 1) then
  838. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  839. else
  840. Result := Result + ')';
  841. end;
  842. else
  843. Result := '[UNKNOWN]';
  844. end;
  845. end;
  846. function debug_op2str(opcode: tasmop): string; inline;
  847. begin
  848. Result := std_op2str[opcode];
  849. end;
  850. function debug_opsize2str(opsize: topsize): string; inline;
  851. begin
  852. Result := gas_opsize2str[opsize];
  853. end;
  854. {$else DEBUG_AOPTCPU}
  855. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  856. begin
  857. end;
  858. function debug_tostr(i: tcgint): string; inline;
  859. begin
  860. Result := '';
  861. end;
  862. function debug_regname(r: TRegister): string; inline;
  863. begin
  864. Result := '';
  865. end;
  866. function debug_operstr(oper: TOper): string; inline;
  867. begin
  868. Result := '';
  869. end;
  870. function debug_op2str(opcode: tasmop): string; inline;
  871. begin
  872. Result := '';
  873. end;
  874. function debug_opsize2str(opsize: topsize): string; inline;
  875. begin
  876. Result := '';
  877. end;
  878. {$endif DEBUG_AOPTCPU}
  879. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  880. begin
  881. {$ifdef x86_64}
  882. { Always fine on x86-64 }
  883. Result := True;
  884. {$else x86_64}
  885. Result :=
  886. {$ifdef i8086}
  887. (current_settings.cputype >= cpu_386) and
  888. {$endif i8086}
  889. (
  890. { Always accept if optimising for size }
  891. (cs_opt_size in current_settings.optimizerswitches) or
  892. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  893. (current_settings.optimizecputype >= cpu_Pentium2)
  894. );
  895. {$endif x86_64}
  896. end;
  897. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  898. begin
  899. if not SuperRegistersEqual(reg1,reg2) then
  900. exit(false);
  901. if getregtype(reg1)<>R_INTREGISTER then
  902. exit(true); {because SuperRegisterEqual is true}
  903. case getsubreg(reg1) of
  904. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  905. higher, it preserves the high bits, so the new value depends on
  906. reg2's previous value. In other words, it is equivalent to doing:
  907. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  908. R_SUBL:
  909. exit(getsubreg(reg2)=R_SUBL);
  910. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  911. higher, it actually does a:
  912. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  913. R_SUBH:
  914. exit(getsubreg(reg2)=R_SUBH);
  915. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  916. bits of reg2:
  917. reg2 := (reg2 and $ffff0000) or word(reg1); }
  918. R_SUBW:
  919. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  920. { a write to R_SUBD always overwrites every other subregister,
  921. because it clears the high 32 bits of R_SUBQ on x86_64 }
  922. R_SUBD,
  923. R_SUBQ:
  924. exit(true);
  925. else
  926. internalerror(2017042801);
  927. end;
  928. end;
  929. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  930. begin
  931. if not SuperRegistersEqual(reg1,reg2) then
  932. exit(false);
  933. if getregtype(reg1)<>R_INTREGISTER then
  934. exit(true); {because SuperRegisterEqual is true}
  935. case getsubreg(reg1) of
  936. R_SUBL:
  937. exit(getsubreg(reg2)<>R_SUBH);
  938. R_SUBH:
  939. exit(getsubreg(reg2)<>R_SUBL);
  940. R_SUBW,
  941. R_SUBD,
  942. R_SUBQ:
  943. exit(true);
  944. else
  945. internalerror(2017042802);
  946. end;
  947. end;
  948. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  949. var
  950. hp1 : tai;
  951. l : TCGInt;
  952. begin
  953. result:=false;
  954. { changes the code sequence
  955. shr/sar const1, x
  956. shl const2, x
  957. to
  958. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  959. if GetNextInstruction(p, hp1) and
  960. MatchInstruction(hp1,A_SHL,[]) and
  961. (taicpu(p).oper[0]^.typ = top_const) and
  962. (taicpu(hp1).oper[0]^.typ = top_const) and
  963. (taicpu(hp1).opsize = taicpu(p).opsize) and
  964. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  965. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  966. begin
  967. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  968. not(cs_opt_size in current_settings.optimizerswitches) then
  969. begin
  970. { shr/sar const1, %reg
  971. shl const2, %reg
  972. with const1 > const2 }
  973. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  974. taicpu(hp1).opcode := A_AND;
  975. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  976. case taicpu(p).opsize Of
  977. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  978. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  979. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  980. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  981. else
  982. Internalerror(2017050703)
  983. end;
  984. end
  985. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  986. not(cs_opt_size in current_settings.optimizerswitches) then
  987. begin
  988. { shr/sar const1, %reg
  989. shl const2, %reg
  990. with const1 < const2 }
  991. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  992. taicpu(p).opcode := A_AND;
  993. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  994. case taicpu(p).opsize Of
  995. S_B: taicpu(p).loadConst(0,l Xor $ff);
  996. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  997. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  998. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  999. else
  1000. Internalerror(2017050702)
  1001. end;
  1002. end
  1003. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1004. begin
  1005. { shr/sar const1, %reg
  1006. shl const2, %reg
  1007. with const1 = const2 }
  1008. taicpu(p).opcode := A_AND;
  1009. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1010. case taicpu(p).opsize Of
  1011. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1012. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1013. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1014. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1015. else
  1016. Internalerror(2017050701)
  1017. end;
  1018. RemoveInstruction(hp1);
  1019. end;
  1020. end;
  1021. end;
  1022. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1023. var
  1024. opsize : topsize;
  1025. hp1 : tai;
  1026. tmpref : treference;
  1027. ShiftValue : Cardinal;
  1028. BaseValue : TCGInt;
  1029. begin
  1030. result:=false;
  1031. opsize:=taicpu(p).opsize;
  1032. { changes certain "imul const, %reg"'s to lea sequences }
  1033. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1034. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1035. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1036. if (taicpu(p).oper[0]^.val = 1) then
  1037. if (taicpu(p).ops = 2) then
  1038. { remove "imul $1, reg" }
  1039. begin
  1040. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1041. Result := RemoveCurrentP(p);
  1042. end
  1043. else
  1044. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1045. begin
  1046. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1047. InsertLLItem(p.previous, p.next, hp1);
  1048. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1049. p.free;
  1050. p := hp1;
  1051. end
  1052. else if ((taicpu(p).ops <= 2) or
  1053. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1054. not(cs_opt_size in current_settings.optimizerswitches) and
  1055. (not(GetNextInstruction(p, hp1)) or
  1056. not((tai(hp1).typ = ait_instruction) and
  1057. ((taicpu(hp1).opcode=A_Jcc) and
  1058. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1059. begin
  1060. {
  1061. imul X, reg1, reg2 to
  1062. lea (reg1,reg1,Y), reg2
  1063. shl ZZ,reg2
  1064. imul XX, reg1 to
  1065. lea (reg1,reg1,YY), reg1
  1066. shl ZZ,reg2
  1067. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1068. it does not exist as a separate optimization target in FPC though.
  1069. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1070. at most two zeros
  1071. }
  1072. reference_reset(tmpref,1,[]);
  1073. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1074. begin
  1075. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1076. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1077. TmpRef.base := taicpu(p).oper[1]^.reg;
  1078. TmpRef.index := taicpu(p).oper[1]^.reg;
  1079. if not(BaseValue in [3,5,9]) then
  1080. Internalerror(2018110101);
  1081. TmpRef.ScaleFactor := BaseValue-1;
  1082. if (taicpu(p).ops = 2) then
  1083. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1084. else
  1085. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1086. AsmL.InsertAfter(hp1,p);
  1087. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1088. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1089. RemoveCurrentP(p, hp1);
  1090. if ShiftValue>0 then
  1091. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1092. end;
  1093. end;
  1094. end;
  1095. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1096. var
  1097. p: taicpu;
  1098. begin
  1099. if not assigned(hp) or
  1100. (hp.typ <> ait_instruction) then
  1101. begin
  1102. Result := false;
  1103. exit;
  1104. end;
  1105. p := taicpu(hp);
  1106. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1107. with insprop[p.opcode] do
  1108. begin
  1109. case getsubreg(reg) of
  1110. R_SUBW,R_SUBD,R_SUBQ:
  1111. Result:=
  1112. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1113. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1114. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1115. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1116. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1117. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1118. R_SUBFLAGCARRY:
  1119. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1120. R_SUBFLAGPARITY:
  1121. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1122. R_SUBFLAGAUXILIARY:
  1123. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1124. R_SUBFLAGZERO:
  1125. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1126. R_SUBFLAGSIGN:
  1127. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1128. R_SUBFLAGOVERFLOW:
  1129. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1130. R_SUBFLAGINTERRUPT:
  1131. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1132. R_SUBFLAGDIRECTION:
  1133. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1134. else
  1135. begin
  1136. writeln(getsubreg(reg));
  1137. internalerror(2017050501);
  1138. end;
  1139. end;
  1140. exit;
  1141. end;
  1142. Result :=
  1143. (((p.opcode = A_MOV) or
  1144. (p.opcode = A_MOVZX) or
  1145. (p.opcode = A_MOVSX) or
  1146. (p.opcode = A_LEA) or
  1147. (p.opcode = A_VMOVSS) or
  1148. (p.opcode = A_VMOVSD) or
  1149. (p.opcode = A_VMOVAPD) or
  1150. (p.opcode = A_VMOVAPS) or
  1151. (p.opcode = A_VMOVQ) or
  1152. (p.opcode = A_MOVSS) or
  1153. (p.opcode = A_MOVSD) or
  1154. (p.opcode = A_MOVQ) or
  1155. (p.opcode = A_MOVAPD) or
  1156. (p.opcode = A_MOVAPS) or
  1157. {$ifndef x86_64}
  1158. (p.opcode = A_LDS) or
  1159. (p.opcode = A_LES) or
  1160. {$endif not x86_64}
  1161. (p.opcode = A_LFS) or
  1162. (p.opcode = A_LGS) or
  1163. (p.opcode = A_LSS)) and
  1164. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1165. (p.oper[1]^.typ = top_reg) and
  1166. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1167. ((p.oper[0]^.typ = top_const) or
  1168. ((p.oper[0]^.typ = top_reg) and
  1169. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1170. ((p.oper[0]^.typ = top_ref) and
  1171. not RegInRef(reg,p.oper[0]^.ref^)))) or
  1172. ((p.opcode = A_POP) and
  1173. (Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg))) or
  1174. ((p.opcode = A_IMUL) and
  1175. (p.ops=3) and
  1176. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1177. (((p.oper[1]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg))) or
  1178. ((p.oper[1]^.typ=top_ref) and not(RegInRef(reg,p.oper[1]^.ref^))))) or
  1179. ((((p.opcode = A_IMUL) or
  1180. (p.opcode = A_MUL)) and
  1181. (p.ops=1)) and
  1182. (((p.oper[0]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1183. ((p.oper[0]^.typ=top_ref) and not(RegInRef(reg,p.oper[0]^.ref^)))) and
  1184. (((p.opsize=S_B) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1185. ((p.opsize=S_W) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1186. ((p.opsize=S_L) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg))
  1187. {$ifdef x86_64}
  1188. or ((p.opsize=S_Q) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg))
  1189. {$endif x86_64}
  1190. )) or
  1191. ((p.opcode = A_CWD) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1192. ((p.opcode = A_CDQ) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)) or
  1193. {$ifdef x86_64}
  1194. ((p.opcode = A_CQO) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)) or
  1195. {$endif x86_64}
  1196. ((p.opcode = A_CBW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1197. {$ifndef x86_64}
  1198. ((p.opcode = A_LDS) and (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1199. ((p.opcode = A_LES) and (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1200. {$endif not x86_64}
  1201. ((p.opcode = A_LFS) and (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1202. ((p.opcode = A_LGS) and (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1203. ((p.opcode = A_LSS) and (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1204. {$ifndef x86_64}
  1205. ((p.opcode = A_AAM) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1206. {$endif not x86_64}
  1207. ((p.opcode = A_LAHF) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1208. ((p.opcode = A_LODSB) and Reg1WriteOverwritesReg2Entirely(NR_AL,reg)) or
  1209. ((p.opcode = A_LODSW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg)) or
  1210. ((p.opcode = A_LODSD) and Reg1WriteOverwritesReg2Entirely(NR_EAX,reg)) or
  1211. {$ifdef x86_64}
  1212. ((p.opcode = A_LODSQ) and Reg1WriteOverwritesReg2Entirely(NR_RAX,reg)) or
  1213. {$endif x86_64}
  1214. ((p.opcode = A_SETcc) and (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1215. (((p.opcode = A_FSTSW) or
  1216. (p.opcode = A_FNSTSW)) and
  1217. (p.oper[0]^.typ=top_reg) and
  1218. Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1219. (((p.opcode = A_SHRX) or (p.opcode = A_SHLX)) and
  1220. (p.ops=3) and
  1221. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1222. (((p.oper[1]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg))) or
  1223. ((p.oper[1]^.typ=top_ref) and not(RegInRef(reg,p.oper[1]^.ref^)))) and
  1224. (((p.oper[0]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1225. ((p.oper[0]^.typ=top_ref) and not(RegInRef(reg,p.oper[0]^.ref^))))) or
  1226. (((p.opcode = A_XOR) or (p.opcode = A_SUB) or (p.opcode = A_SBB)) and
  1227. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  1228. (p.oper[0]^.reg=p.oper[1]^.reg) and
  1229. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg));
  1230. end;
  1231. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1232. var
  1233. hp2,hp3 : tai;
  1234. begin
  1235. { some x86-64 issue a NOP before the real exit code }
  1236. if MatchInstruction(p,A_NOP,[]) then
  1237. GetNextInstruction(p,p);
  1238. result:=assigned(p) and (p.typ=ait_instruction) and
  1239. ((taicpu(p).opcode = A_RET) or
  1240. ((taicpu(p).opcode=A_LEAVE) and
  1241. GetNextInstruction(p,hp2) and
  1242. MatchInstruction(hp2,A_RET,[S_NO])
  1243. ) or
  1244. (((taicpu(p).opcode=A_LEA) and
  1245. MatchOpType(taicpu(p),top_ref,top_reg) and
  1246. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1247. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1248. ) and
  1249. GetNextInstruction(p,hp2) and
  1250. MatchInstruction(hp2,A_RET,[S_NO])
  1251. ) or
  1252. ((((taicpu(p).opcode=A_MOV) and
  1253. MatchOpType(taicpu(p),top_reg,top_reg) and
  1254. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1255. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1256. ((taicpu(p).opcode=A_LEA) and
  1257. MatchOpType(taicpu(p),top_ref,top_reg) and
  1258. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1259. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1260. )
  1261. ) and
  1262. GetNextInstruction(p,hp2) and
  1263. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1264. MatchOpType(taicpu(hp2),top_reg) and
  1265. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1266. GetNextInstruction(hp2,hp3) and
  1267. MatchInstruction(hp3,A_RET,[S_NO])
  1268. )
  1269. );
  1270. end;
  1271. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1272. begin
  1273. isFoldableArithOp := False;
  1274. case hp1.opcode of
  1275. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1276. isFoldableArithOp :=
  1277. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1278. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1279. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1280. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1281. (taicpu(hp1).oper[1]^.reg = reg);
  1282. A_INC,A_DEC,A_NEG,A_NOT:
  1283. isFoldableArithOp :=
  1284. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1285. (taicpu(hp1).oper[0]^.reg = reg);
  1286. else
  1287. ;
  1288. end;
  1289. end;
  1290. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1291. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1292. var
  1293. hp2: tai;
  1294. begin
  1295. hp2 := p;
  1296. repeat
  1297. hp2 := tai(hp2.previous);
  1298. if assigned(hp2) and
  1299. (hp2.typ = ait_regalloc) and
  1300. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1301. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1302. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1303. begin
  1304. RemoveInstruction(hp2);
  1305. break;
  1306. end;
  1307. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1308. end;
  1309. begin
  1310. case current_procinfo.procdef.returndef.typ of
  1311. arraydef,recorddef,pointerdef,
  1312. stringdef,enumdef,procdef,objectdef,errordef,
  1313. filedef,setdef,procvardef,
  1314. classrefdef,forwarddef:
  1315. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1316. orddef:
  1317. if current_procinfo.procdef.returndef.size <> 0 then
  1318. begin
  1319. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1320. { for int64/qword }
  1321. if current_procinfo.procdef.returndef.size = 8 then
  1322. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1323. end;
  1324. else
  1325. ;
  1326. end;
  1327. end;
  1328. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1329. var
  1330. hp1,hp2 : tai;
  1331. begin
  1332. result:=false;
  1333. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1334. begin
  1335. { vmova* reg1,reg1
  1336. =>
  1337. <nop> }
  1338. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1339. begin
  1340. RemoveCurrentP(p);
  1341. result:=true;
  1342. exit;
  1343. end
  1344. else if GetNextInstruction(p,hp1) then
  1345. begin
  1346. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1347. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1348. begin
  1349. { vmova* reg1,reg2
  1350. vmova* reg2,reg3
  1351. dealloc reg2
  1352. =>
  1353. vmova* reg1,reg3 }
  1354. TransferUsedRegs(TmpUsedRegs);
  1355. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1356. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1357. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1358. begin
  1359. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1360. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1361. RemoveInstruction(hp1);
  1362. result:=true;
  1363. exit;
  1364. end
  1365. { special case:
  1366. vmova* reg1,<op>
  1367. vmova* <op>,reg1
  1368. =>
  1369. vmova* reg1,<op> }
  1370. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1371. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1372. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1373. ) then
  1374. begin
  1375. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1376. RemoveInstruction(hp1);
  1377. result:=true;
  1378. exit;
  1379. end
  1380. end
  1381. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1382. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1383. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1384. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1385. ) and
  1386. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1387. begin
  1388. { vmova* reg1,reg2
  1389. vmovs* reg2,<op>
  1390. dealloc reg2
  1391. =>
  1392. vmovs* reg1,reg3 }
  1393. TransferUsedRegs(TmpUsedRegs);
  1394. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1395. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1396. begin
  1397. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1398. taicpu(p).opcode:=taicpu(hp1).opcode;
  1399. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1400. RemoveInstruction(hp1);
  1401. result:=true;
  1402. exit;
  1403. end
  1404. end;
  1405. end;
  1406. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1407. begin
  1408. if MatchInstruction(hp1,[A_VFMADDPD,
  1409. A_VFMADD132PD,
  1410. A_VFMADD132PS,
  1411. A_VFMADD132SD,
  1412. A_VFMADD132SS,
  1413. A_VFMADD213PD,
  1414. A_VFMADD213PS,
  1415. A_VFMADD213SD,
  1416. A_VFMADD213SS,
  1417. A_VFMADD231PD,
  1418. A_VFMADD231PS,
  1419. A_VFMADD231SD,
  1420. A_VFMADD231SS,
  1421. A_VFMADDSUB132PD,
  1422. A_VFMADDSUB132PS,
  1423. A_VFMADDSUB213PD,
  1424. A_VFMADDSUB213PS,
  1425. A_VFMADDSUB231PD,
  1426. A_VFMADDSUB231PS,
  1427. A_VFMSUB132PD,
  1428. A_VFMSUB132PS,
  1429. A_VFMSUB132SD,
  1430. A_VFMSUB132SS,
  1431. A_VFMSUB213PD,
  1432. A_VFMSUB213PS,
  1433. A_VFMSUB213SD,
  1434. A_VFMSUB213SS,
  1435. A_VFMSUB231PD,
  1436. A_VFMSUB231PS,
  1437. A_VFMSUB231SD,
  1438. A_VFMSUB231SS,
  1439. A_VFMSUBADD132PD,
  1440. A_VFMSUBADD132PS,
  1441. A_VFMSUBADD213PD,
  1442. A_VFMSUBADD213PS,
  1443. A_VFMSUBADD231PD,
  1444. A_VFMSUBADD231PS,
  1445. A_VFNMADD132PD,
  1446. A_VFNMADD132PS,
  1447. A_VFNMADD132SD,
  1448. A_VFNMADD132SS,
  1449. A_VFNMADD213PD,
  1450. A_VFNMADD213PS,
  1451. A_VFNMADD213SD,
  1452. A_VFNMADD213SS,
  1453. A_VFNMADD231PD,
  1454. A_VFNMADD231PS,
  1455. A_VFNMADD231SD,
  1456. A_VFNMADD231SS,
  1457. A_VFNMSUB132PD,
  1458. A_VFNMSUB132PS,
  1459. A_VFNMSUB132SD,
  1460. A_VFNMSUB132SS,
  1461. A_VFNMSUB213PD,
  1462. A_VFNMSUB213PS,
  1463. A_VFNMSUB213SD,
  1464. A_VFNMSUB213SS,
  1465. A_VFNMSUB231PD,
  1466. A_VFNMSUB231PS,
  1467. A_VFNMSUB231SD,
  1468. A_VFNMSUB231SS],[S_NO]) and
  1469. { we mix single and double opperations here because we assume that the compiler
  1470. generates vmovapd only after double operations and vmovaps only after single operations }
  1471. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1472. GetNextInstruction(hp1,hp2) and
  1473. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1474. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1475. begin
  1476. TransferUsedRegs(TmpUsedRegs);
  1477. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1478. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1479. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1480. begin
  1481. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1482. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1483. RemoveInstruction(hp2);
  1484. end;
  1485. end
  1486. else if (hp1.typ = ait_instruction) and
  1487. GetNextInstruction(hp1, hp2) and
  1488. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1489. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1490. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1491. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1492. (((taicpu(p).opcode=A_MOVAPS) and
  1493. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1494. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1495. ((taicpu(p).opcode=A_MOVAPD) and
  1496. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1497. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1498. ) then
  1499. { change
  1500. movapX reg,reg2
  1501. addsX/subsX/... reg3, reg2
  1502. movapX reg2,reg
  1503. to
  1504. addsX/subsX/... reg3,reg
  1505. }
  1506. begin
  1507. TransferUsedRegs(TmpUsedRegs);
  1508. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1509. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1510. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1511. begin
  1512. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1513. debug_op2str(taicpu(p).opcode)+' '+
  1514. debug_op2str(taicpu(hp1).opcode)+' '+
  1515. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1516. { we cannot eliminate the first move if
  1517. the operations uses the same register for source and dest }
  1518. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1519. RemoveCurrentP(p, nil);
  1520. p:=hp1;
  1521. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1522. RemoveInstruction(hp2);
  1523. result:=true;
  1524. end;
  1525. end;
  1526. end;
  1527. end;
  1528. end;
  1529. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1530. var
  1531. hp1 : tai;
  1532. begin
  1533. result:=false;
  1534. { replace
  1535. V<Op>X %mreg1,%mreg2,%mreg3
  1536. VMovX %mreg3,%mreg4
  1537. dealloc %mreg3
  1538. by
  1539. V<Op>X %mreg1,%mreg2,%mreg4
  1540. ?
  1541. }
  1542. if GetNextInstruction(p,hp1) and
  1543. { we mix single and double operations here because we assume that the compiler
  1544. generates vmovapd only after double operations and vmovaps only after single operations }
  1545. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1546. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1547. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1548. begin
  1549. TransferUsedRegs(TmpUsedRegs);
  1550. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1551. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1552. begin
  1553. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1554. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1555. RemoveInstruction(hp1);
  1556. result:=true;
  1557. end;
  1558. end;
  1559. end;
  1560. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1561. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1562. begin
  1563. Result := False;
  1564. { For safety reasons, only check for exact register matches }
  1565. { Check base register }
  1566. if (ref.base = AOldReg) then
  1567. begin
  1568. ref.base := ANewReg;
  1569. Result := True;
  1570. end;
  1571. { Check index register }
  1572. if (ref.index = AOldReg) then
  1573. begin
  1574. ref.index := ANewReg;
  1575. Result := True;
  1576. end;
  1577. end;
  1578. { Replaces all references to AOldReg in an operand to ANewReg }
  1579. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1580. var
  1581. OldSupReg, NewSupReg: TSuperRegister;
  1582. OldSubReg, NewSubReg: TSubRegister;
  1583. OldRegType: TRegisterType;
  1584. ThisOper: POper;
  1585. begin
  1586. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1587. Result := False;
  1588. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1589. InternalError(2020011801);
  1590. OldSupReg := getsupreg(AOldReg);
  1591. OldSubReg := getsubreg(AOldReg);
  1592. OldRegType := getregtype(AOldReg);
  1593. NewSupReg := getsupreg(ANewReg);
  1594. NewSubReg := getsubreg(ANewReg);
  1595. if OldRegType <> getregtype(ANewReg) then
  1596. InternalError(2020011802);
  1597. if OldSubReg <> NewSubReg then
  1598. InternalError(2020011803);
  1599. case ThisOper^.typ of
  1600. top_reg:
  1601. if (
  1602. (ThisOper^.reg = AOldReg) or
  1603. (
  1604. (OldRegType = R_INTREGISTER) and
  1605. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1606. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1607. (
  1608. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1609. {$ifndef x86_64}
  1610. and (
  1611. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1612. don't have an 8-bit representation }
  1613. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1614. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1615. )
  1616. {$endif x86_64}
  1617. )
  1618. )
  1619. ) then
  1620. begin
  1621. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1622. Result := True;
  1623. end;
  1624. top_ref:
  1625. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1626. Result := True;
  1627. else
  1628. ;
  1629. end;
  1630. end;
  1631. { Replaces all references to AOldReg in an instruction to ANewReg }
  1632. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1633. const
  1634. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1635. var
  1636. OperIdx: Integer;
  1637. begin
  1638. Result := False;
  1639. for OperIdx := 0 to p.ops - 1 do
  1640. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1641. { The shift and rotate instructions can only use CL }
  1642. not (
  1643. (OperIdx = 0) and
  1644. { This second condition just helps to avoid unnecessarily
  1645. calling MatchInstruction for 10 different opcodes }
  1646. (p.oper[0]^.reg = NR_CL) and
  1647. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1648. ) then
  1649. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1650. end;
  1651. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1652. begin
  1653. Result :=
  1654. (ref^.index = NR_NO) and
  1655. (
  1656. {$ifdef x86_64}
  1657. (
  1658. (ref^.base = NR_RIP) and
  1659. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1660. ) or
  1661. {$endif x86_64}
  1662. (ref^.base = NR_STACK_POINTER_REG) or
  1663. (ref^.base = current_procinfo.framepointer)
  1664. );
  1665. end;
  1666. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1667. var
  1668. l: asizeint;
  1669. begin
  1670. Result := False;
  1671. { Should have been checked previously }
  1672. if p.opcode <> A_LEA then
  1673. InternalError(2020072501);
  1674. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1675. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1676. not(cs_opt_size in current_settings.optimizerswitches) then
  1677. exit;
  1678. with p.oper[0]^.ref^ do
  1679. begin
  1680. if (base <> p.oper[1]^.reg) or
  1681. (index <> NR_NO) or
  1682. assigned(symbol) then
  1683. exit;
  1684. l:=offset;
  1685. if (l=1) and UseIncDec then
  1686. begin
  1687. p.opcode:=A_INC;
  1688. p.loadreg(0,p.oper[1]^.reg);
  1689. p.ops:=1;
  1690. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1691. end
  1692. else if (l=-1) and UseIncDec then
  1693. begin
  1694. p.opcode:=A_DEC;
  1695. p.loadreg(0,p.oper[1]^.reg);
  1696. p.ops:=1;
  1697. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1698. end
  1699. else
  1700. begin
  1701. if (l<0) and (l<>-2147483648) then
  1702. begin
  1703. p.opcode:=A_SUB;
  1704. p.loadConst(0,-l);
  1705. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1706. end
  1707. else
  1708. begin
  1709. p.opcode:=A_ADD;
  1710. p.loadConst(0,l);
  1711. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1712. end;
  1713. end;
  1714. end;
  1715. Result := True;
  1716. end;
  1717. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1718. var
  1719. CurrentReg, ReplaceReg: TRegister;
  1720. begin
  1721. Result := False;
  1722. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1723. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1724. case hp.opcode of
  1725. A_FSTSW, A_FNSTSW,
  1726. A_IN, A_INS, A_OUT, A_OUTS,
  1727. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1728. { These routines have explicit operands, but they are restricted in
  1729. what they can be (e.g. IN and OUT can only read from AL, AX or
  1730. EAX. }
  1731. Exit;
  1732. A_IMUL:
  1733. begin
  1734. { The 1-operand version writes to implicit registers
  1735. The 2-operand version reads from the first operator, and reads
  1736. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1737. the 3-operand version reads from a register that it doesn't write to
  1738. }
  1739. case hp.ops of
  1740. 1:
  1741. if (
  1742. (
  1743. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1744. ) or
  1745. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1746. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1747. begin
  1748. Result := True;
  1749. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1750. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1751. end;
  1752. 2:
  1753. { Only modify the first parameter }
  1754. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1755. begin
  1756. Result := True;
  1757. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1758. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1759. end;
  1760. 3:
  1761. { Only modify the second parameter }
  1762. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1763. begin
  1764. Result := True;
  1765. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1766. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1767. end;
  1768. else
  1769. InternalError(2020012901);
  1770. end;
  1771. end;
  1772. else
  1773. if (hp.ops > 0) and
  1774. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1775. begin
  1776. Result := True;
  1777. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1778. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1779. end;
  1780. end;
  1781. end;
  1782. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  1783. var
  1784. hp1, hp2, hp3: tai;
  1785. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  1786. begin
  1787. if taicpu(hp1).opcode = signed_movop then
  1788. begin
  1789. if taicpu(p).oper[0]^.val > max_value shr 1 then
  1790. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  1791. end
  1792. else
  1793. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  1794. end;
  1795. var
  1796. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  1797. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  1798. NewSize: topsize;
  1799. CurrentReg: TRegister;
  1800. begin
  1801. Result:=false;
  1802. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  1803. { remove mov reg1,reg1? }
  1804. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  1805. then
  1806. begin
  1807. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  1808. { take care of the register (de)allocs following p }
  1809. RemoveCurrentP(p, hp1);
  1810. Result:=true;
  1811. exit;
  1812. end;
  1813. { All the next optimisations require a next instruction }
  1814. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  1815. Exit;
  1816. { Look for:
  1817. mov %reg1,%reg2
  1818. ??? %reg2,r/m
  1819. Change to:
  1820. mov %reg1,%reg2
  1821. ??? %reg1,r/m
  1822. }
  1823. if MatchOpType(taicpu(p), top_reg, top_reg) then
  1824. begin
  1825. CurrentReg := taicpu(p).oper[1]^.reg;
  1826. if RegReadByInstruction(CurrentReg, hp1) and
  1827. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  1828. begin
  1829. TransferUsedRegs(TmpUsedRegs);
  1830. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  1831. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  1832. { Just in case something didn't get modified (e.g. an
  1833. implicit register) }
  1834. not RegReadByInstruction(CurrentReg, hp1) then
  1835. begin
  1836. { We can remove the original MOV }
  1837. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  1838. RemoveCurrentp(p, hp1);
  1839. { UsedRegs got updated by RemoveCurrentp }
  1840. Result := True;
  1841. Exit;
  1842. end;
  1843. { If we know a MOV instruction has become a null operation, we might as well
  1844. get rid of it now to save time. }
  1845. if (taicpu(hp1).opcode = A_MOV) and
  1846. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1847. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  1848. { Just being a register is enough to confirm it's a null operation }
  1849. (taicpu(hp1).oper[0]^.typ = top_reg) then
  1850. begin
  1851. Result := True;
  1852. { Speed-up to reduce a pipeline stall... if we had something like...
  1853. movl %eax,%edx
  1854. movw %dx,%ax
  1855. ... the second instruction would change to movw %ax,%ax, but
  1856. given that it is now %ax that's active rather than %eax,
  1857. penalties might occur due to a partial register write, so instead,
  1858. change it to a MOVZX instruction when optimising for speed.
  1859. }
  1860. if not (cs_opt_size in current_settings.optimizerswitches) and
  1861. IsMOVZXAcceptable and
  1862. (taicpu(hp1).opsize < taicpu(p).opsize)
  1863. {$ifdef x86_64}
  1864. { operations already implicitly set the upper 64 bits to zero }
  1865. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  1866. {$endif x86_64}
  1867. then
  1868. begin
  1869. CurrentReg := taicpu(hp1).oper[1]^.reg;
  1870. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  1871. case taicpu(p).opsize of
  1872. S_W:
  1873. if taicpu(hp1).opsize = S_B then
  1874. taicpu(hp1).opsize := S_BL
  1875. else
  1876. InternalError(2020012911);
  1877. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  1878. case taicpu(hp1).opsize of
  1879. S_B:
  1880. taicpu(hp1).opsize := S_BL;
  1881. S_W:
  1882. taicpu(hp1).opsize := S_WL;
  1883. else
  1884. InternalError(2020012912);
  1885. end;
  1886. else
  1887. InternalError(2020012910);
  1888. end;
  1889. taicpu(hp1).opcode := A_MOVZX;
  1890. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  1891. end
  1892. else
  1893. begin
  1894. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  1895. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  1896. RemoveInstruction(hp1);
  1897. { The instruction after what was hp1 is now the immediate next instruction,
  1898. so we can continue to make optimisations if it's present }
  1899. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  1900. Exit;
  1901. hp1 := hp2;
  1902. end;
  1903. end;
  1904. end;
  1905. end;
  1906. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  1907. overwrites the original destination register. e.g.
  1908. movl ###,%reg2d
  1909. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  1910. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  1911. }
  1912. if (taicpu(p).oper[1]^.typ = top_reg) and
  1913. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  1914. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1915. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  1916. begin
  1917. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  1918. begin
  1919. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  1920. case taicpu(p).oper[0]^.typ of
  1921. top_const:
  1922. { We have something like:
  1923. movb $x, %regb
  1924. movzbl %regb,%regd
  1925. Change to:
  1926. movl $x, %regd
  1927. }
  1928. begin
  1929. case taicpu(hp1).opsize of
  1930. S_BW:
  1931. begin
  1932. convert_mov_value(A_MOVSX, $FF);
  1933. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  1934. taicpu(p).opsize := S_W;
  1935. end;
  1936. S_BL:
  1937. begin
  1938. convert_mov_value(A_MOVSX, $FF);
  1939. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1940. taicpu(p).opsize := S_L;
  1941. end;
  1942. S_WL:
  1943. begin
  1944. convert_mov_value(A_MOVSX, $FFFF);
  1945. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1946. taicpu(p).opsize := S_L;
  1947. end;
  1948. {$ifdef x86_64}
  1949. S_BQ:
  1950. begin
  1951. convert_mov_value(A_MOVSX, $FF);
  1952. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1953. taicpu(p).opsize := S_Q;
  1954. end;
  1955. S_WQ:
  1956. begin
  1957. convert_mov_value(A_MOVSX, $FFFF);
  1958. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1959. taicpu(p).opsize := S_Q;
  1960. end;
  1961. S_LQ:
  1962. begin
  1963. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  1964. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1965. taicpu(p).opsize := S_Q;
  1966. end;
  1967. {$endif x86_64}
  1968. else
  1969. { If hp1 was a MOV instruction, it should have been
  1970. optimised already }
  1971. InternalError(2020021001);
  1972. end;
  1973. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  1974. RemoveInstruction(hp1);
  1975. Result := True;
  1976. Exit;
  1977. end;
  1978. top_ref:
  1979. { We have something like:
  1980. movb mem, %regb
  1981. movzbl %regb,%regd
  1982. Change to:
  1983. movzbl mem, %regd
  1984. }
  1985. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  1986. begin
  1987. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  1988. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  1989. RemoveCurrentP(p, hp1);
  1990. Result:=True;
  1991. Exit;
  1992. end;
  1993. else
  1994. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  1995. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  1996. Exit;
  1997. end;
  1998. end
  1999. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2000. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2001. optimised }
  2002. else
  2003. begin
  2004. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2005. RemoveCurrentP(p, hp1);
  2006. Result := True;
  2007. Exit;
  2008. end;
  2009. end;
  2010. if (taicpu(hp1).opcode = A_AND) and
  2011. (taicpu(p).oper[1]^.typ = top_reg) and
  2012. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2013. begin
  2014. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2015. begin
  2016. case taicpu(p).opsize of
  2017. S_L:
  2018. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2019. begin
  2020. { Optimize out:
  2021. mov x, %reg
  2022. and ffffffffh, %reg
  2023. }
  2024. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2025. RemoveInstruction(hp1);
  2026. Result:=true;
  2027. exit;
  2028. end;
  2029. S_Q: { TODO: Confirm if this is even possible }
  2030. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2031. begin
  2032. { Optimize out:
  2033. mov x, %reg
  2034. and ffffffffffffffffh, %reg
  2035. }
  2036. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2037. RemoveInstruction(hp1);
  2038. Result:=true;
  2039. exit;
  2040. end;
  2041. else
  2042. ;
  2043. end;
  2044. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2045. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2046. GetNextInstruction(hp1,hp2) and
  2047. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2048. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2049. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) and
  2050. GetNextInstruction(hp2,hp3) and
  2051. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2052. (taicpu(hp3).condition in [C_E,C_NE]) then
  2053. begin
  2054. TransferUsedRegs(TmpUsedRegs);
  2055. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2056. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2057. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2058. begin
  2059. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2060. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2061. taicpu(hp1).opcode:=A_TEST;
  2062. RemoveInstruction(hp2);
  2063. RemoveCurrentP(p, hp1);
  2064. Result:=true;
  2065. exit;
  2066. end;
  2067. end;
  2068. end
  2069. else if IsMOVZXAcceptable and
  2070. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2071. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2072. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2073. then
  2074. begin
  2075. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2076. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2077. case taicpu(p).opsize of
  2078. S_B:
  2079. if (taicpu(hp1).oper[0]^.val = $ff) then
  2080. begin
  2081. { Convert:
  2082. movb x, %regl movb x, %regl
  2083. andw ffh, %regw andl ffh, %regd
  2084. To:
  2085. movzbw x, %regd movzbl x, %regd
  2086. (Identical registers, just different sizes)
  2087. }
  2088. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2089. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2090. case taicpu(hp1).opsize of
  2091. S_W: NewSize := S_BW;
  2092. S_L: NewSize := S_BL;
  2093. {$ifdef x86_64}
  2094. S_Q: NewSize := S_BQ;
  2095. {$endif x86_64}
  2096. else
  2097. InternalError(2018011510);
  2098. end;
  2099. end
  2100. else
  2101. NewSize := S_NO;
  2102. S_W:
  2103. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2104. begin
  2105. { Convert:
  2106. movw x, %regw
  2107. andl ffffh, %regd
  2108. To:
  2109. movzwl x, %regd
  2110. (Identical registers, just different sizes)
  2111. }
  2112. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2113. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2114. case taicpu(hp1).opsize of
  2115. S_L: NewSize := S_WL;
  2116. {$ifdef x86_64}
  2117. S_Q: NewSize := S_WQ;
  2118. {$endif x86_64}
  2119. else
  2120. InternalError(2018011511);
  2121. end;
  2122. end
  2123. else
  2124. NewSize := S_NO;
  2125. else
  2126. NewSize := S_NO;
  2127. end;
  2128. if NewSize <> S_NO then
  2129. begin
  2130. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2131. { The actual optimization }
  2132. taicpu(p).opcode := A_MOVZX;
  2133. taicpu(p).changeopsize(NewSize);
  2134. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2135. { Safeguard if "and" is followed by a conditional command }
  2136. TransferUsedRegs(TmpUsedRegs);
  2137. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2138. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2139. begin
  2140. { At this point, the "and" command is effectively equivalent to
  2141. "test %reg,%reg". This will be handled separately by the
  2142. Peephole Optimizer. [Kit] }
  2143. DebugMsg(SPeepholeOptimization + PreMessage +
  2144. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2145. end
  2146. else
  2147. begin
  2148. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2149. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2150. RemoveInstruction(hp1);
  2151. end;
  2152. Result := True;
  2153. Exit;
  2154. end;
  2155. end;
  2156. end;
  2157. { Next instruction is also a MOV ? }
  2158. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2159. begin
  2160. if (taicpu(p).oper[1]^.typ = top_reg) and
  2161. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2162. begin
  2163. CurrentReg := taicpu(p).oper[1]^.reg;
  2164. TransferUsedRegs(TmpUsedRegs);
  2165. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2166. { we have
  2167. mov x, %treg
  2168. mov %treg, y
  2169. }
  2170. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2171. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2172. { we've got
  2173. mov x, %treg
  2174. mov %treg, y
  2175. with %treg is not used after }
  2176. case taicpu(p).oper[0]^.typ Of
  2177. { top_reg is covered by DeepMOVOpt }
  2178. top_const:
  2179. begin
  2180. { change
  2181. mov const, %treg
  2182. mov %treg, y
  2183. to
  2184. mov const, y
  2185. }
  2186. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2187. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2188. begin
  2189. if taicpu(hp1).oper[1]^.typ=top_reg then
  2190. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2191. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2192. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2193. RemoveInstruction(hp1);
  2194. Result:=true;
  2195. Exit;
  2196. end;
  2197. end;
  2198. top_ref:
  2199. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2200. begin
  2201. { change
  2202. mov mem, %treg
  2203. mov %treg, %reg
  2204. to
  2205. mov mem, %reg"
  2206. }
  2207. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2208. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2209. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2210. RemoveInstruction(hp1);
  2211. Result:=true;
  2212. Exit;
  2213. end;
  2214. else
  2215. ;
  2216. end
  2217. else
  2218. { %treg is used afterwards, but all eventualities
  2219. other than the first MOV instruction being a constant
  2220. are covered by DeepMOVOpt, so only check for that }
  2221. if (taicpu(p).oper[0]^.typ = top_const) and
  2222. (
  2223. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2224. not (cs_opt_size in current_settings.optimizerswitches) or
  2225. (taicpu(hp1).opsize = S_B)
  2226. ) and
  2227. (
  2228. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2229. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2230. ) then
  2231. begin
  2232. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2233. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2234. end;
  2235. end;
  2236. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2237. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2238. { mov reg1, mem1 or mov mem1, reg1
  2239. mov mem2, reg2 mov reg2, mem2}
  2240. begin
  2241. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2242. { mov reg1, mem1 or mov mem1, reg1
  2243. mov mem2, reg1 mov reg2, mem1}
  2244. begin
  2245. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2246. { Removes the second statement from
  2247. mov reg1, mem1/reg2
  2248. mov mem1/reg2, reg1 }
  2249. begin
  2250. if taicpu(p).oper[0]^.typ=top_reg then
  2251. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2252. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2253. RemoveInstruction(hp1);
  2254. Result:=true;
  2255. exit;
  2256. end
  2257. else
  2258. begin
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2261. if (taicpu(p).oper[1]^.typ = top_ref) and
  2262. { mov reg1, mem1
  2263. mov mem2, reg1 }
  2264. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2265. GetNextInstruction(hp1, hp2) and
  2266. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2267. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2268. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2269. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2270. { change to
  2271. mov reg1, mem1 mov reg1, mem1
  2272. mov mem2, reg1 cmp reg1, mem2
  2273. cmp mem1, reg1
  2274. }
  2275. begin
  2276. RemoveInstruction(hp2);
  2277. taicpu(hp1).opcode := A_CMP;
  2278. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2279. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2280. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2281. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2282. end;
  2283. end;
  2284. end
  2285. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2286. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2287. begin
  2288. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2289. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2290. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2291. end
  2292. else
  2293. begin
  2294. TransferUsedRegs(TmpUsedRegs);
  2295. if GetNextInstruction(hp1, hp2) and
  2296. MatchOpType(taicpu(p),top_ref,top_reg) and
  2297. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2298. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2299. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2300. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2301. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2302. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2303. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2304. { mov mem1, %reg1
  2305. mov %reg1, mem2
  2306. mov mem2, reg2
  2307. to:
  2308. mov mem1, reg2
  2309. mov reg2, mem2}
  2310. begin
  2311. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2312. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2313. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2314. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2315. RemoveInstruction(hp2);
  2316. end
  2317. {$ifdef i386}
  2318. { this is enabled for i386 only, as the rules to create the reg sets below
  2319. are too complicated for x86-64, so this makes this code too error prone
  2320. on x86-64
  2321. }
  2322. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2323. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2324. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2325. { mov mem1, reg1 mov mem1, reg1
  2326. mov reg1, mem2 mov reg1, mem2
  2327. mov mem2, reg2 mov mem2, reg1
  2328. to: to:
  2329. mov mem1, reg1 mov mem1, reg1
  2330. mov mem1, reg2 mov reg1, mem2
  2331. mov reg1, mem2
  2332. or (if mem1 depends on reg1
  2333. and/or if mem2 depends on reg2)
  2334. to:
  2335. mov mem1, reg1
  2336. mov reg1, mem2
  2337. mov reg1, reg2
  2338. }
  2339. begin
  2340. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2341. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2342. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2343. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2344. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2345. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2346. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2347. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2348. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2349. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2350. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2351. end
  2352. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2353. begin
  2354. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2355. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2356. end
  2357. else
  2358. begin
  2359. RemoveInstruction(hp2);
  2360. end
  2361. {$endif i386}
  2362. ;
  2363. end;
  2364. end
  2365. { movl [mem1],reg1
  2366. movl [mem1],reg2
  2367. to
  2368. movl [mem1],reg1
  2369. movl reg1,reg2
  2370. }
  2371. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2372. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2373. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2374. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2375. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2376. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2377. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2378. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2379. begin
  2380. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2381. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2382. end;
  2383. { movl const1,[mem1]
  2384. movl [mem1],reg1
  2385. to
  2386. movl const1,reg1
  2387. movl reg1,[mem1]
  2388. }
  2389. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2390. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2391. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2392. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2393. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2394. begin
  2395. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2396. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2397. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2398. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2399. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2400. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2401. Result:=true;
  2402. exit;
  2403. end;
  2404. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2405. end;
  2406. { search further than the next instruction for a mov }
  2407. if
  2408. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  2409. (taicpu(p).oper[1]^.typ = top_reg) and
  2410. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2411. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  2412. begin
  2413. { we work with hp2 here, so hp1 can be still used later on when
  2414. checking for GetNextInstruction_p }
  2415. hp3 := hp1;
  2416. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  2417. CrossJump := False;
  2418. while GetNextInstructionUsingRegCond(hp3,hp2,taicpu(p).oper[1]^.reg,CrossJump) and
  2419. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  2420. (hp2.typ=ait_instruction) do
  2421. begin
  2422. case taicpu(hp2).opcode of
  2423. A_MOV:
  2424. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2425. ((taicpu(p).oper[0]^.typ=top_const) or
  2426. ((taicpu(p).oper[0]^.typ=top_reg) and
  2427. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2428. )
  2429. ) then
  2430. begin
  2431. { we have
  2432. mov x, %treg
  2433. mov %treg, y
  2434. }
  2435. TransferUsedRegs(TmpUsedRegs);
  2436. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2437. { We don't need to call UpdateUsedRegs for every instruction between
  2438. p and hp2 because the register we're concerned about will not
  2439. become deallocated (otherwise GetNextInstructionUsingReg would
  2440. have stopped at an earlier instruction). [Kit] }
  2441. TempRegUsed :=
  2442. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  2443. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2444. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2445. case taicpu(p).oper[0]^.typ Of
  2446. top_reg:
  2447. begin
  2448. { change
  2449. mov %reg, %treg
  2450. mov %treg, y
  2451. to
  2452. mov %reg, y
  2453. }
  2454. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2455. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2456. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2457. begin
  2458. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2459. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2460. if TempRegUsed then
  2461. begin
  2462. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2463. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2464. { Set the start of the next GetNextInstructionUsingRegCond search
  2465. to start at the entry right before hp2 (which is about to be removed) }
  2466. hp3 := tai(hp2.Previous);
  2467. RemoveInstruction(hp2);
  2468. { See if there's more we can optimise }
  2469. Continue;
  2470. end
  2471. else
  2472. begin
  2473. RemoveInstruction(hp2);
  2474. { We can remove the original MOV too }
  2475. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2476. RemoveCurrentP(p, hp1);
  2477. Result:=true;
  2478. Exit;
  2479. end;
  2480. end
  2481. else
  2482. begin
  2483. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2484. taicpu(hp2).loadReg(0, CurrentReg);
  2485. if TempRegUsed then
  2486. begin
  2487. { Don't remove the first instruction if the temporary register is in use }
  2488. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2489. { No need to set Result to True. If there's another instruction later on
  2490. that can be optimised, it will be detected when the main Pass 1 loop
  2491. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2492. end
  2493. else
  2494. begin
  2495. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2496. RemoveCurrentP(p, hp1);
  2497. Result:=true;
  2498. Exit;
  2499. end;
  2500. end;
  2501. end;
  2502. top_const:
  2503. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2504. begin
  2505. { change
  2506. mov const, %treg
  2507. mov %treg, y
  2508. to
  2509. mov const, y
  2510. }
  2511. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2512. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2513. begin
  2514. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2515. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2516. if TempRegUsed then
  2517. begin
  2518. { Don't remove the first instruction if the temporary register is in use }
  2519. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2520. { No need to set Result to True. If there's another instruction later on
  2521. that can be optimised, it will be detected when the main Pass 1 loop
  2522. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2523. end
  2524. else
  2525. begin
  2526. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2527. RemoveCurrentP(p, hp1);
  2528. Result:=true;
  2529. Exit;
  2530. end;
  2531. end;
  2532. end;
  2533. else
  2534. Internalerror(2019103001);
  2535. end;
  2536. end;
  2537. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2538. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2539. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2540. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2541. begin
  2542. {
  2543. Change from:
  2544. mov ###, %reg
  2545. ...
  2546. movs/z %reg,%reg (Same register, just different sizes)
  2547. To:
  2548. movs/z ###, %reg (Longer version)
  2549. ...
  2550. (remove)
  2551. }
  2552. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2553. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2554. { Keep the first instruction as mov if ### is a constant }
  2555. if taicpu(p).oper[0]^.typ = top_const then
  2556. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2557. else
  2558. begin
  2559. taicpu(p).opcode := taicpu(hp2).opcode;
  2560. taicpu(p).opsize := taicpu(hp2).opsize;
  2561. end;
  2562. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2563. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2564. RemoveInstruction(hp2);
  2565. Result := True;
  2566. Exit;
  2567. end;
  2568. else
  2569. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2570. begin
  2571. CurrentReg := taicpu(p).oper[1]^.reg;
  2572. TransferUsedRegs(TmpUsedRegs);
  2573. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2574. if
  2575. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  2576. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  2577. { if we replace taicpu(p).oper[1]^.reg by taicpu(p).oper[0]^.reg,
  2578. taicpu(p).oper[1]^.reg might not be modified in between }
  2579. not RegModifiedBetween(CurrentReg, p, hp2) and
  2580. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  2581. begin
  2582. { Just in case something didn't get modified (e.g. an
  2583. implicit register) }
  2584. if not RegReadByInstruction(CurrentReg, hp2) and
  2585. { If a conditional jump was crossed, do not delete
  2586. the original MOV no matter what }
  2587. not CrossJump then
  2588. begin
  2589. TransferUsedRegs(TmpUsedRegs);
  2590. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2591. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2592. if not RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs) then
  2593. begin
  2594. { We can remove the original MOV }
  2595. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  2596. RemoveCurrentp(p, hp1);
  2597. Result := True;
  2598. Exit;
  2599. end
  2600. else
  2601. begin
  2602. { See if there's more we can optimise }
  2603. hp3 := hp2;
  2604. Continue;
  2605. end;
  2606. end;
  2607. end;
  2608. end;
  2609. end;
  2610. { Break out of the while loop under normal circumstances }
  2611. Break;
  2612. end;
  2613. end;
  2614. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2615. (taicpu(p).oper[1]^.typ = top_reg) and
  2616. (taicpu(p).opsize = S_L) and
  2617. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2618. (taicpu(hp2).opcode = A_AND) and
  2619. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2620. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2621. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2622. ) then
  2623. begin
  2624. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2625. begin
  2626. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2627. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2628. begin
  2629. { Optimize out:
  2630. mov x, %reg
  2631. and ffffffffh, %reg
  2632. }
  2633. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2634. RemoveInstruction(hp2);
  2635. Result:=true;
  2636. exit;
  2637. end;
  2638. end;
  2639. end;
  2640. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2641. x >= RetOffset) as it doesn't do anything (it writes either to a
  2642. parameter or to the temporary storage room for the function
  2643. result)
  2644. }
  2645. if IsExitCode(hp1) and
  2646. (taicpu(p).oper[1]^.typ = top_ref) and
  2647. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  2648. (
  2649. (
  2650. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  2651. not (
  2652. assigned(current_procinfo.procdef.funcretsym) and
  2653. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  2654. )
  2655. ) or
  2656. { Also discard writes to the stack that are below the base pointer,
  2657. as this is temporary storage rather than a function result on the
  2658. stack, say. }
  2659. (
  2660. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  2661. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  2662. )
  2663. ) then
  2664. begin
  2665. RemoveCurrentp(p, hp1);
  2666. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  2667. RemoveLastDeallocForFuncRes(p);
  2668. Result:=true;
  2669. exit;
  2670. end;
  2671. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  2672. begin
  2673. if MatchOpType(taicpu(p),top_reg,top_ref) and
  2674. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2675. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2676. begin
  2677. { change
  2678. mov reg1, mem1
  2679. test/cmp x, mem1
  2680. to
  2681. mov reg1, mem1
  2682. test/cmp x, reg1
  2683. }
  2684. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  2685. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  2686. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2687. Result := True;
  2688. Exit;
  2689. end;
  2690. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2691. { The x86 assemblers have difficulty comparing values against absolute addresses }
  2692. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  2693. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  2694. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  2695. (
  2696. (
  2697. (taicpu(hp1).opcode = A_TEST)
  2698. ) or (
  2699. (taicpu(hp1).opcode = A_CMP) and
  2700. { A sanity check more than anything }
  2701. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  2702. )
  2703. ) then
  2704. begin
  2705. { change
  2706. mov mem, %reg
  2707. cmp/test x, %reg / test %reg,%reg
  2708. (reg deallocated)
  2709. to
  2710. cmp/test x, mem / cmp 0, mem
  2711. }
  2712. TransferUsedRegs(TmpUsedRegs);
  2713. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2714. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2715. begin
  2716. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  2717. if (taicpu(hp1).opcode = A_TEST) and
  2718. (
  2719. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  2720. MatchOperand(taicpu(hp1).oper[0]^, -1)
  2721. ) then
  2722. begin
  2723. taicpu(hp1).opcode := A_CMP;
  2724. taicpu(hp1).loadconst(0, 0);
  2725. end;
  2726. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  2727. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  2728. RemoveCurrentP(p, hp1);
  2729. Result := True;
  2730. Exit;
  2731. end;
  2732. end;
  2733. end;
  2734. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  2735. { If the flags register is in use, don't change the instruction to an
  2736. ADD otherwise this will scramble the flags. [Kit] }
  2737. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  2738. begin
  2739. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  2740. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  2741. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  2742. ) or
  2743. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  2744. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  2745. )
  2746. ) then
  2747. { mov reg1,ref
  2748. lea reg2,[reg1,reg2]
  2749. to
  2750. add reg2,ref}
  2751. begin
  2752. TransferUsedRegs(TmpUsedRegs);
  2753. { reg1 may not be used afterwards }
  2754. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  2755. begin
  2756. Taicpu(hp1).opcode:=A_ADD;
  2757. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  2758. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  2759. RemoveCurrentp(p, hp1);
  2760. result:=true;
  2761. exit;
  2762. end;
  2763. end;
  2764. { If the LEA instruction can be converted into an arithmetic instruction,
  2765. it may be possible to then fold it in the next optimisation, otherwise
  2766. there's nothing more that can be optimised here. }
  2767. if not ConvertLEA(taicpu(hp1)) then
  2768. Exit;
  2769. end;
  2770. if (taicpu(p).oper[1]^.typ = top_reg) and
  2771. (hp1.typ = ait_instruction) and
  2772. GetNextInstruction(hp1, hp2) and
  2773. MatchInstruction(hp2,A_MOV,[]) and
  2774. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  2775. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  2776. (
  2777. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  2778. {$ifdef x86_64}
  2779. or
  2780. (
  2781. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  2782. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  2783. )
  2784. {$endif x86_64}
  2785. ) then
  2786. begin
  2787. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2788. (taicpu(hp2).oper[0]^.typ=top_reg) then
  2789. { change movsX/movzX reg/ref, reg2
  2790. add/sub/or/... reg3/$const, reg2
  2791. mov reg2 reg/ref
  2792. dealloc reg2
  2793. to
  2794. add/sub/or/... reg3/$const, reg/ref }
  2795. begin
  2796. TransferUsedRegs(TmpUsedRegs);
  2797. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2798. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2799. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2800. begin
  2801. { by example:
  2802. movswl %si,%eax movswl %si,%eax p
  2803. decl %eax addl %edx,%eax hp1
  2804. movw %ax,%si movw %ax,%si hp2
  2805. ->
  2806. movswl %si,%eax movswl %si,%eax p
  2807. decw %eax addw %edx,%eax hp1
  2808. movw %ax,%si movw %ax,%si hp2
  2809. }
  2810. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  2811. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2812. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2813. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2814. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2815. {
  2816. ->
  2817. movswl %si,%eax movswl %si,%eax p
  2818. decw %si addw %dx,%si hp1
  2819. movw %ax,%si movw %ax,%si hp2
  2820. }
  2821. case taicpu(hp1).ops of
  2822. 1:
  2823. begin
  2824. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2825. if taicpu(hp1).oper[0]^.typ=top_reg then
  2826. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2827. end;
  2828. 2:
  2829. begin
  2830. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2831. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2832. (taicpu(hp1).opcode<>A_SHL) and
  2833. (taicpu(hp1).opcode<>A_SHR) and
  2834. (taicpu(hp1).opcode<>A_SAR) then
  2835. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2836. end;
  2837. else
  2838. internalerror(2008042701);
  2839. end;
  2840. {
  2841. ->
  2842. decw %si addw %dx,%si p
  2843. }
  2844. RemoveInstruction(hp2);
  2845. RemoveCurrentP(p, hp1);
  2846. Result:=True;
  2847. Exit;
  2848. end;
  2849. end;
  2850. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2851. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  2852. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  2853. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  2854. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  2855. )
  2856. {$ifdef i386}
  2857. { byte registers of esi, edi, ebp, esp are not available on i386 }
  2858. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2859. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2860. {$endif i386}
  2861. then
  2862. { change movsX/movzX reg/ref, reg2
  2863. add/sub/or/... regX/$const, reg2
  2864. mov reg2, reg3
  2865. dealloc reg2
  2866. to
  2867. movsX/movzX reg/ref, reg3
  2868. add/sub/or/... reg3/$const, reg3
  2869. }
  2870. begin
  2871. TransferUsedRegs(TmpUsedRegs);
  2872. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2873. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2874. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2875. begin
  2876. { by example:
  2877. movswl %si,%eax movswl %si,%eax p
  2878. decl %eax addl %edx,%eax hp1
  2879. movw %ax,%si movw %ax,%si hp2
  2880. ->
  2881. movswl %si,%eax movswl %si,%eax p
  2882. decw %eax addw %edx,%eax hp1
  2883. movw %ax,%si movw %ax,%si hp2
  2884. }
  2885. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  2886. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2887. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2888. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2889. { limit size of constants as well to avoid assembler errors, but
  2890. check opsize to avoid overflow when left shifting the 1 }
  2891. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  2892. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  2893. {$ifdef x86_64}
  2894. { Be careful of, for example:
  2895. movl %reg1,%reg2
  2896. addl %reg3,%reg2
  2897. movq %reg2,%reg4
  2898. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  2899. }
  2900. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  2901. begin
  2902. taicpu(hp2).changeopsize(S_L);
  2903. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  2904. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  2905. end;
  2906. {$endif x86_64}
  2907. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2908. taicpu(p).changeopsize(taicpu(hp2).opsize);
  2909. if taicpu(p).oper[0]^.typ=top_reg then
  2910. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2911. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  2912. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  2913. {
  2914. ->
  2915. movswl %si,%eax movswl %si,%eax p
  2916. decw %si addw %dx,%si hp1
  2917. movw %ax,%si movw %ax,%si hp2
  2918. }
  2919. case taicpu(hp1).ops of
  2920. 1:
  2921. begin
  2922. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2923. if taicpu(hp1).oper[0]^.typ=top_reg then
  2924. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2925. end;
  2926. 2:
  2927. begin
  2928. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2929. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2930. (taicpu(hp1).opcode<>A_SHL) and
  2931. (taicpu(hp1).opcode<>A_SHR) and
  2932. (taicpu(hp1).opcode<>A_SAR) then
  2933. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2934. end;
  2935. else
  2936. internalerror(2018111801);
  2937. end;
  2938. {
  2939. ->
  2940. decw %si addw %dx,%si p
  2941. }
  2942. RemoveInstruction(hp2);
  2943. end;
  2944. end;
  2945. end;
  2946. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  2947. GetNextInstruction(hp1, hp2) and
  2948. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  2949. MatchOperand(Taicpu(p).oper[0]^,0) and
  2950. (Taicpu(p).oper[1]^.typ = top_reg) and
  2951. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  2952. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  2953. { mov reg1,0
  2954. bts reg1,operand1 --> mov reg1,operand2
  2955. or reg1,operand2 bts reg1,operand1}
  2956. begin
  2957. Taicpu(hp2).opcode:=A_MOV;
  2958. asml.remove(hp1);
  2959. insertllitem(hp2,hp2.next,hp1);
  2960. RemoveCurrentp(p, hp1);
  2961. Result:=true;
  2962. exit;
  2963. end;
  2964. {$ifdef x86_64}
  2965. { Convert:
  2966. movq x(ref),%reg64
  2967. shrq y,%reg64
  2968. To:
  2969. movq x+4(ref),%reg32
  2970. shrq y-32,%reg32 (Remove if y = 32)
  2971. }
  2972. if (taicpu(p).opsize = S_Q) and
  2973. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  2974. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  2975. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  2976. MatchOpType(taicpu(hp1), top_const, top_reg) and
  2977. (taicpu(hp1).oper[0]^.val >= 32) and
  2978. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  2979. begin
  2980. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  2981. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  2982. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  2983. { Convert to 32-bit }
  2984. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2985. taicpu(p).opsize := S_L;
  2986. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  2987. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  2988. if (taicpu(hp1).oper[0]^.val = 32) then
  2989. begin
  2990. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  2991. RemoveInstruction(hp1);
  2992. end
  2993. else
  2994. begin
  2995. { This will potentially open up more arithmetic operations since
  2996. the peephole optimizer now has a big hint that only the lower
  2997. 32 bits are currently in use (and opcodes are smaller in size) }
  2998. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2999. taicpu(hp1).opsize := S_L;
  3000. Dec(taicpu(hp1).oper[0]^.val, 32);
  3001. DebugMsg(SPeepholeOptimization + PreMessage +
  3002. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3003. end;
  3004. Result := True;
  3005. Exit;
  3006. end;
  3007. {$endif x86_64}
  3008. end;
  3009. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3010. var
  3011. hp1 : tai;
  3012. begin
  3013. Result:=false;
  3014. if taicpu(p).ops <> 2 then
  3015. exit;
  3016. if GetNextInstruction(p,hp1) and
  3017. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3018. (taicpu(hp1).ops = 2) then
  3019. begin
  3020. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3021. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3022. { movXX reg1, mem1 or movXX mem1, reg1
  3023. movXX mem2, reg2 movXX reg2, mem2}
  3024. begin
  3025. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3026. { movXX reg1, mem1 or movXX mem1, reg1
  3027. movXX mem2, reg1 movXX reg2, mem1}
  3028. begin
  3029. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3030. begin
  3031. { Removes the second statement from
  3032. movXX reg1, mem1/reg2
  3033. movXX mem1/reg2, reg1
  3034. }
  3035. if taicpu(p).oper[0]^.typ=top_reg then
  3036. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3037. { Removes the second statement from
  3038. movXX mem1/reg1, reg2
  3039. movXX reg2, mem1/reg1
  3040. }
  3041. if (taicpu(p).oper[1]^.typ=top_reg) and
  3042. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3043. begin
  3044. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3045. RemoveInstruction(hp1);
  3046. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3047. end
  3048. else
  3049. begin
  3050. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3051. RemoveInstruction(hp1);
  3052. end;
  3053. Result:=true;
  3054. exit;
  3055. end
  3056. end;
  3057. end;
  3058. end;
  3059. end;
  3060. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3061. var
  3062. hp1 : tai;
  3063. begin
  3064. result:=false;
  3065. { replace
  3066. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3067. MovX %mreg2,%mreg1
  3068. dealloc %mreg2
  3069. by
  3070. <Op>X %mreg2,%mreg1
  3071. ?
  3072. }
  3073. if GetNextInstruction(p,hp1) and
  3074. { we mix single and double opperations here because we assume that the compiler
  3075. generates vmovapd only after double operations and vmovaps only after single operations }
  3076. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3077. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3078. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3079. (taicpu(p).oper[0]^.typ=top_reg) then
  3080. begin
  3081. TransferUsedRegs(TmpUsedRegs);
  3082. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3083. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3084. begin
  3085. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3086. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3087. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3088. RemoveInstruction(hp1);
  3089. result:=true;
  3090. end;
  3091. end;
  3092. end;
  3093. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3094. var
  3095. hp1, p_label, p_dist, hp1_dist: tai;
  3096. JumpLabel, JumpLabel_dist: TAsmLabel;
  3097. begin
  3098. Result := False;
  3099. if (taicpu(p).oper[1]^.typ = top_reg) then
  3100. begin
  3101. if GetNextInstruction(p, hp1) and
  3102. MatchInstruction(hp1,A_MOV,[]) and
  3103. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3104. (
  3105. (taicpu(p).oper[0]^.typ <> top_reg) or
  3106. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3107. ) then
  3108. begin
  3109. { If we have something like:
  3110. test %reg1,%reg1
  3111. mov 0,%reg2
  3112. And no registers are shared (the two %reg1's can be different, as
  3113. long as neither of them are also %reg2), move the MOV command to
  3114. before the comparison as this means it can be optimised without
  3115. worrying about the FLAGS register. (This combination is generated
  3116. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3117. }
  3118. SwapMovCmp(p, hp1);
  3119. Result := True;
  3120. Exit;
  3121. end;
  3122. { Search for:
  3123. test %reg,%reg
  3124. j(c1) @lbl1
  3125. ...
  3126. @lbl:
  3127. test %reg,%reg (same register)
  3128. j(c2) @lbl2
  3129. If c2 is a subset of c1, change to:
  3130. test %reg,%reg
  3131. j(c1) @lbl2
  3132. (@lbl1 may become a dead label as a result)
  3133. }
  3134. if (taicpu(p).oper[0]^.typ = top_reg) and
  3135. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3136. MatchInstruction(hp1, A_JCC, []) and
  3137. IsJumpToLabel(taicpu(hp1)) then
  3138. begin
  3139. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3140. p_label := nil;
  3141. if Assigned(JumpLabel) then
  3142. p_label := getlabelwithsym(JumpLabel);
  3143. if Assigned(p_label) and
  3144. GetNextInstruction(p_label, p_dist) and
  3145. MatchInstruction(p_dist, A_TEST, []) and
  3146. { It's fine if the second test uses smaller sub-registers }
  3147. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3148. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3149. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3150. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3151. GetNextInstruction(p_dist, hp1_dist) and
  3152. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3153. begin
  3154. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3155. if JumpLabel = JumpLabel_dist then
  3156. { This is an infinite loop }
  3157. Exit;
  3158. { Best optimisation when the first condition is a subset (or equal) of the second }
  3159. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3160. begin
  3161. { Any registers used here will already be allocated }
  3162. if Assigned(JumpLabel_dist) then
  3163. JumpLabel_dist.IncRefs;
  3164. if Assigned(JumpLabel) then
  3165. JumpLabel.DecRefs;
  3166. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3167. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3168. Result := True;
  3169. Exit;
  3170. end;
  3171. end;
  3172. end;
  3173. end;
  3174. end;
  3175. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3176. var
  3177. hp1 : tai;
  3178. begin
  3179. result:=false;
  3180. { replace
  3181. addX const,%reg1
  3182. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3183. dealloc %reg1
  3184. by
  3185. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3186. }
  3187. if MatchOpType(taicpu(p),top_const,top_reg) and
  3188. GetNextInstruction(p,hp1) and
  3189. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3190. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3191. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3192. begin
  3193. TransferUsedRegs(TmpUsedRegs);
  3194. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3195. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3196. begin
  3197. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3198. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3199. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3200. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3201. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3202. RemoveCurrentP(p);
  3203. result:=true;
  3204. end;
  3205. end;
  3206. end;
  3207. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3208. var
  3209. hp1: tai;
  3210. ref: Integer;
  3211. saveref: treference;
  3212. TempReg: TRegister;
  3213. Multiple: TCGInt;
  3214. begin
  3215. Result:=false;
  3216. { removes seg register prefixes from LEA operations, as they
  3217. don't do anything}
  3218. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3219. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3220. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3221. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3222. { do not mess with leas acessing the stack pointer }
  3223. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3224. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3225. begin
  3226. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3227. begin
  3228. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3229. begin
  3230. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3231. taicpu(p).oper[1]^.reg);
  3232. InsertLLItem(p.previous,p.next, hp1);
  3233. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3234. p.free;
  3235. p:=hp1;
  3236. end
  3237. else
  3238. begin
  3239. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3240. RemoveCurrentP(p);
  3241. end;
  3242. Result:=true;
  3243. exit;
  3244. end
  3245. else if (
  3246. { continue to use lea to adjust the stack pointer,
  3247. it is the recommended way, but only if not optimizing for size }
  3248. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3249. (cs_opt_size in current_settings.optimizerswitches)
  3250. ) and
  3251. { If the flags register is in use, don't change the instruction
  3252. to an ADD otherwise this will scramble the flags. [Kit] }
  3253. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3254. ConvertLEA(taicpu(p)) then
  3255. begin
  3256. Result:=true;
  3257. exit;
  3258. end;
  3259. end;
  3260. if GetNextInstruction(p,hp1) and
  3261. (hp1.typ=ait_instruction) then
  3262. begin
  3263. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3264. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3265. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3266. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3267. begin
  3268. TransferUsedRegs(TmpUsedRegs);
  3269. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3270. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3271. begin
  3272. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3273. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3274. RemoveInstruction(hp1);
  3275. result:=true;
  3276. exit;
  3277. end;
  3278. end;
  3279. { changes
  3280. lea <ref1>, reg1
  3281. <op> ...,<ref. with reg1>,...
  3282. to
  3283. <op> ...,<ref1>,... }
  3284. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3285. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3286. not(MatchInstruction(hp1,A_LEA,[])) then
  3287. begin
  3288. { find a reference which uses reg1 }
  3289. 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
  3290. ref:=0
  3291. 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
  3292. ref:=1
  3293. else
  3294. ref:=-1;
  3295. if (ref<>-1) and
  3296. { reg1 must be either the base or the index }
  3297. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3298. begin
  3299. { reg1 can be removed from the reference }
  3300. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3301. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3302. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3303. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3304. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3305. else
  3306. Internalerror(2019111201);
  3307. { check if the can insert all data of the lea into the second instruction }
  3308. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3309. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3310. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3311. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3312. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3313. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3314. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3315. {$ifdef x86_64}
  3316. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3317. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3318. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3319. )
  3320. {$endif x86_64}
  3321. then
  3322. begin
  3323. { reg1 might not used by the second instruction after it is remove from the reference }
  3324. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3325. begin
  3326. TransferUsedRegs(TmpUsedRegs);
  3327. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3328. { reg1 is not updated so it might not be used afterwards }
  3329. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3330. begin
  3331. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3332. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3333. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3334. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3335. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3336. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3337. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3338. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3339. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3340. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3341. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3342. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3343. RemoveCurrentP(p, hp1);
  3344. result:=true;
  3345. exit;
  3346. end
  3347. end;
  3348. end;
  3349. { recover }
  3350. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3351. end;
  3352. end;
  3353. end;
  3354. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3355. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3356. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3357. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3358. begin
  3359. { Check common LEA/LEA conditions }
  3360. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3361. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  3362. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  3363. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  3364. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  3365. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  3366. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  3367. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  3368. (
  3369. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  3370. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  3371. ) and (
  3372. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  3373. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3374. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  3375. ) then
  3376. begin
  3377. { changes
  3378. lea (regX,scale), reg1
  3379. lea offset(reg1,reg1), reg1
  3380. to
  3381. lea offset(regX,scale*2), reg1
  3382. and
  3383. lea (regX,scale1), reg1
  3384. lea offset(reg1,scale2), reg1
  3385. to
  3386. lea offset(regX,scale1*scale2), reg1
  3387. ... so long as the final scale does not exceed 8
  3388. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  3389. }
  3390. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  3391. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3392. (
  3393. (
  3394. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3395. ) or (
  3396. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3397. (
  3398. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  3399. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  3400. )
  3401. )
  3402. ) and (
  3403. (
  3404. { lea (reg1,scale2), reg1 variant }
  3405. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  3406. (
  3407. (
  3408. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  3409. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  3410. ) or (
  3411. { lea (regX,regX), reg1 variant }
  3412. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3413. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  3414. )
  3415. )
  3416. ) or (
  3417. { lea (reg1,reg1), reg1 variant }
  3418. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3419. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  3420. )
  3421. ) then
  3422. begin
  3423. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  3424. { Make everything homogeneous to make calculations easier }
  3425. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  3426. begin
  3427. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  3428. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  3429. taicpu(p).oper[0]^.ref^.scalefactor := 2
  3430. else
  3431. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  3432. taicpu(p).oper[0]^.ref^.base := NR_NO;
  3433. end;
  3434. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  3435. begin
  3436. { Just to prevent miscalculations }
  3437. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  3438. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  3439. else
  3440. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  3441. end
  3442. else
  3443. begin
  3444. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  3445. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  3446. end;
  3447. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  3448. RemoveCurrentP(p);
  3449. result:=true;
  3450. exit;
  3451. end
  3452. { changes
  3453. lea offset1(regX), reg1
  3454. lea offset2(reg1), reg1
  3455. to
  3456. lea offset1+offset2(regX), reg1 }
  3457. else if
  3458. (
  3459. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3460. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  3461. ) or (
  3462. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3463. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3464. (
  3465. (
  3466. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3467. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3468. ) or (
  3469. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3470. (
  3471. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3472. (
  3473. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3474. (
  3475. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  3476. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  3477. )
  3478. )
  3479. )
  3480. )
  3481. )
  3482. ) then
  3483. begin
  3484. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  3485. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3486. begin
  3487. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3488. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3489. { if the register is used as index and base, we have to increase for base as well
  3490. and adapt base }
  3491. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3492. begin
  3493. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3494. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3495. end;
  3496. end
  3497. else
  3498. begin
  3499. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3500. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3501. end;
  3502. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3503. begin
  3504. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3505. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3506. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3507. end;
  3508. RemoveCurrentP(p);
  3509. result:=true;
  3510. exit;
  3511. end;
  3512. end;
  3513. { Change:
  3514. leal/q $x(%reg1),%reg2
  3515. ...
  3516. shll/q $y,%reg2
  3517. To:
  3518. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3519. }
  3520. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3521. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3522. (taicpu(hp1).oper[0]^.val <= 3) then
  3523. begin
  3524. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3525. TransferUsedRegs(TmpUsedRegs);
  3526. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3527. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3528. if
  3529. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3530. (this works even if scalefactor is zero) }
  3531. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3532. { Ensure offset doesn't go out of bounds }
  3533. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3534. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3535. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3536. (
  3537. (
  3538. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3539. (
  3540. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3541. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3542. (
  3543. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3544. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3545. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3546. )
  3547. )
  3548. ) or (
  3549. (
  3550. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3551. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3552. ) and
  3553. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3554. )
  3555. ) then
  3556. begin
  3557. repeat
  3558. with taicpu(p).oper[0]^.ref^ do
  3559. begin
  3560. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3561. if index = base then
  3562. begin
  3563. if Multiple > 4 then
  3564. { Optimisation will no longer work because resultant
  3565. scale factor will exceed 8 }
  3566. Break;
  3567. base := NR_NO;
  3568. scalefactor := 2;
  3569. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3570. end
  3571. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3572. begin
  3573. { Scale factor only works on the index register }
  3574. index := base;
  3575. base := NR_NO;
  3576. end;
  3577. { For safety }
  3578. if scalefactor <= 1 then
  3579. begin
  3580. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3581. scalefactor := Multiple;
  3582. end
  3583. else
  3584. begin
  3585. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3586. scalefactor := scalefactor * Multiple;
  3587. end;
  3588. offset := offset * Multiple;
  3589. end;
  3590. RemoveInstruction(hp1);
  3591. Result := True;
  3592. Exit;
  3593. { This repeat..until loop exists for the benefit of Break }
  3594. until True;
  3595. end;
  3596. end;
  3597. end;
  3598. end;
  3599. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3600. var
  3601. hp1 : tai;
  3602. begin
  3603. DoSubAddOpt := False;
  3604. if GetLastInstruction(p, hp1) and
  3605. (hp1.typ = ait_instruction) and
  3606. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3607. case taicpu(hp1).opcode Of
  3608. A_DEC:
  3609. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3610. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3611. begin
  3612. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3613. RemoveInstruction(hp1);
  3614. end;
  3615. A_SUB:
  3616. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3617. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3618. begin
  3619. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3620. RemoveInstruction(hp1);
  3621. end;
  3622. A_ADD:
  3623. begin
  3624. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3625. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3626. begin
  3627. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3628. RemoveInstruction(hp1);
  3629. if (taicpu(p).oper[0]^.val = 0) then
  3630. begin
  3631. hp1 := tai(p.next);
  3632. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3633. if not GetLastInstruction(hp1, p) then
  3634. p := hp1;
  3635. DoSubAddOpt := True;
  3636. end
  3637. end;
  3638. end;
  3639. else
  3640. ;
  3641. end;
  3642. end;
  3643. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  3644. {$ifdef i386}
  3645. var
  3646. hp1 : tai;
  3647. {$endif i386}
  3648. begin
  3649. Result:=false;
  3650. { * change "subl $2, %esp; pushw x" to "pushl x"}
  3651. { * change "sub/add const1, reg" or "dec reg" followed by
  3652. "sub const2, reg" to one "sub ..., reg" }
  3653. if MatchOpType(taicpu(p),top_const,top_reg) then
  3654. begin
  3655. {$ifdef i386}
  3656. if (taicpu(p).oper[0]^.val = 2) and
  3657. (taicpu(p).oper[1]^.reg = NR_ESP) and
  3658. { Don't do the sub/push optimization if the sub }
  3659. { comes from setting up the stack frame (JM) }
  3660. (not(GetLastInstruction(p,hp1)) or
  3661. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  3662. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  3663. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  3664. begin
  3665. hp1 := tai(p.next);
  3666. while Assigned(hp1) and
  3667. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  3668. not RegReadByInstruction(NR_ESP,hp1) and
  3669. not RegModifiedByInstruction(NR_ESP,hp1) do
  3670. hp1 := tai(hp1.next);
  3671. if Assigned(hp1) and
  3672. MatchInstruction(hp1,A_PUSH,[S_W]) then
  3673. begin
  3674. taicpu(hp1).changeopsize(S_L);
  3675. if taicpu(hp1).oper[0]^.typ=top_reg then
  3676. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  3677. hp1 := tai(p.next);
  3678. RemoveCurrentp(p, hp1);
  3679. Result:=true;
  3680. exit;
  3681. end;
  3682. end;
  3683. {$endif i386}
  3684. if DoSubAddOpt(p) then
  3685. Result:=true;
  3686. end;
  3687. end;
  3688. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  3689. var
  3690. TmpBool1,TmpBool2 : Boolean;
  3691. tmpref : treference;
  3692. hp1,hp2: tai;
  3693. mask: tcgint;
  3694. begin
  3695. Result:=false;
  3696. { All these optimisations work on "shl/sal const,%reg" }
  3697. if not MatchOpType(taicpu(p),top_const,top_reg) then
  3698. Exit;
  3699. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3700. (taicpu(p).oper[0]^.val <= 3) then
  3701. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  3702. begin
  3703. { should we check the next instruction? }
  3704. TmpBool1 := True;
  3705. { have we found an add/sub which could be
  3706. integrated in the lea? }
  3707. TmpBool2 := False;
  3708. reference_reset(tmpref,2,[]);
  3709. TmpRef.index := taicpu(p).oper[1]^.reg;
  3710. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3711. while TmpBool1 and
  3712. GetNextInstruction(p, hp1) and
  3713. (tai(hp1).typ = ait_instruction) and
  3714. ((((taicpu(hp1).opcode = A_ADD) or
  3715. (taicpu(hp1).opcode = A_SUB)) and
  3716. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  3717. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  3718. (((taicpu(hp1).opcode = A_INC) or
  3719. (taicpu(hp1).opcode = A_DEC)) and
  3720. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3721. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  3722. ((taicpu(hp1).opcode = A_LEA) and
  3723. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3724. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  3725. (not GetNextInstruction(hp1,hp2) or
  3726. not instrReadsFlags(hp2)) Do
  3727. begin
  3728. TmpBool1 := False;
  3729. if taicpu(hp1).opcode=A_LEA then
  3730. begin
  3731. if (TmpRef.base = NR_NO) and
  3732. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  3733. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  3734. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  3735. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  3736. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  3737. begin
  3738. TmpBool1 := True;
  3739. TmpBool2 := True;
  3740. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  3741. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  3742. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  3743. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  3744. RemoveInstruction(hp1);
  3745. end
  3746. end
  3747. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  3748. begin
  3749. TmpBool1 := True;
  3750. TmpBool2 := True;
  3751. case taicpu(hp1).opcode of
  3752. A_ADD:
  3753. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3754. A_SUB:
  3755. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3756. else
  3757. internalerror(2019050536);
  3758. end;
  3759. RemoveInstruction(hp1);
  3760. end
  3761. else
  3762. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3763. (((taicpu(hp1).opcode = A_ADD) and
  3764. (TmpRef.base = NR_NO)) or
  3765. (taicpu(hp1).opcode = A_INC) or
  3766. (taicpu(hp1).opcode = A_DEC)) then
  3767. begin
  3768. TmpBool1 := True;
  3769. TmpBool2 := True;
  3770. case taicpu(hp1).opcode of
  3771. A_ADD:
  3772. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  3773. A_INC:
  3774. inc(TmpRef.offset);
  3775. A_DEC:
  3776. dec(TmpRef.offset);
  3777. else
  3778. internalerror(2019050535);
  3779. end;
  3780. RemoveInstruction(hp1);
  3781. end;
  3782. end;
  3783. if TmpBool2
  3784. {$ifndef x86_64}
  3785. or
  3786. ((current_settings.optimizecputype < cpu_Pentium2) and
  3787. (taicpu(p).oper[0]^.val <= 3) and
  3788. not(cs_opt_size in current_settings.optimizerswitches))
  3789. {$endif x86_64}
  3790. then
  3791. begin
  3792. if not(TmpBool2) and
  3793. (taicpu(p).oper[0]^.val=1) then
  3794. begin
  3795. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3796. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  3797. end
  3798. else
  3799. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  3800. taicpu(p).oper[1]^.reg);
  3801. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  3802. InsertLLItem(p.previous, p.next, hp1);
  3803. p.free;
  3804. p := hp1;
  3805. end;
  3806. end
  3807. {$ifndef x86_64}
  3808. else if (current_settings.optimizecputype < cpu_Pentium2) then
  3809. begin
  3810. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  3811. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  3812. (unlike shl, which is only Tairable in the U pipe) }
  3813. if taicpu(p).oper[0]^.val=1 then
  3814. begin
  3815. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3816. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  3817. InsertLLItem(p.previous, p.next, hp1);
  3818. p.free;
  3819. p := hp1;
  3820. end
  3821. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  3822. "shl $3, %reg" to "lea (,%reg,8), %reg }
  3823. else if (taicpu(p).opsize = S_L) and
  3824. (taicpu(p).oper[0]^.val<= 3) then
  3825. begin
  3826. reference_reset(tmpref,2,[]);
  3827. TmpRef.index := taicpu(p).oper[1]^.reg;
  3828. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3829. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  3830. InsertLLItem(p.previous, p.next, hp1);
  3831. p.free;
  3832. p := hp1;
  3833. end;
  3834. end
  3835. {$endif x86_64}
  3836. else if
  3837. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  3838. (
  3839. (
  3840. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  3841. SetAndTest(hp1, hp2)
  3842. {$ifdef x86_64}
  3843. ) or
  3844. (
  3845. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3846. GetNextInstruction(hp1, hp2) and
  3847. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  3848. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3849. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  3850. {$endif x86_64}
  3851. )
  3852. ) and
  3853. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  3854. begin
  3855. { Change:
  3856. shl x, %reg1
  3857. mov -(1<<x), %reg2
  3858. and %reg2, %reg1
  3859. Or:
  3860. shl x, %reg1
  3861. and -(1<<x), %reg1
  3862. To just:
  3863. shl x, %reg1
  3864. Since the and operation only zeroes bits that are already zero from the shl operation
  3865. }
  3866. case taicpu(p).oper[0]^.val of
  3867. 8:
  3868. mask:=$FFFFFFFFFFFFFF00;
  3869. 16:
  3870. mask:=$FFFFFFFFFFFF0000;
  3871. 32:
  3872. mask:=$FFFFFFFF00000000;
  3873. 63:
  3874. { Constant pre-calculated to prevent overflow errors with Int64 }
  3875. mask:=$8000000000000000;
  3876. else
  3877. begin
  3878. if taicpu(p).oper[0]^.val >= 64 then
  3879. { Shouldn't happen realistically, since the register
  3880. is guaranteed to be set to zero at this point }
  3881. mask := 0
  3882. else
  3883. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  3884. end;
  3885. end;
  3886. if taicpu(hp1).oper[0]^.val = mask then
  3887. begin
  3888. { Everything checks out, perform the optimisation, as long as
  3889. the FLAGS register isn't being used}
  3890. TransferUsedRegs(TmpUsedRegs);
  3891. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3892. {$ifdef x86_64}
  3893. if (hp1 <> hp2) then
  3894. begin
  3895. { "shl/mov/and" version }
  3896. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3897. { Don't do the optimisation if the FLAGS register is in use }
  3898. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  3899. begin
  3900. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  3901. { Don't remove the 'mov' instruction if its register is used elsewhere }
  3902. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3903. begin
  3904. RemoveInstruction(hp1);
  3905. Result := True;
  3906. end;
  3907. { Only set Result to True if the 'mov' instruction was removed }
  3908. RemoveInstruction(hp2);
  3909. end;
  3910. end
  3911. else
  3912. {$endif x86_64}
  3913. begin
  3914. { "shl/and" version }
  3915. { Don't do the optimisation if the FLAGS register is in use }
  3916. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3917. begin
  3918. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  3919. RemoveInstruction(hp1);
  3920. Result := True;
  3921. end;
  3922. end;
  3923. Exit;
  3924. end
  3925. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  3926. begin
  3927. { Even if the mask doesn't allow for its removal, we might be
  3928. able to optimise the mask for the "shl/and" version, which
  3929. may permit other peephole optimisations }
  3930. {$ifdef DEBUG_AOPTCPU}
  3931. mask := taicpu(hp1).oper[0]^.val and mask;
  3932. if taicpu(hp1).oper[0]^.val <> mask then
  3933. begin
  3934. DebugMsg(
  3935. SPeepholeOptimization +
  3936. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  3937. ' to $' + debug_tostr(mask) +
  3938. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  3939. taicpu(hp1).oper[0]^.val := mask;
  3940. end;
  3941. {$else DEBUG_AOPTCPU}
  3942. { If debugging is off, just set the operand even if it's the same }
  3943. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  3944. {$endif DEBUG_AOPTCPU}
  3945. end;
  3946. end;
  3947. end;
  3948. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  3949. var
  3950. CurrentRef: TReference;
  3951. FullReg: TRegister;
  3952. hp1, hp2: tai;
  3953. begin
  3954. Result := False;
  3955. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  3956. Exit;
  3957. { We assume you've checked if the operand is actually a reference by
  3958. this point. If it isn't, you'll most likely get an access violation }
  3959. CurrentRef := first_mov.oper[1]^.ref^;
  3960. { Memory must be aligned }
  3961. if (CurrentRef.offset mod 4) <> 0 then
  3962. Exit;
  3963. Inc(CurrentRef.offset);
  3964. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  3965. if MatchOperand(second_mov.oper[0]^, 0) and
  3966. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  3967. GetNextInstruction(second_mov, hp1) and
  3968. (hp1.typ = ait_instruction) and
  3969. (taicpu(hp1).opcode = A_MOV) and
  3970. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3971. (taicpu(hp1).oper[0]^.val = 0) then
  3972. begin
  3973. Inc(CurrentRef.offset);
  3974. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  3975. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  3976. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  3977. begin
  3978. case taicpu(hp1).opsize of
  3979. S_B:
  3980. if GetNextInstruction(hp1, hp2) and
  3981. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  3982. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3983. (taicpu(hp2).oper[0]^.val = 0) then
  3984. begin
  3985. Inc(CurrentRef.offset);
  3986. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  3987. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  3988. (taicpu(hp2).opsize = S_B) then
  3989. begin
  3990. RemoveInstruction(hp1);
  3991. RemoveInstruction(hp2);
  3992. first_mov.opsize := S_L;
  3993. if first_mov.oper[0]^.typ = top_reg then
  3994. begin
  3995. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  3996. { Reuse second_mov as a MOVZX instruction }
  3997. second_mov.opcode := A_MOVZX;
  3998. second_mov.opsize := S_BL;
  3999. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4000. second_mov.loadreg(1, FullReg);
  4001. first_mov.oper[0]^.reg := FullReg;
  4002. asml.Remove(second_mov);
  4003. asml.InsertBefore(second_mov, first_mov);
  4004. end
  4005. else
  4006. { It's a value }
  4007. begin
  4008. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4009. RemoveInstruction(second_mov);
  4010. end;
  4011. Result := True;
  4012. Exit;
  4013. end;
  4014. end;
  4015. S_W:
  4016. begin
  4017. RemoveInstruction(hp1);
  4018. first_mov.opsize := S_L;
  4019. if first_mov.oper[0]^.typ = top_reg then
  4020. begin
  4021. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4022. { Reuse second_mov as a MOVZX instruction }
  4023. second_mov.opcode := A_MOVZX;
  4024. second_mov.opsize := S_BL;
  4025. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4026. second_mov.loadreg(1, FullReg);
  4027. first_mov.oper[0]^.reg := FullReg;
  4028. asml.Remove(second_mov);
  4029. asml.InsertBefore(second_mov, first_mov);
  4030. end
  4031. else
  4032. { It's a value }
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4035. RemoveInstruction(second_mov);
  4036. end;
  4037. Result := True;
  4038. Exit;
  4039. end;
  4040. else
  4041. ;
  4042. end;
  4043. end;
  4044. end;
  4045. end;
  4046. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4047. { returns true if a "continue" should be done after this optimization }
  4048. var
  4049. hp1, hp2: tai;
  4050. begin
  4051. Result := false;
  4052. if MatchOpType(taicpu(p),top_ref) and
  4053. GetNextInstruction(p, hp1) and
  4054. (hp1.typ = ait_instruction) and
  4055. (((taicpu(hp1).opcode = A_FLD) and
  4056. (taicpu(p).opcode = A_FSTP)) or
  4057. ((taicpu(p).opcode = A_FISTP) and
  4058. (taicpu(hp1).opcode = A_FILD))) and
  4059. MatchOpType(taicpu(hp1),top_ref) and
  4060. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4061. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4062. begin
  4063. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4064. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4065. GetNextInstruction(hp1, hp2) and
  4066. (hp2.typ = ait_instruction) and
  4067. IsExitCode(hp2) and
  4068. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4069. not(assigned(current_procinfo.procdef.funcretsym) and
  4070. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4071. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4072. begin
  4073. RemoveInstruction(hp1);
  4074. RemoveCurrentP(p, hp2);
  4075. RemoveLastDeallocForFuncRes(p);
  4076. Result := true;
  4077. end
  4078. else
  4079. { we can do this only in fast math mode as fstp is rounding ...
  4080. ... still disabled as it breaks the compiler and/or rtl }
  4081. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4082. { ... or if another fstp equal to the first one follows }
  4083. (GetNextInstruction(hp1,hp2) and
  4084. (hp2.typ = ait_instruction) and
  4085. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4086. (taicpu(p).opsize=taicpu(hp2).opsize))
  4087. ) and
  4088. { fst can't store an extended/comp value }
  4089. (taicpu(p).opsize <> S_FX) and
  4090. (taicpu(p).opsize <> S_IQ) then
  4091. begin
  4092. if (taicpu(p).opcode = A_FSTP) then
  4093. taicpu(p).opcode := A_FST
  4094. else
  4095. taicpu(p).opcode := A_FIST;
  4096. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4097. RemoveInstruction(hp1);
  4098. end;
  4099. end;
  4100. end;
  4101. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4102. var
  4103. hp1, hp2: tai;
  4104. begin
  4105. result:=false;
  4106. if MatchOpType(taicpu(p),top_reg) and
  4107. GetNextInstruction(p, hp1) and
  4108. (hp1.typ = Ait_Instruction) and
  4109. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4110. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4111. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4112. { change to
  4113. fld reg fxxx reg,st
  4114. fxxxp st, st1 (hp1)
  4115. Remark: non commutative operations must be reversed!
  4116. }
  4117. begin
  4118. case taicpu(hp1).opcode Of
  4119. A_FMULP,A_FADDP,
  4120. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4121. begin
  4122. case taicpu(hp1).opcode Of
  4123. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4124. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4125. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4126. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4127. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4128. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4129. else
  4130. internalerror(2019050534);
  4131. end;
  4132. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4133. taicpu(hp1).oper[1]^.reg := NR_ST;
  4134. RemoveCurrentP(p, hp1);
  4135. Result:=true;
  4136. exit;
  4137. end;
  4138. else
  4139. ;
  4140. end;
  4141. end
  4142. else
  4143. if MatchOpType(taicpu(p),top_ref) and
  4144. GetNextInstruction(p, hp2) and
  4145. (hp2.typ = Ait_Instruction) and
  4146. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4147. (taicpu(p).opsize in [S_FS, S_FL]) and
  4148. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4149. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4150. if GetLastInstruction(p, hp1) and
  4151. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4152. MatchOpType(taicpu(hp1),top_ref) and
  4153. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4154. if ((taicpu(hp2).opcode = A_FMULP) or
  4155. (taicpu(hp2).opcode = A_FADDP)) then
  4156. { change to
  4157. fld/fst mem1 (hp1) fld/fst mem1
  4158. fld mem1 (p) fadd/
  4159. faddp/ fmul st, st
  4160. fmulp st, st1 (hp2) }
  4161. begin
  4162. RemoveCurrentP(p, hp1);
  4163. if (taicpu(hp2).opcode = A_FADDP) then
  4164. taicpu(hp2).opcode := A_FADD
  4165. else
  4166. taicpu(hp2).opcode := A_FMUL;
  4167. taicpu(hp2).oper[1]^.reg := NR_ST;
  4168. end
  4169. else
  4170. { change to
  4171. fld/fst mem1 (hp1) fld/fst mem1
  4172. fld mem1 (p) fld st}
  4173. begin
  4174. taicpu(p).changeopsize(S_FL);
  4175. taicpu(p).loadreg(0,NR_ST);
  4176. end
  4177. else
  4178. begin
  4179. case taicpu(hp2).opcode Of
  4180. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4181. { change to
  4182. fld/fst mem1 (hp1) fld/fst mem1
  4183. fld mem2 (p) fxxx mem2
  4184. fxxxp st, st1 (hp2) }
  4185. begin
  4186. case taicpu(hp2).opcode Of
  4187. A_FADDP: taicpu(p).opcode := A_FADD;
  4188. A_FMULP: taicpu(p).opcode := A_FMUL;
  4189. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4190. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4191. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4192. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4193. else
  4194. internalerror(2019050533);
  4195. end;
  4196. RemoveInstruction(hp2);
  4197. end
  4198. else
  4199. ;
  4200. end
  4201. end
  4202. end;
  4203. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4204. var
  4205. v: TCGInt;
  4206. hp1, hp2: tai;
  4207. FirstMatch: Boolean;
  4208. begin
  4209. Result:=false;
  4210. if taicpu(p).oper[0]^.typ = top_const then
  4211. begin
  4212. { Though GetNextInstruction can be factored out, it is an expensive
  4213. call, so delay calling it until we have first checked cheaper
  4214. conditions that are independent of it. }
  4215. if (taicpu(p).oper[0]^.val = 0) and
  4216. (taicpu(p).oper[1]^.typ = top_reg) and
  4217. GetNextInstruction(p, hp1) and
  4218. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  4219. begin
  4220. hp2 := p;
  4221. FirstMatch := True;
  4222. { When dealing with "cmp $0,%reg", only ZF and SF contain
  4223. anything meaningful once it's converted to "test %reg,%reg";
  4224. additionally, some jumps will always (or never) branch, so
  4225. evaluate every jump immediately following the
  4226. comparison, optimising the conditions if possible.
  4227. Similarly with SETcc... those that are always set to 0 or 1
  4228. are changed to MOV instructions }
  4229. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  4230. (
  4231. GetNextInstruction(hp2, hp1) and
  4232. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  4233. ) do
  4234. begin
  4235. FirstMatch := False;
  4236. case taicpu(hp1).condition of
  4237. C_B, C_C, C_NAE, C_O:
  4238. { For B/NAE:
  4239. Will never branch since an unsigned integer can never be below zero
  4240. For C/O:
  4241. Result cannot overflow because 0 is being subtracted
  4242. }
  4243. begin
  4244. if taicpu(hp1).opcode = A_Jcc then
  4245. begin
  4246. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  4247. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  4248. RemoveInstruction(hp1);
  4249. { Since hp1 was deleted, hp2 must not be updated }
  4250. Continue;
  4251. end
  4252. else
  4253. begin
  4254. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  4255. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  4256. taicpu(hp1).opcode := A_MOV;
  4257. taicpu(hp1).ops := 2;
  4258. taicpu(hp1).condition := C_None;
  4259. taicpu(hp1).opsize := S_B;
  4260. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4261. taicpu(hp1).loadconst(0, 0);
  4262. end;
  4263. end;
  4264. C_BE, C_NA:
  4265. begin
  4266. { Will only branch if equal to zero }
  4267. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  4268. taicpu(hp1).condition := C_E;
  4269. end;
  4270. C_A, C_NBE:
  4271. begin
  4272. { Will only branch if not equal to zero }
  4273. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  4274. taicpu(hp1).condition := C_NE;
  4275. end;
  4276. C_AE, C_NB, C_NC, C_NO:
  4277. begin
  4278. { Will always branch }
  4279. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  4280. if taicpu(hp1).opcode = A_Jcc then
  4281. begin
  4282. MakeUnconditional(taicpu(hp1));
  4283. { Any jumps/set that follow will now be dead code }
  4284. RemoveDeadCodeAfterJump(taicpu(hp1));
  4285. Break;
  4286. end
  4287. else
  4288. begin
  4289. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  4290. taicpu(hp1).opcode := A_MOV;
  4291. taicpu(hp1).ops := 2;
  4292. taicpu(hp1).condition := C_None;
  4293. taicpu(hp1).opsize := S_B;
  4294. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4295. taicpu(hp1).loadconst(0, 1);
  4296. end;
  4297. end;
  4298. C_None:
  4299. InternalError(2020012201);
  4300. C_P, C_PE, C_NP, C_PO:
  4301. { We can't handle parity checks and they should never be generated
  4302. after a general-purpose CMP (it's used in some floating-point
  4303. comparisons that don't use CMP) }
  4304. InternalError(2020012202);
  4305. else
  4306. { Zero/Equality, Sign, their complements and all of the
  4307. signed comparisons do not need to be converted };
  4308. end;
  4309. hp2 := hp1;
  4310. end;
  4311. { Convert the instruction to a TEST }
  4312. taicpu(p).opcode := A_TEST;
  4313. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4314. Result := True;
  4315. Exit;
  4316. end
  4317. else if (taicpu(p).oper[0]^.val = 1) and
  4318. GetNextInstruction(p, hp1) and
  4319. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4320. (taicpu(hp1).condition in [C_L, C_NGE]) then
  4321. begin
  4322. { Convert; To:
  4323. cmp $1,r/m cmp $0,r/m
  4324. jl @lbl jle @lbl
  4325. }
  4326. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  4327. taicpu(p).oper[0]^.val := 0;
  4328. taicpu(hp1).condition := C_LE;
  4329. { If the instruction is now "cmp $0,%reg", convert it to a
  4330. TEST (and effectively do the work of the "cmp $0,%reg" in
  4331. the block above)
  4332. If it's a reference, we can get away with not setting
  4333. Result to True because he haven't evaluated the jump
  4334. in this pass yet.
  4335. }
  4336. if (taicpu(p).oper[1]^.typ = top_reg) then
  4337. begin
  4338. taicpu(p).opcode := A_TEST;
  4339. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4340. Result := True;
  4341. end;
  4342. Exit;
  4343. end
  4344. else if (taicpu(p).oper[1]^.typ = top_reg) then
  4345. begin
  4346. { cmp register,$8000 neg register
  4347. je target --> jo target
  4348. .... only if register is deallocated before jump.}
  4349. case Taicpu(p).opsize of
  4350. S_B: v:=$80;
  4351. S_W: v:=$8000;
  4352. S_L: v:=qword($80000000);
  4353. { S_Q will never happen: cmp with 64 bit constants is not possible }
  4354. S_Q:
  4355. Exit;
  4356. else
  4357. internalerror(2013112905);
  4358. end;
  4359. if (taicpu(p).oper[0]^.val=v) and
  4360. GetNextInstruction(p, hp1) and
  4361. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4362. (Taicpu(hp1).condition in [C_E,C_NE]) then
  4363. begin
  4364. TransferUsedRegs(TmpUsedRegs);
  4365. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  4366. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  4367. begin
  4368. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  4369. Taicpu(p).opcode:=A_NEG;
  4370. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  4371. Taicpu(p).clearop(1);
  4372. Taicpu(p).ops:=1;
  4373. if Taicpu(hp1).condition=C_E then
  4374. Taicpu(hp1).condition:=C_O
  4375. else
  4376. Taicpu(hp1).condition:=C_NO;
  4377. Result:=true;
  4378. exit;
  4379. end;
  4380. end;
  4381. end;
  4382. end;
  4383. if (taicpu(p).oper[1]^.typ = top_reg) and
  4384. GetNextInstruction(p, hp1) and
  4385. MatchInstruction(hp1,A_MOV,[]) and
  4386. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  4387. (
  4388. (taicpu(p).oper[0]^.typ <> top_reg) or
  4389. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  4390. ) then
  4391. begin
  4392. { If we have something like:
  4393. cmp ###,%reg1
  4394. mov 0,%reg2
  4395. And no registers are shared, move the MOV command to before the
  4396. comparison as this means it can be optimised without worrying
  4397. about the FLAGS register. (This combination is generated by
  4398. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  4399. }
  4400. SwapMovCmp(p, hp1);
  4401. Result := True;
  4402. Exit;
  4403. end;
  4404. end;
  4405. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  4406. var
  4407. hp1: tai;
  4408. begin
  4409. {
  4410. remove the second (v)pxor from
  4411. pxor reg,reg
  4412. ...
  4413. pxor reg,reg
  4414. }
  4415. Result:=false;
  4416. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4417. MatchOpType(taicpu(p),top_reg,top_reg) and
  4418. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4419. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4420. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4421. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  4422. begin
  4423. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  4424. RemoveInstruction(hp1);
  4425. Result:=true;
  4426. Exit;
  4427. end
  4428. {
  4429. replace
  4430. pxor reg1,reg1
  4431. movapd/s reg1,reg2
  4432. dealloc reg1
  4433. by
  4434. pxor reg2,reg2
  4435. }
  4436. else if GetNextInstruction(p,hp1) and
  4437. { we mix single and double opperations here because we assume that the compiler
  4438. generates vmovapd only after double operations and vmovaps only after single operations }
  4439. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4440. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4441. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4442. (taicpu(p).oper[0]^.typ=top_reg) then
  4443. begin
  4444. TransferUsedRegs(TmpUsedRegs);
  4445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4446. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4447. begin
  4448. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  4449. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4450. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  4451. RemoveInstruction(hp1);
  4452. result:=true;
  4453. end;
  4454. end;
  4455. end;
  4456. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  4457. var
  4458. hp1: tai;
  4459. begin
  4460. {
  4461. remove the second (v)pxor from
  4462. (v)pxor reg,reg
  4463. ...
  4464. (v)pxor reg,reg
  4465. }
  4466. Result:=false;
  4467. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4468. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4469. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4470. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4471. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4472. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4473. begin
  4474. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4475. RemoveInstruction(hp1);
  4476. Result:=true;
  4477. Exit;
  4478. end
  4479. else
  4480. Result:=OptPass1VOP(p);
  4481. end;
  4482. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4483. var
  4484. hp1 : tai;
  4485. begin
  4486. result:=false;
  4487. { replace
  4488. IMul const,%mreg1,%mreg2
  4489. Mov %reg2,%mreg3
  4490. dealloc %mreg3
  4491. by
  4492. Imul const,%mreg1,%mreg23
  4493. }
  4494. if (taicpu(p).ops=3) and
  4495. GetNextInstruction(p,hp1) and
  4496. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4497. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4498. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4499. begin
  4500. TransferUsedRegs(TmpUsedRegs);
  4501. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4502. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4503. begin
  4504. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4505. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  4506. RemoveInstruction(hp1);
  4507. result:=true;
  4508. end;
  4509. end;
  4510. end;
  4511. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  4512. var
  4513. hp1 : tai;
  4514. begin
  4515. result:=false;
  4516. { replace
  4517. IMul %reg0,%reg1,%reg2
  4518. Mov %reg2,%reg3
  4519. dealloc %reg2
  4520. by
  4521. Imul %reg0,%reg1,%reg3
  4522. }
  4523. if GetNextInstruction(p,hp1) and
  4524. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4525. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4526. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4527. begin
  4528. TransferUsedRegs(TmpUsedRegs);
  4529. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4530. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4531. begin
  4532. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4533. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  4534. RemoveInstruction(hp1);
  4535. result:=true;
  4536. end;
  4537. end;
  4538. end;
  4539. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  4540. var
  4541. hp1, hp2, hp3, hp4, hp5: tai;
  4542. ThisReg: TRegister;
  4543. begin
  4544. Result := False;
  4545. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  4546. Exit;
  4547. {
  4548. convert
  4549. j<c> .L1
  4550. mov 1,reg
  4551. jmp .L2
  4552. .L1
  4553. mov 0,reg
  4554. .L2
  4555. into
  4556. mov 0,reg
  4557. set<not(c)> reg
  4558. take care of alignment and that the mov 0,reg is not converted into a xor as this
  4559. would destroy the flag contents
  4560. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  4561. executed at the same time as a previous comparison.
  4562. set<not(c)> reg
  4563. movzx reg, reg
  4564. }
  4565. if MatchInstruction(hp1,A_MOV,[]) and
  4566. (taicpu(hp1).oper[0]^.typ = top_const) and
  4567. (
  4568. (
  4569. (taicpu(hp1).oper[1]^.typ = top_reg)
  4570. {$ifdef i386}
  4571. { Under i386, ESI, EDI, EBP and ESP
  4572. don't have an 8-bit representation }
  4573. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  4574. {$endif i386}
  4575. ) or (
  4576. {$ifdef i386}
  4577. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  4578. {$endif i386}
  4579. (taicpu(hp1).opsize = S_B)
  4580. )
  4581. ) and
  4582. GetNextInstruction(hp1,hp2) and
  4583. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  4584. GetNextInstruction(hp2,hp3) and
  4585. SkipAligns(hp3, hp3) and
  4586. (hp3.typ=ait_label) and
  4587. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  4588. GetNextInstruction(hp3,hp4) and
  4589. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  4590. (taicpu(hp4).oper[0]^.typ = top_const) and
  4591. (
  4592. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  4593. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  4594. ) and
  4595. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  4596. GetNextInstruction(hp4,hp5) and
  4597. SkipAligns(hp5, hp5) and
  4598. (hp5.typ=ait_label) and
  4599. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  4600. begin
  4601. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4602. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  4603. tai_label(hp3).labsym.DecRefs;
  4604. { If this isn't the only reference to the middle label, we can
  4605. still make a saving - only that the first jump and everything
  4606. that follows will remain. }
  4607. if (tai_label(hp3).labsym.getrefs = 0) then
  4608. begin
  4609. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4610. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  4611. else
  4612. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  4613. { remove jump, first label and second MOV (also catching any aligns) }
  4614. repeat
  4615. if not GetNextInstruction(hp2, hp3) then
  4616. InternalError(2021040810);
  4617. RemoveInstruction(hp2);
  4618. hp2 := hp3;
  4619. until hp2 = hp5;
  4620. { Don't decrement reference count before the removal loop
  4621. above, otherwise GetNextInstruction won't stop on the
  4622. the label }
  4623. tai_label(hp5).labsym.DecRefs;
  4624. end
  4625. else
  4626. begin
  4627. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4628. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  4629. else
  4630. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  4631. end;
  4632. taicpu(p).opcode:=A_SETcc;
  4633. taicpu(p).opsize:=S_B;
  4634. taicpu(p).is_jmp:=False;
  4635. if taicpu(hp1).opsize=S_B then
  4636. begin
  4637. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  4638. RemoveInstruction(hp1);
  4639. end
  4640. else
  4641. begin
  4642. { Will be a register because the size can't be S_B otherwise }
  4643. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  4644. taicpu(p).loadreg(0, ThisReg);
  4645. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  4646. begin
  4647. case taicpu(hp1).opsize of
  4648. S_W:
  4649. taicpu(hp1).opsize := S_BW;
  4650. S_L:
  4651. taicpu(hp1).opsize := S_BL;
  4652. {$ifdef x86_64}
  4653. S_Q:
  4654. begin
  4655. taicpu(hp1).opsize := S_BL;
  4656. { Change the destination register to 32-bit }
  4657. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  4658. end;
  4659. {$endif x86_64}
  4660. else
  4661. InternalError(2021040820);
  4662. end;
  4663. taicpu(hp1).opcode := A_MOVZX;
  4664. taicpu(hp1).loadreg(0, ThisReg);
  4665. end
  4666. else
  4667. begin
  4668. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  4669. { hp1 is already a MOV instruction with the correct register }
  4670. taicpu(hp1).loadconst(0, 0);
  4671. { Inserting it right before p will guarantee that the flags are also tracked }
  4672. asml.Remove(hp1);
  4673. asml.InsertBefore(hp1, p);
  4674. end;
  4675. end;
  4676. Result:=true;
  4677. exit;
  4678. end
  4679. end;
  4680. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  4681. var
  4682. hp2, hp3, first_assignment: tai;
  4683. IncCount, OperIdx: Integer;
  4684. OrigLabel: TAsmLabel;
  4685. begin
  4686. Count := 0;
  4687. Result := False;
  4688. first_assignment := nil;
  4689. if (LoopCount >= 20) then
  4690. begin
  4691. { Guard against infinite loops }
  4692. Exit;
  4693. end;
  4694. if (taicpu(p).oper[0]^.typ <> top_ref) or
  4695. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  4696. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  4697. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  4698. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  4699. Exit;
  4700. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  4701. {
  4702. change
  4703. jmp .L1
  4704. ...
  4705. .L1:
  4706. mov ##, ## ( multiple movs possible )
  4707. jmp/ret
  4708. into
  4709. mov ##, ##
  4710. jmp/ret
  4711. }
  4712. if not Assigned(hp1) then
  4713. begin
  4714. hp1 := GetLabelWithSym(OrigLabel);
  4715. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  4716. Exit;
  4717. end;
  4718. hp2 := hp1;
  4719. while Assigned(hp2) do
  4720. begin
  4721. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  4722. SkipLabels(hp2,hp2);
  4723. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  4724. Break;
  4725. case taicpu(hp2).opcode of
  4726. A_MOVSS:
  4727. begin
  4728. if taicpu(hp2).ops = 0 then
  4729. { Wrong MOVSS }
  4730. Break;
  4731. Inc(Count);
  4732. if Count >= 5 then
  4733. { Too many to be worthwhile }
  4734. Break;
  4735. GetNextInstruction(hp2, hp2);
  4736. Continue;
  4737. end;
  4738. A_MOV,
  4739. A_MOVD,
  4740. A_MOVQ,
  4741. A_MOVSX,
  4742. {$ifdef x86_64}
  4743. A_MOVSXD,
  4744. {$endif x86_64}
  4745. A_MOVZX,
  4746. A_MOVAPS,
  4747. A_MOVUPS,
  4748. A_MOVSD,
  4749. A_MOVAPD,
  4750. A_MOVUPD,
  4751. A_MOVDQA,
  4752. A_MOVDQU,
  4753. A_VMOVSS,
  4754. A_VMOVAPS,
  4755. A_VMOVUPS,
  4756. A_VMOVSD,
  4757. A_VMOVAPD,
  4758. A_VMOVUPD,
  4759. A_VMOVDQA,
  4760. A_VMOVDQU:
  4761. begin
  4762. Inc(Count);
  4763. if Count >= 5 then
  4764. { Too many to be worthwhile }
  4765. Break;
  4766. GetNextInstruction(hp2, hp2);
  4767. Continue;
  4768. end;
  4769. A_JMP:
  4770. begin
  4771. { Guard against infinite loops }
  4772. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  4773. Exit;
  4774. { Analyse this jump first in case it also duplicates assignments }
  4775. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  4776. begin
  4777. { Something did change! }
  4778. Result := True;
  4779. Inc(Count, IncCount);
  4780. if Count >= 5 then
  4781. begin
  4782. { Too many to be worthwhile }
  4783. Exit;
  4784. end;
  4785. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  4786. Break;
  4787. end;
  4788. Result := True;
  4789. Break;
  4790. end;
  4791. A_RET:
  4792. begin
  4793. Result := True;
  4794. Break;
  4795. end;
  4796. else
  4797. Break;
  4798. end;
  4799. end;
  4800. if Result then
  4801. begin
  4802. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  4803. if Count = 0 then
  4804. begin
  4805. Result := False;
  4806. Exit;
  4807. end;
  4808. hp3 := p;
  4809. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  4810. while True do
  4811. begin
  4812. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  4813. SkipLabels(hp1,hp1);
  4814. if (hp1.typ <> ait_instruction) then
  4815. InternalError(2021040720);
  4816. case taicpu(hp1).opcode of
  4817. A_JMP:
  4818. begin
  4819. { Change the original jump to the new destination }
  4820. OrigLabel.decrefs;
  4821. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  4822. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  4823. { Set p to the first duplicated assignment so it can get optimised if needs be }
  4824. if not Assigned(first_assignment) then
  4825. InternalError(2021040810)
  4826. else
  4827. p := first_assignment;
  4828. Exit;
  4829. end;
  4830. A_RET:
  4831. begin
  4832. { Now change the jump into a RET instruction }
  4833. ConvertJumpToRET(p, hp1);
  4834. { Set p to the first duplicated assignment so it can get optimised if needs be }
  4835. if not Assigned(first_assignment) then
  4836. InternalError(2021040811)
  4837. else
  4838. p := first_assignment;
  4839. Exit;
  4840. end;
  4841. else
  4842. begin
  4843. { Duplicate the MOV instruction }
  4844. hp3:=tai(hp1.getcopy);
  4845. if first_assignment = nil then
  4846. first_assignment := hp3;
  4847. asml.InsertBefore(hp3, p);
  4848. { Make sure the compiler knows about any final registers written here }
  4849. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  4850. with taicpu(hp3).oper[OperIdx]^ do
  4851. begin
  4852. case typ of
  4853. top_ref:
  4854. begin
  4855. if (ref^.base <> NR_NO) and
  4856. (getsupreg(ref^.base) <> RS_ESP) and
  4857. (getsupreg(ref^.base) <> RS_EBP)
  4858. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  4859. then
  4860. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  4861. if (ref^.index <> NR_NO) and
  4862. (getsupreg(ref^.index) <> RS_ESP) and
  4863. (getsupreg(ref^.index) <> RS_EBP)
  4864. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  4865. (ref^.index <> ref^.base) then
  4866. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  4867. end;
  4868. top_reg:
  4869. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  4870. else
  4871. ;
  4872. end;
  4873. end;
  4874. end;
  4875. end;
  4876. if not GetNextInstruction(hp1, hp1) then
  4877. { Should have dropped out earlier }
  4878. InternalError(2021040710);
  4879. end;
  4880. end;
  4881. end;
  4882. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  4883. var
  4884. hp2: tai;
  4885. X: Integer;
  4886. begin
  4887. asml.Remove(hp1);
  4888. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  4889. if not GetLastInstruction(p, hp2) then
  4890. asml.InsertBefore(hp1, p)
  4891. else
  4892. asml.InsertAfter(hp1, hp2);
  4893. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  4894. for X := 0 to 1 do
  4895. case taicpu(hp1).oper[X]^.typ of
  4896. top_reg:
  4897. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  4898. top_ref:
  4899. begin
  4900. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  4901. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  4902. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  4903. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  4904. end;
  4905. else
  4906. ;
  4907. end;
  4908. end;
  4909. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  4910. function IsXCHGAcceptable: Boolean; inline;
  4911. begin
  4912. { Always accept if optimising for size }
  4913. Result := (cs_opt_size in current_settings.optimizerswitches) or
  4914. (
  4915. {$ifdef x86_64}
  4916. { XCHG takes 3 cycles on AMD Athlon64 }
  4917. (current_settings.optimizecputype >= cpu_core_i)
  4918. {$else x86_64}
  4919. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  4920. than 3, so it becomes a saving compared to three MOVs with two of
  4921. them able to execute simultaneously. [Kit] }
  4922. (current_settings.optimizecputype >= cpu_PentiumM)
  4923. {$endif x86_64}
  4924. );
  4925. end;
  4926. var
  4927. NewRef: TReference;
  4928. hp1, hp2, hp3, hp4: Tai;
  4929. {$ifndef x86_64}
  4930. OperIdx: Integer;
  4931. {$endif x86_64}
  4932. NewInstr : Taicpu;
  4933. NewAligh : Tai_align;
  4934. DestLabel: TAsmLabel;
  4935. begin
  4936. Result:=false;
  4937. { This optimisation adds an instruction, so only do it for speed }
  4938. if not (cs_opt_size in current_settings.optimizerswitches) and
  4939. MatchOpType(taicpu(p), top_const, top_reg) and
  4940. (taicpu(p).oper[0]^.val = 0) then
  4941. begin
  4942. { To avoid compiler warning }
  4943. DestLabel := nil;
  4944. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  4945. InternalError(2021040750);
  4946. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  4947. Exit;
  4948. case hp1.typ of
  4949. ait_label:
  4950. begin
  4951. { Change:
  4952. mov $0,%reg mov $0,%reg
  4953. @Lbl1: @Lbl1:
  4954. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  4955. je @Lbl2 jne @Lbl2
  4956. To: To:
  4957. mov $0,%reg mov $0,%reg
  4958. jmp @Lbl2 jmp @Lbl3
  4959. (align) (align)
  4960. @Lbl1: @Lbl1:
  4961. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  4962. je @Lbl2 je @Lbl2
  4963. @Lbl3: <-- Only if label exists
  4964. (Not if it's optimised for size)
  4965. }
  4966. if not GetNextInstruction(hp1, hp2) then
  4967. Exit;
  4968. if not (cs_opt_size in current_settings.optimizerswitches) and
  4969. (hp2.typ = ait_instruction) and
  4970. (
  4971. { Register sizes must exactly match }
  4972. (
  4973. (taicpu(hp2).opcode = A_CMP) and
  4974. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  4975. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  4976. ) or (
  4977. (taicpu(hp2).opcode = A_TEST) and
  4978. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  4979. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  4980. )
  4981. ) and GetNextInstruction(hp2, hp3) and
  4982. (hp3.typ = ait_instruction) and
  4983. (taicpu(hp3).opcode = A_JCC) and
  4984. (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
  4985. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  4986. begin
  4987. { Check condition of jump }
  4988. { Always true? }
  4989. if condition_in(C_E, taicpu(hp3).condition) then
  4990. begin
  4991. { Copy label symbol and obtain matching label entry for the
  4992. conditional jump, as this will be our destination}
  4993. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  4994. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  4995. Result := True;
  4996. end
  4997. { Always false? }
  4998. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  4999. begin
  5000. { This is only worth it if there's a jump to take }
  5001. case hp2.typ of
  5002. ait_instruction:
  5003. begin
  5004. if taicpu(hp2).opcode = A_JMP then
  5005. begin
  5006. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5007. { An unconditional jump follows the conditional jump which will always be false,
  5008. so use this jump's destination for the new jump }
  5009. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5010. Result := True;
  5011. end
  5012. else if taicpu(hp2).opcode = A_JCC then
  5013. begin
  5014. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5015. if condition_in(C_E, taicpu(hp2).condition) then
  5016. begin
  5017. { A second conditional jump follows the conditional jump which will always be false,
  5018. while the second jump is always True, so use this jump's destination for the new jump }
  5019. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5020. Result := True;
  5021. end;
  5022. { Don't risk it if the jump isn't always true (Result remains False) }
  5023. end;
  5024. end;
  5025. else
  5026. { If anything else don't optimise };
  5027. end;
  5028. end;
  5029. if Result then
  5030. begin
  5031. { Just so we have something to insert as a paremeter}
  5032. reference_reset(NewRef, 1, []);
  5033. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5034. { Now actually load the correct parameter }
  5035. NewInstr.loadsymbol(0, DestLabel, 0);
  5036. { Get instruction before original label (may not be p under -O3) }
  5037. if not GetLastInstruction(hp1, hp2) then
  5038. { Shouldn't fail here }
  5039. InternalError(2021040701);
  5040. DestLabel.increfs;
  5041. AsmL.InsertAfter(NewInstr, hp2);
  5042. { Add new alignment field }
  5043. (* AsmL.InsertAfter(
  5044. cai_align.create_max(
  5045. current_settings.alignment.jumpalign,
  5046. current_settings.alignment.jumpalignskipmax
  5047. ),
  5048. NewInstr
  5049. ); *)
  5050. end;
  5051. Exit;
  5052. end;
  5053. end;
  5054. else
  5055. ;
  5056. end;
  5057. end;
  5058. if not GetNextInstruction(p, hp1) then
  5059. Exit;
  5060. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5061. begin
  5062. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5063. further, but we can't just put this jump optimisation in pass 1
  5064. because it tends to perform worse when conditional jumps are
  5065. nearby (e.g. when converting CMOV instructions). [Kit] }
  5066. if OptPass2JMP(hp1) then
  5067. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5068. Result := OptPass1MOV(p)
  5069. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5070. returned True and the instruction is still a MOV, thus checking
  5071. the optimisations below }
  5072. { If OptPass2JMP returned False, no optimisations were done to
  5073. the jump and there are no further optimisations that can be done
  5074. to the MOV instruction on this pass }
  5075. end
  5076. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5077. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5078. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5079. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5080. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5081. { be lazy, checking separately for sub would be slightly better }
  5082. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5083. begin
  5084. { Change:
  5085. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5086. addl/q $x,%reg2 subl/q $x,%reg2
  5087. To:
  5088. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5089. }
  5090. TransferUsedRegs(TmpUsedRegs);
  5091. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5092. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5093. if not GetNextInstruction(hp1, hp2) or
  5094. (
  5095. { The FLAGS register isn't always tracked properly, so do not
  5096. perform this optimisation if a conditional statement follows }
  5097. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5098. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5099. ) then
  5100. begin
  5101. reference_reset(NewRef, 1, []);
  5102. NewRef.base := taicpu(p).oper[0]^.reg;
  5103. NewRef.scalefactor := 1;
  5104. if taicpu(hp1).opcode = A_ADD then
  5105. begin
  5106. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5107. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5108. end
  5109. else
  5110. begin
  5111. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5112. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5113. end;
  5114. taicpu(p).opcode := A_LEA;
  5115. taicpu(p).loadref(0, NewRef);
  5116. RemoveInstruction(hp1);
  5117. Result := True;
  5118. Exit;
  5119. end;
  5120. end
  5121. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5122. {$ifdef x86_64}
  5123. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5124. {$else x86_64}
  5125. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5126. {$endif x86_64}
  5127. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5128. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5129. { mov reg1, reg2 mov reg1, reg2
  5130. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5131. begin
  5132. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5133. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5134. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5135. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5136. TransferUsedRegs(TmpUsedRegs);
  5137. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5138. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5139. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5140. then
  5141. begin
  5142. RemoveCurrentP(p, hp1);
  5143. Result:=true;
  5144. end;
  5145. exit;
  5146. end
  5147. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5148. IsXCHGAcceptable and
  5149. { XCHG doesn't support 8-byte registers }
  5150. (taicpu(p).opsize <> S_B) and
  5151. MatchInstruction(hp1, A_MOV, []) and
  5152. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5153. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5154. GetNextInstruction(hp1, hp2) and
  5155. MatchInstruction(hp2, A_MOV, []) and
  5156. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5157. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5158. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5159. begin
  5160. { mov %reg1,%reg2
  5161. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5162. mov %reg2,%reg3
  5163. (%reg2 not used afterwards)
  5164. Note that xchg takes 3 cycles to execute, and generally mov's take
  5165. only one cycle apiece, but the first two mov's can be executed in
  5166. parallel, only taking 2 cycles overall. Older processors should
  5167. therefore only optimise for size. [Kit]
  5168. }
  5169. TransferUsedRegs(TmpUsedRegs);
  5170. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5171. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5172. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5173. begin
  5174. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5175. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5176. taicpu(hp1).opcode := A_XCHG;
  5177. RemoveCurrentP(p, hp1);
  5178. RemoveInstruction(hp2);
  5179. Result := True;
  5180. Exit;
  5181. end;
  5182. end
  5183. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5184. MatchInstruction(hp1, A_SAR, []) then
  5185. begin
  5186. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5187. begin
  5188. { the use of %edx also covers the opsize being S_L }
  5189. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5190. begin
  5191. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5192. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5193. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5194. begin
  5195. { Change:
  5196. movl %eax,%edx
  5197. sarl $31,%edx
  5198. To:
  5199. cltd
  5200. }
  5201. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5202. RemoveInstruction(hp1);
  5203. taicpu(p).opcode := A_CDQ;
  5204. taicpu(p).opsize := S_NO;
  5205. taicpu(p).clearop(1);
  5206. taicpu(p).clearop(0);
  5207. taicpu(p).ops:=0;
  5208. Result := True;
  5209. end
  5210. else if (cs_opt_size in current_settings.optimizerswitches) and
  5211. (taicpu(p).oper[0]^.reg = NR_EDX) and
  5212. (taicpu(p).oper[1]^.reg = NR_EAX) then
  5213. begin
  5214. { Change:
  5215. movl %edx,%eax
  5216. sarl $31,%edx
  5217. To:
  5218. movl %edx,%eax
  5219. cltd
  5220. Note that this creates a dependency between the two instructions,
  5221. so only perform if optimising for size.
  5222. }
  5223. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  5224. taicpu(hp1).opcode := A_CDQ;
  5225. taicpu(hp1).opsize := S_NO;
  5226. taicpu(hp1).clearop(1);
  5227. taicpu(hp1).clearop(0);
  5228. taicpu(hp1).ops:=0;
  5229. end;
  5230. {$ifndef x86_64}
  5231. end
  5232. { Don't bother if CMOV is supported, because a more optimal
  5233. sequence would have been generated for the Abs() intrinsic }
  5234. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  5235. { the use of %eax also covers the opsize being S_L }
  5236. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  5237. (taicpu(p).oper[0]^.reg = NR_EAX) and
  5238. (taicpu(p).oper[1]^.reg = NR_EDX) and
  5239. GetNextInstruction(hp1, hp2) and
  5240. MatchInstruction(hp2, A_XOR, [S_L]) and
  5241. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  5242. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  5243. GetNextInstruction(hp2, hp3) and
  5244. MatchInstruction(hp3, A_SUB, [S_L]) and
  5245. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  5246. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  5247. begin
  5248. { Change:
  5249. movl %eax,%edx
  5250. sarl $31,%eax
  5251. xorl %eax,%edx
  5252. subl %eax,%edx
  5253. (Instruction that uses %edx)
  5254. (%eax deallocated)
  5255. (%edx deallocated)
  5256. To:
  5257. cltd
  5258. xorl %edx,%eax <-- Note the registers have swapped
  5259. subl %edx,%eax
  5260. (Instruction that uses %eax) <-- %eax rather than %edx
  5261. }
  5262. TransferUsedRegs(TmpUsedRegs);
  5263. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5264. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5265. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5266. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  5267. begin
  5268. if GetNextInstruction(hp3, hp4) and
  5269. not RegModifiedByInstruction(NR_EDX, hp4) and
  5270. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  5271. begin
  5272. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  5273. taicpu(p).opcode := A_CDQ;
  5274. taicpu(p).clearop(1);
  5275. taicpu(p).clearop(0);
  5276. taicpu(p).ops:=0;
  5277. RemoveInstruction(hp1);
  5278. taicpu(hp2).loadreg(0, NR_EDX);
  5279. taicpu(hp2).loadreg(1, NR_EAX);
  5280. taicpu(hp3).loadreg(0, NR_EDX);
  5281. taicpu(hp3).loadreg(1, NR_EAX);
  5282. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  5283. { Convert references in the following instruction (hp4) from %edx to %eax }
  5284. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  5285. with taicpu(hp4).oper[OperIdx]^ do
  5286. case typ of
  5287. top_reg:
  5288. if getsupreg(reg) = RS_EDX then
  5289. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5290. top_ref:
  5291. begin
  5292. if getsupreg(reg) = RS_EDX then
  5293. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5294. if getsupreg(reg) = RS_EDX then
  5295. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5296. end;
  5297. else
  5298. ;
  5299. end;
  5300. end;
  5301. end;
  5302. {$else x86_64}
  5303. end;
  5304. end
  5305. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  5306. { the use of %rdx also covers the opsize being S_Q }
  5307. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  5308. begin
  5309. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  5310. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  5311. (taicpu(p).oper[1]^.reg = NR_RDX) then
  5312. begin
  5313. { Change:
  5314. movq %rax,%rdx
  5315. sarq $63,%rdx
  5316. To:
  5317. cqto
  5318. }
  5319. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  5320. RemoveInstruction(hp1);
  5321. taicpu(p).opcode := A_CQO;
  5322. taicpu(p).opsize := S_NO;
  5323. taicpu(p).clearop(1);
  5324. taicpu(p).clearop(0);
  5325. taicpu(p).ops:=0;
  5326. Result := True;
  5327. end
  5328. else if (cs_opt_size in current_settings.optimizerswitches) and
  5329. (taicpu(p).oper[0]^.reg = NR_RDX) and
  5330. (taicpu(p).oper[1]^.reg = NR_RAX) then
  5331. begin
  5332. { Change:
  5333. movq %rdx,%rax
  5334. sarq $63,%rdx
  5335. To:
  5336. movq %rdx,%rax
  5337. cqto
  5338. Note that this creates a dependency between the two instructions,
  5339. so only perform if optimising for size.
  5340. }
  5341. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  5342. taicpu(hp1).opcode := A_CQO;
  5343. taicpu(hp1).opsize := S_NO;
  5344. taicpu(hp1).clearop(1);
  5345. taicpu(hp1).clearop(0);
  5346. taicpu(hp1).ops:=0;
  5347. {$endif x86_64}
  5348. end;
  5349. end;
  5350. end
  5351. else if MatchInstruction(hp1, A_MOV, []) and
  5352. (taicpu(hp1).oper[1]^.typ = top_reg) then
  5353. { Though "GetNextInstruction" could be factored out, along with
  5354. the instructions that depend on hp2, it is an expensive call that
  5355. should be delayed for as long as possible, hence we do cheaper
  5356. checks first that are likely to be False. [Kit] }
  5357. begin
  5358. if (
  5359. (
  5360. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  5361. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  5362. (
  5363. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5364. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  5365. )
  5366. ) or
  5367. (
  5368. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  5369. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  5370. (
  5371. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5372. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  5373. )
  5374. )
  5375. ) and
  5376. GetNextInstruction(hp1, hp2) and
  5377. MatchInstruction(hp2, A_SAR, []) and
  5378. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  5379. begin
  5380. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  5381. begin
  5382. { Change:
  5383. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  5384. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  5385. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  5386. To:
  5387. movl r/m,%eax <- Note the change in register
  5388. cltd
  5389. }
  5390. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  5391. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  5392. taicpu(p).loadreg(1, NR_EAX);
  5393. taicpu(hp1).opcode := A_CDQ;
  5394. taicpu(hp1).clearop(1);
  5395. taicpu(hp1).clearop(0);
  5396. taicpu(hp1).ops:=0;
  5397. RemoveInstruction(hp2);
  5398. (*
  5399. {$ifdef x86_64}
  5400. end
  5401. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  5402. { This code sequence does not get generated - however it might become useful
  5403. if and when 128-bit signed integer types make an appearance, so the code
  5404. is kept here for when it is eventually needed. [Kit] }
  5405. (
  5406. (
  5407. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  5408. (
  5409. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5410. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  5411. )
  5412. ) or
  5413. (
  5414. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  5415. (
  5416. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5417. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  5418. )
  5419. )
  5420. ) and
  5421. GetNextInstruction(hp1, hp2) and
  5422. MatchInstruction(hp2, A_SAR, [S_Q]) and
  5423. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  5424. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  5425. begin
  5426. { Change:
  5427. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  5428. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  5429. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  5430. To:
  5431. movq r/m,%rax <- Note the change in register
  5432. cqto
  5433. }
  5434. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  5435. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  5436. taicpu(p).loadreg(1, NR_RAX);
  5437. taicpu(hp1).opcode := A_CQO;
  5438. taicpu(hp1).clearop(1);
  5439. taicpu(hp1).clearop(0);
  5440. taicpu(hp1).ops:=0;
  5441. RemoveInstruction(hp2);
  5442. {$endif x86_64}
  5443. *)
  5444. end;
  5445. end;
  5446. {$ifdef x86_64}
  5447. end
  5448. else if (taicpu(p).opsize = S_L) and
  5449. (taicpu(p).oper[1]^.typ = top_reg) and
  5450. (
  5451. MatchInstruction(hp1, A_MOV,[]) and
  5452. (taicpu(hp1).opsize = S_L) and
  5453. (taicpu(hp1).oper[1]^.typ = top_reg)
  5454. ) and (
  5455. GetNextInstruction(hp1, hp2) and
  5456. (tai(hp2).typ=ait_instruction) and
  5457. (taicpu(hp2).opsize = S_Q) and
  5458. (
  5459. (
  5460. MatchInstruction(hp2, A_ADD,[]) and
  5461. (taicpu(hp2).opsize = S_Q) and
  5462. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5463. (
  5464. (
  5465. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5466. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5467. ) or (
  5468. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5469. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5470. )
  5471. )
  5472. ) or (
  5473. MatchInstruction(hp2, A_LEA,[]) and
  5474. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  5475. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  5476. (
  5477. (
  5478. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5479. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5480. ) or (
  5481. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5482. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  5483. )
  5484. ) and (
  5485. (
  5486. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5487. ) or (
  5488. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5489. )
  5490. )
  5491. )
  5492. )
  5493. ) and (
  5494. GetNextInstruction(hp2, hp3) and
  5495. MatchInstruction(hp3, A_SHR,[]) and
  5496. (taicpu(hp3).opsize = S_Q) and
  5497. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5498. (taicpu(hp3).oper[0]^.val = 1) and
  5499. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  5500. ) then
  5501. begin
  5502. { Change movl x, reg1d movl x, reg1d
  5503. movl y, reg2d movl y, reg2d
  5504. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  5505. shrq $1, reg1q shrq $1, reg1q
  5506. ( reg1d and reg2d can be switched around in the first two instructions )
  5507. To movl x, reg1d
  5508. addl y, reg1d
  5509. rcrl $1, reg1d
  5510. This corresponds to the common expression (x + y) shr 1, where
  5511. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  5512. smaller code, but won't account for x + y causing an overflow). [Kit]
  5513. }
  5514. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  5515. { Change first MOV command to have the same register as the final output }
  5516. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  5517. else
  5518. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  5519. { Change second MOV command to an ADD command. This is easier than
  5520. converting the existing command because it means we don't have to
  5521. touch 'y', which might be a complicated reference, and also the
  5522. fact that the third command might either be ADD or LEA. [Kit] }
  5523. taicpu(hp1).opcode := A_ADD;
  5524. { Delete old ADD/LEA instruction }
  5525. RemoveInstruction(hp2);
  5526. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  5527. taicpu(hp3).opcode := A_RCR;
  5528. taicpu(hp3).changeopsize(S_L);
  5529. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  5530. {$endif x86_64}
  5531. end;
  5532. end;
  5533. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  5534. var
  5535. ThisReg: TRegister;
  5536. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  5537. TargetSubReg: TSubRegister;
  5538. hp1, hp2: tai;
  5539. RegInUse, RegChanged, p_removed: Boolean;
  5540. { Store list of found instructions so we don't have to call
  5541. GetNextInstructionUsingReg multiple times }
  5542. InstrList: array of taicpu;
  5543. InstrMax, Index: Integer;
  5544. UpperLimit, TrySmallerLimit: TCgInt;
  5545. PreMessage: string;
  5546. { Data flow analysis }
  5547. TestValMin, TestValMax: TCgInt;
  5548. SmallerOverflow: Boolean;
  5549. begin
  5550. Result := False;
  5551. p_removed := False;
  5552. { This is anything but quick! }
  5553. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  5554. Exit;
  5555. SetLength(InstrList, 0);
  5556. InstrMax := -1;
  5557. ThisReg := taicpu(p).oper[1]^.reg;
  5558. case taicpu(p).opsize of
  5559. S_BW, S_BL:
  5560. begin
  5561. {$if defined(i386) or defined(i8086)}
  5562. { If the target size is 8-bit, make sure we can actually encode it }
  5563. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  5564. Exit;
  5565. {$endif i386 or i8086}
  5566. UpperLimit := $FF;
  5567. MinSize := S_B;
  5568. if taicpu(p).opsize = S_BW then
  5569. MaxSize := S_W
  5570. else
  5571. MaxSize := S_L;
  5572. end;
  5573. S_WL:
  5574. begin
  5575. UpperLimit := $FFFF;
  5576. MinSize := S_W;
  5577. MaxSize := S_L;
  5578. end
  5579. else
  5580. InternalError(2020112301);
  5581. end;
  5582. TestValMin := 0;
  5583. TestValMax := UpperLimit;
  5584. TrySmallerLimit := UpperLimit;
  5585. TrySmaller := S_NO;
  5586. SmallerOverflow := False;
  5587. RegChanged := False;
  5588. hp1 := p;
  5589. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  5590. (hp1.typ = ait_instruction) and
  5591. (
  5592. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  5593. instruction that doesn't actually contain ThisReg }
  5594. (cs_opt_level3 in current_settings.optimizerswitches) or
  5595. RegInInstruction(ThisReg, hp1)
  5596. ) do
  5597. begin
  5598. case taicpu(hp1).opcode of
  5599. A_INC,A_DEC:
  5600. begin
  5601. { Has to be an exact match on the register }
  5602. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  5603. Break;
  5604. if taicpu(hp1).opcode = A_INC then
  5605. begin
  5606. Inc(TestValMin);
  5607. Inc(TestValMax);
  5608. end
  5609. else
  5610. begin
  5611. Dec(TestValMin);
  5612. Dec(TestValMax);
  5613. end;
  5614. end;
  5615. A_CMP:
  5616. begin
  5617. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5618. { Has to be an exact match on the register }
  5619. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5620. (taicpu(hp1).oper[0]^.typ <> top_const) or
  5621. { Make sure the comparison value is not smaller than the
  5622. smallest allowed signed value for the minimum size (e.g.
  5623. -128 for 8-bit) }
  5624. not (
  5625. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5626. { Is it in the negative range? }
  5627. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  5628. ) then
  5629. Break;
  5630. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  5631. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  5632. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  5633. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  5634. { Overflow }
  5635. Break;
  5636. { Check to see if the active register is used afterwards }
  5637. TransferUsedRegs(TmpUsedRegs);
  5638. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  5639. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  5640. begin
  5641. case MinSize of
  5642. S_B:
  5643. TargetSubReg := R_SUBL;
  5644. S_W:
  5645. TargetSubReg := R_SUBW;
  5646. else
  5647. InternalError(2021051002);
  5648. end;
  5649. { Update the register to its new size }
  5650. setsubreg(ThisReg, TargetSubReg);
  5651. taicpu(hp1).oper[1]^.reg := ThisReg;
  5652. taicpu(hp1).opsize := MinSize;
  5653. { Convert the input MOVZX to a MOV }
  5654. if (taicpu(p).oper[0]^.typ = top_reg) and
  5655. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  5656. begin
  5657. { Or remove it completely! }
  5658. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  5659. RemoveCurrentP(p);
  5660. p_removed := True;
  5661. end
  5662. else
  5663. begin
  5664. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  5665. taicpu(p).opcode := A_MOV;
  5666. taicpu(p).oper[1]^.reg := ThisReg;
  5667. taicpu(p).opsize := MinSize;
  5668. end;
  5669. if (InstrMax >= 0) then
  5670. begin
  5671. for Index := 0 to InstrMax do
  5672. begin
  5673. { If p_removed is true, then the original MOV/Z was removed
  5674. and removing the AND instruction may not be safe if it
  5675. appears first }
  5676. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  5677. InternalError(2020112311);
  5678. if InstrList[Index].oper[0]^.typ = top_reg then
  5679. InstrList[Index].oper[0]^.reg := ThisReg;
  5680. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  5681. InstrList[Index].opsize := MinSize;
  5682. end;
  5683. end;
  5684. Result := True;
  5685. Exit;
  5686. end;
  5687. end;
  5688. { OR and XOR are not included because they can too easily fool
  5689. the data flow analysis (they can cause non-linear behaviour) }
  5690. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  5691. begin
  5692. if
  5693. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5694. { Has to be an exact match on the register }
  5695. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  5696. (
  5697. (
  5698. (taicpu(hp1).oper[0]^.typ = top_const) and
  5699. (
  5700. (
  5701. (taicpu(hp1).opcode = A_SHL) and
  5702. (
  5703. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  5704. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  5705. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  5706. )
  5707. ) or (
  5708. (taicpu(hp1).opcode <> A_SHL) and
  5709. (
  5710. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5711. { Is it in the negative range? }
  5712. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  5713. )
  5714. )
  5715. )
  5716. ) or (
  5717. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  5718. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  5719. )
  5720. ) then
  5721. Break;
  5722. case taicpu(hp1).opcode of
  5723. A_ADD:
  5724. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  5725. begin
  5726. TestValMin := TestValMin * 2;
  5727. TestValMax := TestValMax * 2;
  5728. end
  5729. else
  5730. begin
  5731. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  5732. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  5733. end;
  5734. A_SUB:
  5735. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  5736. begin
  5737. TestValMin := 0;
  5738. TestValMax := 0;
  5739. end
  5740. else
  5741. begin
  5742. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  5743. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  5744. end;
  5745. A_AND:
  5746. if (taicpu(hp1).oper[0]^.typ = top_const) then
  5747. begin
  5748. { we might be able to go smaller if AND appears first }
  5749. if InstrMax = -1 then
  5750. case MinSize of
  5751. S_B:
  5752. ;
  5753. S_W:
  5754. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  5755. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  5756. begin
  5757. TrySmaller := S_B;
  5758. TrySmallerLimit := $FF;
  5759. end;
  5760. S_L:
  5761. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  5762. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  5763. begin
  5764. TrySmaller := S_B;
  5765. TrySmallerLimit := $FF;
  5766. end
  5767. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  5768. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  5769. begin
  5770. TrySmaller := S_W;
  5771. TrySmallerLimit := $FFFF;
  5772. end;
  5773. else
  5774. InternalError(2020112320);
  5775. end;
  5776. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  5777. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  5778. end;
  5779. A_SHL:
  5780. begin
  5781. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  5782. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  5783. end;
  5784. A_SHR:
  5785. begin
  5786. { we might be able to go smaller if SHR appears first }
  5787. if InstrMax = -1 then
  5788. case MinSize of
  5789. S_B:
  5790. ;
  5791. S_W:
  5792. if (taicpu(hp1).oper[0]^.val >= 8) then
  5793. begin
  5794. TrySmaller := S_B;
  5795. TrySmallerLimit := $FF;
  5796. end;
  5797. S_L:
  5798. if (taicpu(hp1).oper[0]^.val >= 24) then
  5799. begin
  5800. TrySmaller := S_B;
  5801. TrySmallerLimit := $FF;
  5802. end
  5803. else if (taicpu(hp1).oper[0]^.val >= 16) then
  5804. begin
  5805. TrySmaller := S_W;
  5806. TrySmallerLimit := $FFFF;
  5807. end;
  5808. else
  5809. InternalError(2020112321);
  5810. end;
  5811. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  5812. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  5813. end;
  5814. else
  5815. InternalError(2020112303);
  5816. end;
  5817. end;
  5818. (*
  5819. A_IMUL:
  5820. case taicpu(hp1).ops of
  5821. 2:
  5822. begin
  5823. if not MatchOpType(hp1, top_reg, top_reg) or
  5824. { Has to be an exact match on the register }
  5825. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  5826. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  5827. Break;
  5828. TestValMin := TestValMin * TestValMin;
  5829. TestValMax := TestValMax * TestValMax;
  5830. end;
  5831. 3:
  5832. begin
  5833. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  5834. { Has to be an exact match on the register }
  5835. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5836. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  5837. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5838. { Is it in the negative range? }
  5839. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  5840. Break;
  5841. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  5842. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  5843. end;
  5844. else
  5845. Break;
  5846. end;
  5847. A_IDIV:
  5848. case taicpu(hp1).ops of
  5849. 3:
  5850. begin
  5851. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  5852. { Has to be an exact match on the register }
  5853. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5854. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  5855. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5856. { Is it in the negative range? }
  5857. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  5858. Break;
  5859. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  5860. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  5861. end;
  5862. else
  5863. Break;
  5864. end;
  5865. *)
  5866. A_MOVZX:
  5867. begin
  5868. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  5869. Break;
  5870. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  5871. begin
  5872. { Because hp1 was obtained via GetNextInstructionUsingReg
  5873. and ThisReg doesn't appear in the first operand, it
  5874. must appear in the second operand and hence gets
  5875. overwritten }
  5876. if (InstrMax = -1) and
  5877. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  5878. begin
  5879. { The two MOVZX instructions are adjacent, so remove the first one }
  5880. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  5881. RemoveCurrentP(p);
  5882. Result := True;
  5883. Exit;
  5884. end;
  5885. Break;
  5886. end;
  5887. { The objective here is to try to find a combination that
  5888. removes one of the MOV/Z instructions. }
  5889. case taicpu(hp1).opsize of
  5890. S_WL:
  5891. if (MinSize in [S_B, S_W]) then
  5892. begin
  5893. TargetSize := S_L;
  5894. TargetSubReg := R_SUBD;
  5895. end
  5896. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  5897. begin
  5898. TargetSize := TrySmaller;
  5899. if TrySmaller = S_B then
  5900. TargetSubReg := R_SUBL
  5901. else
  5902. TargetSubReg := R_SUBW;
  5903. end
  5904. else
  5905. Break;
  5906. S_BW:
  5907. if (MinSize in [S_B, S_W]) then
  5908. begin
  5909. TargetSize := S_W;
  5910. TargetSubReg := R_SUBW;
  5911. end
  5912. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  5913. begin
  5914. TargetSize := S_B;
  5915. TargetSubReg := R_SUBL;
  5916. end
  5917. else
  5918. Break;
  5919. S_BL:
  5920. if (MinSize in [S_B, S_W]) then
  5921. begin
  5922. TargetSize := S_L;
  5923. TargetSubReg := R_SUBD;
  5924. end
  5925. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  5926. begin
  5927. TargetSize := S_B;
  5928. TargetSubReg := R_SUBL;
  5929. end
  5930. else
  5931. Break;
  5932. else
  5933. InternalError(2020112302);
  5934. end;
  5935. { Update the register to its new size }
  5936. setsubreg(ThisReg, TargetSubReg);
  5937. if TargetSize = MinSize then
  5938. begin
  5939. { Convert the input MOVZX to a MOV }
  5940. if (taicpu(p).oper[0]^.typ = top_reg) and
  5941. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  5942. begin
  5943. { Or remove it completely! }
  5944. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  5945. RemoveCurrentP(p);
  5946. p_removed := True;
  5947. end
  5948. else
  5949. begin
  5950. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  5951. taicpu(p).opcode := A_MOV;
  5952. taicpu(p).oper[1]^.reg := ThisReg;
  5953. taicpu(p).opsize := TargetSize;
  5954. end;
  5955. Result := True;
  5956. end
  5957. else if TargetSize <> MaxSize then
  5958. begin
  5959. case MaxSize of
  5960. S_L:
  5961. if TargetSize = S_W then
  5962. begin
  5963. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  5964. taicpu(p).opsize := S_BW;
  5965. taicpu(p).oper[1]^.reg := ThisReg;
  5966. Result := True;
  5967. end
  5968. else
  5969. InternalError(2020112341);
  5970. S_W:
  5971. if TargetSize = S_L then
  5972. begin
  5973. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  5974. taicpu(p).opsize := S_BL;
  5975. taicpu(p).oper[1]^.reg := ThisReg;
  5976. Result := True;
  5977. end
  5978. else
  5979. InternalError(2020112342);
  5980. else
  5981. ;
  5982. end;
  5983. end;
  5984. if (MaxSize = TargetSize) or
  5985. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  5986. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  5987. begin
  5988. { Convert the output MOVZX to a MOV }
  5989. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  5990. begin
  5991. { Or remove it completely! }
  5992. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  5993. { Be careful; if p = hp1 and p was also removed, p
  5994. will become a dangling pointer }
  5995. if p = hp1 then
  5996. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  5997. else
  5998. RemoveInstruction(hp1);
  5999. end
  6000. else
  6001. begin
  6002. taicpu(hp1).opcode := A_MOV;
  6003. taicpu(hp1).oper[0]^.reg := ThisReg;
  6004. taicpu(hp1).opsize := TargetSize;
  6005. { Check to see if the active register is used afterwards;
  6006. if not, we can change it and make a saving. }
  6007. RegInUse := False;
  6008. TransferUsedRegs(TmpUsedRegs);
  6009. { The target register may be marked as in use to cross
  6010. a jump to a distant label, so exclude it }
  6011. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6012. hp2 := p;
  6013. repeat
  6014. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6015. { Explicitly check for the excluded register (don't include the first
  6016. instruction as it may be reading from here }
  6017. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6018. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6019. begin
  6020. RegInUse := True;
  6021. Break;
  6022. end;
  6023. if not GetNextInstruction(hp2, hp2) then
  6024. InternalError(2020112340);
  6025. until (hp2 = hp1);
  6026. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6027. begin
  6028. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6029. ThisReg := taicpu(hp1).oper[1]^.reg;
  6030. RegChanged := True;
  6031. TransferUsedRegs(TmpUsedRegs);
  6032. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6033. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6034. if p = hp1 then
  6035. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6036. else
  6037. RemoveInstruction(hp1);
  6038. { Instruction will become "mov %reg,%reg" }
  6039. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6040. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6041. begin
  6042. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6043. RemoveCurrentP(p);
  6044. p_removed := True;
  6045. end
  6046. else
  6047. taicpu(p).oper[1]^.reg := ThisReg;
  6048. Result := True;
  6049. end
  6050. else
  6051. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6052. end;
  6053. end
  6054. else
  6055. InternalError(2020112330);
  6056. { Now go through every instruction we found and change the
  6057. size. If TargetSize = MaxSize, then almost no changes are
  6058. needed and Result can remain False if it hasn't been set
  6059. yet.
  6060. If RegChanged is True, then the register requires changing
  6061. and so the point about TargetSize = MaxSize doesn't apply. }
  6062. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6063. begin
  6064. for Index := 0 to InstrMax do
  6065. begin
  6066. { If p_removed is true, then the original MOV/Z was removed
  6067. and removing the AND instruction may not be safe if it
  6068. appears first }
  6069. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6070. InternalError(2020112310);
  6071. if InstrList[Index].oper[0]^.typ = top_reg then
  6072. InstrList[Index].oper[0]^.reg := ThisReg;
  6073. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6074. InstrList[Index].opsize := TargetSize;
  6075. end;
  6076. Result := True;
  6077. end;
  6078. Exit;
  6079. end;
  6080. else
  6081. { This includes ADC, SBB, IDIV and SAR }
  6082. Break;
  6083. end;
  6084. if (TestValMin < 0) or (TestValMax < 0) or
  6085. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6086. { Overflow }
  6087. Break
  6088. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6089. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6090. SmallerOverflow := True;
  6091. { Contains highest index (so instruction count - 1) }
  6092. Inc(InstrMax);
  6093. if InstrMax > High(InstrList) then
  6094. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6095. InstrList[InstrMax] := taicpu(hp1);
  6096. end;
  6097. end;
  6098. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6099. var
  6100. hp1 : tai;
  6101. begin
  6102. Result:=false;
  6103. if (taicpu(p).ops >= 2) and
  6104. ((taicpu(p).oper[0]^.typ = top_const) or
  6105. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6106. (taicpu(p).oper[1]^.typ = top_reg) and
  6107. ((taicpu(p).ops = 2) or
  6108. ((taicpu(p).oper[2]^.typ = top_reg) and
  6109. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6110. GetLastInstruction(p,hp1) and
  6111. MatchInstruction(hp1,A_MOV,[]) and
  6112. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6113. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6114. begin
  6115. TransferUsedRegs(TmpUsedRegs);
  6116. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6117. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6118. { change
  6119. mov reg1,reg2
  6120. imul y,reg2 to imul y,reg1,reg2 }
  6121. begin
  6122. taicpu(p).ops := 3;
  6123. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6124. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6125. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6126. RemoveInstruction(hp1);
  6127. result:=true;
  6128. end;
  6129. end;
  6130. end;
  6131. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6132. var
  6133. ThisLabel: TAsmLabel;
  6134. begin
  6135. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6136. ThisLabel.decrefs;
  6137. taicpu(p).opcode := A_RET;
  6138. taicpu(p).is_jmp := false;
  6139. taicpu(p).ops := taicpu(ret_p).ops;
  6140. case taicpu(ret_p).ops of
  6141. 0:
  6142. taicpu(p).clearop(0);
  6143. 1:
  6144. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6145. else
  6146. internalerror(2016041301);
  6147. end;
  6148. { If the original label is now dead, it might turn out that the label
  6149. immediately follows p. As a result, everything beyond it, which will
  6150. be just some final register configuration and a RET instruction, is
  6151. now dead code. [Kit] }
  6152. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6153. running RemoveDeadCodeAfterJump for each RET instruction, because
  6154. this optimisation rarely happens and most RETs appear at the end of
  6155. routines where there is nothing that can be stripped. [Kit] }
  6156. if not ThisLabel.is_used then
  6157. RemoveDeadCodeAfterJump(p);
  6158. end;
  6159. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6160. var
  6161. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6162. Unconditional, PotentialModified: Boolean;
  6163. OperPtr: POper;
  6164. NewRef: TReference;
  6165. InstrList: array of taicpu;
  6166. InstrMax, Index: Integer;
  6167. const
  6168. {$ifdef DEBUG_AOPTCPU}
  6169. SNoFlags: shortstring = ' so the flags aren''t modified';
  6170. {$else DEBUG_AOPTCPU}
  6171. SNoFlags = '';
  6172. {$endif DEBUG_AOPTCPU}
  6173. begin
  6174. Result:=false;
  6175. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6176. begin
  6177. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6178. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6179. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6180. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6181. GetNextInstruction(hp1, hp2) and
  6182. MatchInstruction(hp2, A_Jcc, []) then
  6183. { Change from: To:
  6184. set(C) %reg j(~C) label
  6185. test %reg,%reg/cmp $0,%reg
  6186. je label
  6187. set(C) %reg j(C) label
  6188. test %reg,%reg/cmp $0,%reg
  6189. jne label
  6190. }
  6191. begin
  6192. { Before we do anything else, we need to check the instructions
  6193. in between SETcc and TEST to make sure they don't modify the
  6194. FLAGS register - if -O2 or under, there won't be any
  6195. instructions between SET and TEST }
  6196. TransferUsedRegs(TmpUsedRegs);
  6197. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6198. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6199. begin
  6200. next := p;
  6201. SetLength(InstrList, 0);
  6202. InstrMax := -1;
  6203. PotentialModified := False;
  6204. { Make a note of every instruction that modifies the FLAGS
  6205. register }
  6206. while GetNextInstruction(next, next) and (next <> hp1) do
  6207. begin
  6208. if next.typ <> ait_instruction then
  6209. { GetNextInstructionUsingReg should have returned False }
  6210. InternalError(2021051701);
  6211. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  6212. begin
  6213. case taicpu(next).opcode of
  6214. A_SETcc,
  6215. A_CMOVcc,
  6216. A_Jcc:
  6217. begin
  6218. if PotentialModified then
  6219. { Not safe because the flags were modified earlier }
  6220. Exit
  6221. else
  6222. { Condition is the same as the initial SETcc, so this is safe
  6223. (don't add to instruction list though) }
  6224. Continue;
  6225. end;
  6226. A_ADD:
  6227. begin
  6228. if (taicpu(next).opsize = S_B) or
  6229. { LEA doesn't support 8-bit operands }
  6230. (taicpu(next).oper[1]^.typ <> top_reg) or
  6231. { Must write to a register }
  6232. (taicpu(next).oper[0]^.typ = top_ref) then
  6233. { Require a constant or a register }
  6234. Exit;
  6235. PotentialModified := True;
  6236. end;
  6237. A_SUB:
  6238. begin
  6239. if (taicpu(next).opsize = S_B) or
  6240. { LEA doesn't support 8-bit operands }
  6241. (taicpu(next).oper[1]^.typ <> top_reg) or
  6242. { Must write to a register }
  6243. (taicpu(next).oper[0]^.typ <> top_const) or
  6244. (taicpu(next).oper[0]^.val = $80000000) then
  6245. { Can't subtract a register with LEA - also
  6246. check that the value isn't -2^31, as this
  6247. can't be negated }
  6248. Exit;
  6249. PotentialModified := True;
  6250. end;
  6251. A_SAL,
  6252. A_SHL:
  6253. begin
  6254. if (taicpu(next).opsize = S_B) or
  6255. { LEA doesn't support 8-bit operands }
  6256. (taicpu(next).oper[1]^.typ <> top_reg) or
  6257. { Must write to a register }
  6258. (taicpu(next).oper[0]^.typ <> top_const) or
  6259. (taicpu(next).oper[0]^.val < 0) or
  6260. (taicpu(next).oper[0]^.val > 3) then
  6261. Exit;
  6262. PotentialModified := True;
  6263. end;
  6264. A_IMUL:
  6265. begin
  6266. if (taicpu(next).ops <> 3) or
  6267. (taicpu(next).oper[1]^.typ <> top_reg) or
  6268. { Must write to a register }
  6269. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  6270. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  6271. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  6272. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  6273. Exit
  6274. else
  6275. PotentialModified := True;
  6276. end;
  6277. else
  6278. { Don't know how to change this, so abort }
  6279. Exit;
  6280. end;
  6281. { Contains highest index (so instruction count - 1) }
  6282. Inc(InstrMax);
  6283. if InstrMax > High(InstrList) then
  6284. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6285. InstrList[InstrMax] := taicpu(next);
  6286. end;
  6287. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  6288. end;
  6289. if not Assigned(next) or (next <> hp1) then
  6290. { It should be equal to hp1 }
  6291. InternalError(2021051702);
  6292. { Cycle through each instruction and check to see if we can
  6293. change them to versions that don't modify the flags }
  6294. if (InstrMax >= 0) then
  6295. begin
  6296. for Index := 0 to InstrMax do
  6297. case InstrList[Index].opcode of
  6298. A_ADD:
  6299. begin
  6300. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  6301. InstrList[Index].opcode := A_LEA;
  6302. reference_reset(NewRef, 1, []);
  6303. NewRef.base := InstrList[Index].oper[1]^.reg;
  6304. if InstrList[Index].oper[0]^.typ = top_reg then
  6305. begin
  6306. NewRef.index := InstrList[Index].oper[0]^.reg;
  6307. NewRef.scalefactor := 1;
  6308. end
  6309. else
  6310. NewRef.offset := InstrList[Index].oper[0]^.val;
  6311. InstrList[Index].loadref(0, NewRef);
  6312. end;
  6313. A_SUB:
  6314. begin
  6315. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  6316. InstrList[Index].opcode := A_LEA;
  6317. reference_reset(NewRef, 1, []);
  6318. NewRef.base := InstrList[Index].oper[1]^.reg;
  6319. NewRef.offset := -InstrList[Index].oper[0]^.val;
  6320. InstrList[Index].loadref(0, NewRef);
  6321. end;
  6322. A_SHL,
  6323. A_SAL:
  6324. begin
  6325. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  6326. InstrList[Index].opcode := A_LEA;
  6327. reference_reset(NewRef, 1, []);
  6328. NewRef.index := InstrList[Index].oper[1]^.reg;
  6329. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  6330. InstrList[Index].loadref(0, NewRef);
  6331. end;
  6332. A_IMUL:
  6333. begin
  6334. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  6335. InstrList[Index].opcode := A_LEA;
  6336. reference_reset(NewRef, 1, []);
  6337. NewRef.index := InstrList[Index].oper[1]^.reg;
  6338. case InstrList[Index].oper[0]^.val of
  6339. 2, 4, 8:
  6340. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  6341. else {3, 5 and 9}
  6342. begin
  6343. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  6344. NewRef.base := InstrList[Index].oper[1]^.reg;
  6345. end;
  6346. end;
  6347. InstrList[Index].loadref(0, NewRef);
  6348. end;
  6349. else
  6350. InternalError(2021051710);
  6351. end;
  6352. end;
  6353. { Mark the FLAGS register as used across this whole block }
  6354. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  6355. end;
  6356. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6357. JumpC := taicpu(hp2).condition;
  6358. Unconditional := False;
  6359. if conditions_equal(JumpC, C_E) then
  6360. SetC := inverse_cond(taicpu(p).condition)
  6361. else if conditions_equal(JumpC, C_NE) then
  6362. SetC := taicpu(p).condition
  6363. else
  6364. { We've got something weird here (and inefficent) }
  6365. begin
  6366. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  6367. SetC := C_NONE;
  6368. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  6369. if condition_in(C_AE, JumpC) then
  6370. Unconditional := True
  6371. else
  6372. { Not sure what to do with this jump - drop out }
  6373. Exit;
  6374. end;
  6375. RemoveInstruction(hp1);
  6376. if Unconditional then
  6377. MakeUnconditional(taicpu(hp2))
  6378. else
  6379. begin
  6380. if SetC = C_NONE then
  6381. InternalError(2018061402);
  6382. taicpu(hp2).SetCondition(SetC);
  6383. end;
  6384. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  6385. TmpUsedRegs }
  6386. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  6387. begin
  6388. RemoveCurrentp(p, hp2);
  6389. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  6390. end
  6391. else
  6392. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  6393. Result := True;
  6394. end
  6395. else if
  6396. { Make sure the instructions are adjacent }
  6397. (
  6398. not (cs_opt_level3 in current_settings.optimizerswitches) or
  6399. GetNextInstruction(p, hp1)
  6400. ) and
  6401. MatchInstruction(hp1, A_MOV, [S_B]) and
  6402. { Writing to memory is allowed }
  6403. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  6404. begin
  6405. {
  6406. Watch out for sequences such as:
  6407. set(c)b %regb
  6408. movb %regb,(ref)
  6409. movb $0,1(ref)
  6410. movb $0,2(ref)
  6411. movb $0,3(ref)
  6412. Much more efficient to turn it into:
  6413. movl $0,%regl
  6414. set(c)b %regb
  6415. movl %regl,(ref)
  6416. Or:
  6417. set(c)b %regb
  6418. movzbl %regb,%regl
  6419. movl %regl,(ref)
  6420. }
  6421. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  6422. GetNextInstruction(hp1, hp2) and
  6423. MatchInstruction(hp2, A_MOV, [S_B]) and
  6424. (taicpu(hp2).oper[1]^.typ = top_ref) and
  6425. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  6426. begin
  6427. { Don't do anything else except set Result to True }
  6428. end
  6429. else
  6430. begin
  6431. if taicpu(p).oper[0]^.typ = top_reg then
  6432. begin
  6433. TransferUsedRegs(TmpUsedRegs);
  6434. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6435. end;
  6436. { If it's not a register, it's a memory address }
  6437. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  6438. begin
  6439. { Even if the register is still in use, we can minimise the
  6440. pipeline stall by changing the MOV into another SETcc. }
  6441. taicpu(hp1).opcode := A_SETcc;
  6442. taicpu(hp1).condition := taicpu(p).condition;
  6443. if taicpu(hp1).oper[1]^.typ = top_ref then
  6444. begin
  6445. { Swapping the operand pointers like this is probably a
  6446. bit naughty, but it is far faster than using loadoper
  6447. to transfer the reference from oper[1] to oper[0] if
  6448. you take into account the extra procedure calls and
  6449. the memory allocation and deallocation required }
  6450. OperPtr := taicpu(hp1).oper[1];
  6451. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  6452. taicpu(hp1).oper[0] := OperPtr;
  6453. end
  6454. else
  6455. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  6456. taicpu(hp1).clearop(1);
  6457. taicpu(hp1).ops := 1;
  6458. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  6459. end
  6460. else
  6461. begin
  6462. if taicpu(hp1).oper[1]^.typ = top_reg then
  6463. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  6464. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6465. RemoveInstruction(hp1);
  6466. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  6467. end
  6468. end;
  6469. Result := True;
  6470. end;
  6471. end;
  6472. end;
  6473. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  6474. var
  6475. hp1: tai;
  6476. Count: Integer;
  6477. OrigLabel: TAsmLabel;
  6478. begin
  6479. result := False;
  6480. { Sometimes, the optimisations below can permit this }
  6481. RemoveDeadCodeAfterJump(p);
  6482. 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
  6483. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  6484. begin
  6485. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6486. { Also a side-effect of optimisations }
  6487. if CollapseZeroDistJump(p, OrigLabel) then
  6488. begin
  6489. Result := True;
  6490. Exit;
  6491. end;
  6492. hp1 := GetLabelWithSym(OrigLabel);
  6493. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  6494. begin
  6495. case taicpu(hp1).opcode of
  6496. A_RET:
  6497. {
  6498. change
  6499. jmp .L1
  6500. ...
  6501. .L1:
  6502. ret
  6503. into
  6504. ret
  6505. }
  6506. begin
  6507. ConvertJumpToRET(p, hp1);
  6508. result:=true;
  6509. end;
  6510. { Check any kind of direct assignment instruction }
  6511. A_MOV,
  6512. A_MOVD,
  6513. A_MOVQ,
  6514. A_MOVSX,
  6515. {$ifdef x86_64}
  6516. A_MOVSXD,
  6517. {$endif x86_64}
  6518. A_MOVZX,
  6519. A_MOVAPS,
  6520. A_MOVUPS,
  6521. A_MOVSD,
  6522. A_MOVAPD,
  6523. A_MOVUPD,
  6524. A_MOVDQA,
  6525. A_MOVDQU,
  6526. A_VMOVSS,
  6527. A_VMOVAPS,
  6528. A_VMOVUPS,
  6529. A_VMOVSD,
  6530. A_VMOVAPD,
  6531. A_VMOVUPD,
  6532. A_VMOVDQA,
  6533. A_VMOVDQU:
  6534. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  6535. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  6536. begin
  6537. Result := True;
  6538. Exit;
  6539. end;
  6540. else
  6541. ;
  6542. end;
  6543. end;
  6544. end;
  6545. end;
  6546. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  6547. begin
  6548. CanBeCMOV:=assigned(p) and
  6549. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  6550. { we can't use cmov ref,reg because
  6551. ref could be nil and cmov still throws an exception
  6552. if ref=nil but the mov isn't done (FK)
  6553. or ((taicpu(p).oper[0]^.typ = top_ref) and
  6554. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  6555. }
  6556. (taicpu(p).oper[1]^.typ = top_reg) and
  6557. (
  6558. (taicpu(p).oper[0]^.typ = top_reg) or
  6559. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  6560. it is not expected that this can cause a seg. violation }
  6561. (
  6562. (taicpu(p).oper[0]^.typ = top_ref) and
  6563. IsRefSafe(taicpu(p).oper[0]^.ref)
  6564. )
  6565. );
  6566. end;
  6567. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  6568. var
  6569. hp1,hp2: tai;
  6570. {$ifndef i8086}
  6571. hp3,hp4,hpmov2, hp5: tai;
  6572. l : Longint;
  6573. condition : TAsmCond;
  6574. {$endif i8086}
  6575. carryadd_opcode : TAsmOp;
  6576. symbol: TAsmSymbol;
  6577. reg: tsuperregister;
  6578. increg, tmpreg: TRegister;
  6579. begin
  6580. result:=false;
  6581. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  6582. begin
  6583. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6584. if (
  6585. (
  6586. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  6587. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  6588. (Taicpu(hp1).oper[0]^.val=1)
  6589. ) or
  6590. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  6591. ) and
  6592. GetNextInstruction(hp1,hp2) and
  6593. SkipAligns(hp2, hp2) and
  6594. (hp2.typ = ait_label) and
  6595. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  6596. { jb @@1 cmc
  6597. inc/dec operand --> adc/sbb operand,0
  6598. @@1:
  6599. ... and ...
  6600. jnb @@1
  6601. inc/dec operand --> adc/sbb operand,0
  6602. @@1: }
  6603. begin
  6604. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  6605. begin
  6606. case taicpu(hp1).opcode of
  6607. A_INC,
  6608. A_ADD:
  6609. carryadd_opcode:=A_ADC;
  6610. A_DEC,
  6611. A_SUB:
  6612. carryadd_opcode:=A_SBB;
  6613. else
  6614. InternalError(2021011001);
  6615. end;
  6616. Taicpu(p).clearop(0);
  6617. Taicpu(p).ops:=0;
  6618. Taicpu(p).is_jmp:=false;
  6619. Taicpu(p).opcode:=A_CMC;
  6620. Taicpu(p).condition:=C_NONE;
  6621. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  6622. Taicpu(hp1).ops:=2;
  6623. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6624. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  6625. else
  6626. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  6627. Taicpu(hp1).loadconst(0,0);
  6628. Taicpu(hp1).opcode:=carryadd_opcode;
  6629. result:=true;
  6630. exit;
  6631. end
  6632. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  6633. begin
  6634. case taicpu(hp1).opcode of
  6635. A_INC,
  6636. A_ADD:
  6637. carryadd_opcode:=A_ADC;
  6638. A_DEC,
  6639. A_SUB:
  6640. carryadd_opcode:=A_SBB;
  6641. else
  6642. InternalError(2021011002);
  6643. end;
  6644. Taicpu(hp1).ops:=2;
  6645. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  6646. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6647. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  6648. else
  6649. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  6650. Taicpu(hp1).loadconst(0,0);
  6651. Taicpu(hp1).opcode:=carryadd_opcode;
  6652. RemoveCurrentP(p, hp1);
  6653. result:=true;
  6654. exit;
  6655. end
  6656. {
  6657. jcc @@1 setcc tmpreg
  6658. inc/dec/add/sub operand -> (movzx tmpreg)
  6659. @@1: add/sub tmpreg,operand
  6660. While this increases code size slightly, it makes the code much faster if the
  6661. jump is unpredictable
  6662. }
  6663. else if not(cs_opt_size in current_settings.optimizerswitches) then
  6664. begin
  6665. { search for an available register which is volatile }
  6666. for reg in tcpuregisterset do
  6667. begin
  6668. if
  6669. {$if defined(i386) or defined(i8086)}
  6670. { Only use registers whose lowest 8-bits can Be accessed }
  6671. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  6672. {$endif i386 or i8086}
  6673. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  6674. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  6675. { We don't need to check if tmpreg is in hp1 or not, because
  6676. it will be marked as in use at p (if not, this is
  6677. indictive of a compiler bug). }
  6678. then
  6679. begin
  6680. TAsmLabel(symbol).decrefs;
  6681. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  6682. Taicpu(p).clearop(0);
  6683. Taicpu(p).ops:=1;
  6684. Taicpu(p).is_jmp:=false;
  6685. Taicpu(p).opcode:=A_SETcc;
  6686. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  6687. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  6688. Taicpu(p).loadreg(0,increg);
  6689. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  6690. begin
  6691. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  6692. R_SUBW:
  6693. begin
  6694. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  6695. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  6696. end;
  6697. R_SUBD:
  6698. begin
  6699. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  6700. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  6701. end;
  6702. {$ifdef x86_64}
  6703. R_SUBQ:
  6704. begin
  6705. { MOVZX doesn't have a 64-bit variant, because
  6706. the 32-bit version implicitly zeroes the
  6707. upper 32-bits of the destination register }
  6708. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  6709. newreg(R_INTREGISTER,reg,R_SUBD));
  6710. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  6711. end;
  6712. {$endif x86_64}
  6713. else
  6714. Internalerror(2020030601);
  6715. end;
  6716. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  6717. asml.InsertAfter(hp2,p);
  6718. end
  6719. else
  6720. tmpreg := increg;
  6721. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  6722. begin
  6723. Taicpu(hp1).ops:=2;
  6724. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  6725. end;
  6726. Taicpu(hp1).loadreg(0,tmpreg);
  6727. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  6728. Result := True;
  6729. { p is no longer a Jcc instruction, so exit }
  6730. Exit;
  6731. end;
  6732. end;
  6733. end;
  6734. end;
  6735. { Detect the following:
  6736. jmp<cond> @Lbl1
  6737. jmp @Lbl2
  6738. ...
  6739. @Lbl1:
  6740. ret
  6741. Change to:
  6742. jmp<inv_cond> @Lbl2
  6743. ret
  6744. }
  6745. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  6746. begin
  6747. hp2:=getlabelwithsym(TAsmLabel(symbol));
  6748. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  6749. MatchInstruction(hp2,A_RET,[S_NO]) then
  6750. begin
  6751. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6752. { Change label address to that of the unconditional jump }
  6753. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  6754. TAsmLabel(symbol).DecRefs;
  6755. taicpu(hp1).opcode := A_RET;
  6756. taicpu(hp1).is_jmp := false;
  6757. taicpu(hp1).ops := taicpu(hp2).ops;
  6758. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  6759. case taicpu(hp2).ops of
  6760. 0:
  6761. taicpu(hp1).clearop(0);
  6762. 1:
  6763. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  6764. else
  6765. internalerror(2016041302);
  6766. end;
  6767. end;
  6768. {$ifndef i8086}
  6769. end
  6770. {
  6771. convert
  6772. j<c> .L1
  6773. mov 1,reg
  6774. jmp .L2
  6775. .L1
  6776. mov 0,reg
  6777. .L2
  6778. into
  6779. mov 0,reg
  6780. set<not(c)> reg
  6781. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6782. would destroy the flag contents
  6783. }
  6784. else if MatchInstruction(hp1,A_MOV,[]) and
  6785. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6786. {$ifdef i386}
  6787. (
  6788. { Under i386, ESI, EDI, EBP and ESP
  6789. don't have an 8-bit representation }
  6790. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6791. ) and
  6792. {$endif i386}
  6793. (taicpu(hp1).oper[0]^.val=1) and
  6794. GetNextInstruction(hp1,hp2) and
  6795. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6796. GetNextInstruction(hp2,hp3) and
  6797. { skip align }
  6798. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  6799. (hp3.typ=ait_label) and
  6800. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6801. (tai_label(hp3).labsym.getrefs=1) and
  6802. GetNextInstruction(hp3,hp4) and
  6803. MatchInstruction(hp4,A_MOV,[]) and
  6804. MatchOpType(taicpu(hp4),top_const,top_reg) and
  6805. (taicpu(hp4).oper[0]^.val=0) and
  6806. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6807. GetNextInstruction(hp4,hp5) and
  6808. (hp5.typ=ait_label) and
  6809. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  6810. (tai_label(hp5).labsym.getrefs=1) then
  6811. begin
  6812. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  6813. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  6814. { remove last label }
  6815. RemoveInstruction(hp5);
  6816. { remove second label }
  6817. RemoveInstruction(hp3);
  6818. { if align is present remove it }
  6819. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  6820. RemoveInstruction(hp3);
  6821. { remove jmp }
  6822. RemoveInstruction(hp2);
  6823. if taicpu(hp1).opsize=S_B then
  6824. RemoveInstruction(hp1)
  6825. else
  6826. taicpu(hp1).loadconst(0,0);
  6827. taicpu(hp4).opcode:=A_SETcc;
  6828. taicpu(hp4).opsize:=S_B;
  6829. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  6830. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  6831. taicpu(hp4).opercnt:=1;
  6832. taicpu(hp4).ops:=1;
  6833. taicpu(hp4).freeop(1);
  6834. RemoveCurrentP(p);
  6835. Result:=true;
  6836. exit;
  6837. end
  6838. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  6839. begin
  6840. { check for
  6841. jCC xxx
  6842. <several movs>
  6843. xxx:
  6844. }
  6845. l:=0;
  6846. while assigned(hp1) and
  6847. CanBeCMOV(hp1) and
  6848. { stop on labels }
  6849. not(hp1.typ=ait_label) do
  6850. begin
  6851. inc(l);
  6852. GetNextInstruction(hp1,hp1);
  6853. end;
  6854. if assigned(hp1) then
  6855. begin
  6856. if FindLabel(tasmlabel(symbol),hp1) then
  6857. begin
  6858. if (l<=4) and (l>0) then
  6859. begin
  6860. condition:=inverse_cond(taicpu(p).condition);
  6861. GetNextInstruction(p,hp1);
  6862. repeat
  6863. if not Assigned(hp1) then
  6864. InternalError(2018062900);
  6865. taicpu(hp1).opcode:=A_CMOVcc;
  6866. taicpu(hp1).condition:=condition;
  6867. UpdateUsedRegs(hp1);
  6868. GetNextInstruction(hp1,hp1);
  6869. until not(CanBeCMOV(hp1));
  6870. { Remember what hp1 is in case there's multiple aligns to get rid of }
  6871. hp2 := hp1;
  6872. repeat
  6873. if not Assigned(hp2) then
  6874. InternalError(2018062910);
  6875. case hp2.typ of
  6876. ait_label:
  6877. { What we expected - break out of the loop (it won't be a dead label at the top of
  6878. a cluster because that was optimised at an earlier stage) }
  6879. Break;
  6880. ait_align:
  6881. { Go to the next entry until a label is found (may be multiple aligns before it) }
  6882. begin
  6883. hp2 := tai(hp2.Next);
  6884. Continue;
  6885. end;
  6886. else
  6887. begin
  6888. { Might be a comment or temporary allocation entry }
  6889. if not (hp2.typ in SkipInstr) then
  6890. InternalError(2018062911);
  6891. hp2 := tai(hp2.Next);
  6892. Continue;
  6893. end;
  6894. end;
  6895. until False;
  6896. { Now we can safely decrement the reference count }
  6897. tasmlabel(symbol).decrefs;
  6898. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  6899. { Remove the original jump }
  6900. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6901. GetNextInstruction(hp2, p); { Instruction after the label }
  6902. { Remove the label if this is its final reference }
  6903. if (tasmlabel(symbol).getrefs=0) then
  6904. StripLabelFast(hp1);
  6905. if Assigned(p) then
  6906. begin
  6907. UpdateUsedRegs(p);
  6908. result:=true;
  6909. end;
  6910. exit;
  6911. end;
  6912. end
  6913. else
  6914. begin
  6915. { check further for
  6916. jCC xxx
  6917. <several movs 1>
  6918. jmp yyy
  6919. xxx:
  6920. <several movs 2>
  6921. yyy:
  6922. }
  6923. { hp2 points to jmp yyy }
  6924. hp2:=hp1;
  6925. { skip hp1 to xxx (or an align right before it) }
  6926. GetNextInstruction(hp1, hp1);
  6927. if assigned(hp2) and
  6928. assigned(hp1) and
  6929. (l<=3) and
  6930. (hp2.typ=ait_instruction) and
  6931. (taicpu(hp2).is_jmp) and
  6932. (taicpu(hp2).condition=C_None) and
  6933. { real label and jump, no further references to the
  6934. label are allowed }
  6935. (tasmlabel(symbol).getrefs=1) and
  6936. FindLabel(tasmlabel(symbol),hp1) then
  6937. begin
  6938. l:=0;
  6939. { skip hp1 to <several moves 2> }
  6940. if (hp1.typ = ait_align) then
  6941. GetNextInstruction(hp1, hp1);
  6942. GetNextInstruction(hp1, hpmov2);
  6943. hp1 := hpmov2;
  6944. while assigned(hp1) and
  6945. CanBeCMOV(hp1) do
  6946. begin
  6947. inc(l);
  6948. GetNextInstruction(hp1, hp1);
  6949. end;
  6950. { hp1 points to yyy (or an align right before it) }
  6951. hp3 := hp1;
  6952. if assigned(hp1) and
  6953. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  6954. begin
  6955. condition:=inverse_cond(taicpu(p).condition);
  6956. GetNextInstruction(p,hp1);
  6957. repeat
  6958. taicpu(hp1).opcode:=A_CMOVcc;
  6959. taicpu(hp1).condition:=condition;
  6960. UpdateUsedRegs(hp1);
  6961. GetNextInstruction(hp1,hp1);
  6962. until not(assigned(hp1)) or
  6963. not(CanBeCMOV(hp1));
  6964. condition:=inverse_cond(condition);
  6965. hp1 := hpmov2;
  6966. { hp1 is now at <several movs 2> }
  6967. while Assigned(hp1) and CanBeCMOV(hp1) do
  6968. begin
  6969. taicpu(hp1).opcode:=A_CMOVcc;
  6970. taicpu(hp1).condition:=condition;
  6971. UpdateUsedRegs(hp1);
  6972. GetNextInstruction(hp1,hp1);
  6973. end;
  6974. hp1 := p;
  6975. { Get first instruction after label }
  6976. GetNextInstruction(hp3, p);
  6977. if assigned(p) and (hp3.typ = ait_align) then
  6978. GetNextInstruction(p, p);
  6979. { Don't dereference yet, as doing so will cause
  6980. GetNextInstruction to skip the label and
  6981. optional align marker. [Kit] }
  6982. GetNextInstruction(hp2, hp4);
  6983. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  6984. { remove jCC }
  6985. RemoveInstruction(hp1);
  6986. { Now we can safely decrement it }
  6987. tasmlabel(symbol).decrefs;
  6988. { Remove label xxx (it will have a ref of zero due to the initial check }
  6989. StripLabelFast(hp4);
  6990. { remove jmp }
  6991. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  6992. RemoveInstruction(hp2);
  6993. { As before, now we can safely decrement it }
  6994. tasmlabel(symbol).decrefs;
  6995. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  6996. if tasmlabel(symbol).getrefs = 0 then
  6997. StripLabelFast(hp3);
  6998. if Assigned(p) then
  6999. begin
  7000. UpdateUsedRegs(p);
  7001. result:=true;
  7002. end;
  7003. exit;
  7004. end;
  7005. end;
  7006. end;
  7007. end;
  7008. {$endif i8086}
  7009. end;
  7010. end;
  7011. end;
  7012. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7013. var
  7014. hp1,hp2: tai;
  7015. reg_and_hp1_is_instr: Boolean;
  7016. begin
  7017. result:=false;
  7018. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7019. GetNextInstruction(p,hp1) and
  7020. (hp1.typ = ait_instruction);
  7021. if reg_and_hp1_is_instr and
  7022. (
  7023. (taicpu(hp1).opcode <> A_LEA) or
  7024. { If the LEA instruction can be converted into an arithmetic instruction,
  7025. it may be possible to then fold it. }
  7026. (
  7027. { If the flags register is in use, don't change the instruction
  7028. to an ADD otherwise this will scramble the flags. [Kit] }
  7029. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7030. ConvertLEA(taicpu(hp1))
  7031. )
  7032. ) and
  7033. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7034. GetNextInstruction(hp1,hp2) and
  7035. MatchInstruction(hp2,A_MOV,[]) and
  7036. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7037. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7038. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7039. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7040. {$ifdef i386}
  7041. { not all registers have byte size sub registers on i386 }
  7042. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7043. {$endif i386}
  7044. (((taicpu(hp1).ops=2) and
  7045. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7046. ((taicpu(hp1).ops=1) and
  7047. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7048. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7049. begin
  7050. { change movsX/movzX reg/ref, reg2
  7051. add/sub/or/... reg3/$const, reg2
  7052. mov reg2 reg/ref
  7053. to add/sub/or/... reg3/$const, reg/ref }
  7054. { by example:
  7055. movswl %si,%eax movswl %si,%eax p
  7056. decl %eax addl %edx,%eax hp1
  7057. movw %ax,%si movw %ax,%si hp2
  7058. ->
  7059. movswl %si,%eax movswl %si,%eax p
  7060. decw %eax addw %edx,%eax hp1
  7061. movw %ax,%si movw %ax,%si hp2
  7062. }
  7063. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7064. {
  7065. ->
  7066. movswl %si,%eax movswl %si,%eax p
  7067. decw %si addw %dx,%si hp1
  7068. movw %ax,%si movw %ax,%si hp2
  7069. }
  7070. case taicpu(hp1).ops of
  7071. 1:
  7072. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7073. 2:
  7074. begin
  7075. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7076. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7077. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7078. end;
  7079. else
  7080. internalerror(2008042702);
  7081. end;
  7082. {
  7083. ->
  7084. decw %si addw %dx,%si p
  7085. }
  7086. DebugMsg(SPeepholeOptimization + 'var3',p);
  7087. RemoveCurrentP(p, hp1);
  7088. RemoveInstruction(hp2);
  7089. end
  7090. else if reg_and_hp1_is_instr and
  7091. (taicpu(hp1).opcode = A_MOV) and
  7092. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7093. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7094. {$ifdef x86_64}
  7095. { check for implicit extension to 64 bit }
  7096. or
  7097. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7098. (taicpu(hp1).opsize=S_Q) and
  7099. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7100. )
  7101. {$endif x86_64}
  7102. )
  7103. then
  7104. begin
  7105. { change
  7106. movx %reg1,%reg2
  7107. mov %reg2,%reg3
  7108. dealloc %reg2
  7109. into
  7110. movx %reg,%reg3
  7111. }
  7112. TransferUsedRegs(TmpUsedRegs);
  7113. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7114. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7115. begin
  7116. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7117. {$ifdef x86_64}
  7118. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7119. (taicpu(hp1).opsize=S_Q) then
  7120. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7121. else
  7122. {$endif x86_64}
  7123. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7124. RemoveInstruction(hp1);
  7125. end;
  7126. end
  7127. else if reg_and_hp1_is_instr and
  7128. (taicpu(hp1).opcode = A_MOV) and
  7129. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7130. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7131. (taicpu(hp1).opsize=S_B)) or
  7132. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7133. (taicpu(hp1).opsize=S_W))
  7134. {$ifdef x86_64}
  7135. or ((taicpu(p).opsize=S_LQ) and
  7136. (taicpu(hp1).opsize=S_L))
  7137. {$endif x86_64}
  7138. ) and
  7139. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7140. begin
  7141. { change
  7142. movx %reg1,%reg2
  7143. mov %reg2,%reg3
  7144. dealloc %reg2
  7145. into
  7146. mov %reg1,%reg3
  7147. if the second mov accesses only the bits stored in reg1
  7148. }
  7149. TransferUsedRegs(TmpUsedRegs);
  7150. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7151. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7152. begin
  7153. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7154. if taicpu(p).oper[0]^.typ=top_reg then
  7155. begin
  7156. case taicpu(hp1).opsize of
  7157. S_B:
  7158. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7159. S_W:
  7160. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7161. S_L:
  7162. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7163. else
  7164. Internalerror(2020102301);
  7165. end;
  7166. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7167. end
  7168. else
  7169. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7170. RemoveCurrentP(p);
  7171. result:=true;
  7172. exit;
  7173. end;
  7174. end
  7175. else if reg_and_hp1_is_instr and
  7176. (taicpu(p).oper[0]^.typ = top_reg) and
  7177. (
  7178. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7179. ) and
  7180. (taicpu(hp1).oper[0]^.typ = top_const) and
  7181. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7182. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7183. { Minimum shift value allowed is the bit difference between the sizes }
  7184. (taicpu(hp1).oper[0]^.val >=
  7185. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7186. 8 * (
  7187. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7188. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7189. )
  7190. ) then
  7191. begin
  7192. { For:
  7193. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7194. shl/sal ##, %reg1
  7195. Remove the movsx/movzx instruction if the shift overwrites the
  7196. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7197. }
  7198. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7199. RemoveCurrentP(p, hp1);
  7200. Result := True;
  7201. Exit;
  7202. end
  7203. else if reg_and_hp1_is_instr and
  7204. (taicpu(p).oper[0]^.typ = top_reg) and
  7205. (
  7206. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  7207. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  7208. ) and
  7209. (taicpu(hp1).oper[0]^.typ = top_const) and
  7210. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7211. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7212. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  7213. (taicpu(hp1).oper[0]^.val <
  7214. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7215. 8 * (
  7216. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7217. )
  7218. ) then
  7219. begin
  7220. { For:
  7221. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  7222. sar ##, %reg1 shr ##, %reg1
  7223. Move the shift to before the movx instruction if the shift value
  7224. is not too large.
  7225. }
  7226. asml.Remove(hp1);
  7227. asml.InsertBefore(hp1, p);
  7228. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  7229. case taicpu(p).opsize of
  7230. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  7231. taicpu(hp1).opsize := S_B;
  7232. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  7233. taicpu(hp1).opsize := S_W;
  7234. {$ifdef x86_64}
  7235. S_LQ:
  7236. taicpu(hp1).opsize := S_L;
  7237. {$endif}
  7238. else
  7239. InternalError(2020112401);
  7240. end;
  7241. if (taicpu(hp1).opcode = A_SHR) then
  7242. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  7243. else
  7244. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  7245. Result := True;
  7246. end
  7247. else if taicpu(p).opcode=A_MOVZX then
  7248. begin
  7249. { removes superfluous And's after movzx's }
  7250. if reg_and_hp1_is_instr and
  7251. (taicpu(hp1).opcode = A_AND) and
  7252. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7253. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  7254. {$ifdef x86_64}
  7255. { check for implicit extension to 64 bit }
  7256. or
  7257. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7258. (taicpu(hp1).opsize=S_Q) and
  7259. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  7260. )
  7261. {$endif x86_64}
  7262. )
  7263. then
  7264. begin
  7265. case taicpu(p).opsize Of
  7266. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7267. if (taicpu(hp1).oper[0]^.val = $ff) then
  7268. begin
  7269. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  7270. RemoveInstruction(hp1);
  7271. Result:=true;
  7272. exit;
  7273. end;
  7274. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7275. if (taicpu(hp1).oper[0]^.val = $ffff) then
  7276. begin
  7277. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  7278. RemoveInstruction(hp1);
  7279. Result:=true;
  7280. exit;
  7281. end;
  7282. {$ifdef x86_64}
  7283. S_LQ:
  7284. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  7285. begin
  7286. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  7287. RemoveInstruction(hp1);
  7288. Result:=true;
  7289. exit;
  7290. end;
  7291. {$endif x86_64}
  7292. else
  7293. ;
  7294. end;
  7295. { we cannot get rid of the and, but can we get rid of the movz ?}
  7296. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  7297. begin
  7298. case taicpu(p).opsize Of
  7299. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7300. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  7301. begin
  7302. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  7303. RemoveCurrentP(p,hp1);
  7304. Result:=true;
  7305. exit;
  7306. end;
  7307. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7308. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  7309. begin
  7310. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  7311. RemoveCurrentP(p,hp1);
  7312. Result:=true;
  7313. exit;
  7314. end;
  7315. {$ifdef x86_64}
  7316. S_LQ:
  7317. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  7318. begin
  7319. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  7320. RemoveCurrentP(p,hp1);
  7321. Result:=true;
  7322. exit;
  7323. end;
  7324. {$endif x86_64}
  7325. else
  7326. ;
  7327. end;
  7328. end;
  7329. end;
  7330. { changes some movzx constructs to faster synonyms (all examples
  7331. are given with eax/ax, but are also valid for other registers)}
  7332. if MatchOpType(taicpu(p),top_reg,top_reg) then
  7333. begin
  7334. case taicpu(p).opsize of
  7335. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  7336. (the machine code is equivalent to movzbl %al,%eax), but the
  7337. code generator still generates that assembler instruction and
  7338. it is silently converted. This should probably be checked.
  7339. [Kit] }
  7340. S_BW:
  7341. begin
  7342. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7343. (
  7344. not IsMOVZXAcceptable
  7345. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  7346. or (
  7347. (cs_opt_size in current_settings.optimizerswitches) and
  7348. (taicpu(p).oper[1]^.reg = NR_AX)
  7349. )
  7350. ) then
  7351. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  7352. begin
  7353. DebugMsg(SPeepholeOptimization + 'var7',p);
  7354. taicpu(p).opcode := A_AND;
  7355. taicpu(p).changeopsize(S_W);
  7356. taicpu(p).loadConst(0,$ff);
  7357. Result := True;
  7358. end
  7359. else if not IsMOVZXAcceptable and
  7360. GetNextInstruction(p, hp1) and
  7361. (tai(hp1).typ = ait_instruction) and
  7362. (taicpu(hp1).opcode = A_AND) and
  7363. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7364. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7365. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  7366. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  7367. begin
  7368. DebugMsg(SPeepholeOptimization + 'var8',p);
  7369. taicpu(p).opcode := A_MOV;
  7370. taicpu(p).changeopsize(S_W);
  7371. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  7372. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7373. Result := True;
  7374. end;
  7375. end;
  7376. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  7377. S_BL:
  7378. begin
  7379. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7380. (
  7381. not IsMOVZXAcceptable
  7382. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  7383. or (
  7384. (cs_opt_size in current_settings.optimizerswitches) and
  7385. (taicpu(p).oper[1]^.reg = NR_EAX)
  7386. )
  7387. ) then
  7388. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  7389. begin
  7390. DebugMsg(SPeepholeOptimization + 'var9',p);
  7391. taicpu(p).opcode := A_AND;
  7392. taicpu(p).changeopsize(S_L);
  7393. taicpu(p).loadConst(0,$ff);
  7394. Result := True;
  7395. end
  7396. else if not IsMOVZXAcceptable and
  7397. GetNextInstruction(p, hp1) and
  7398. (tai(hp1).typ = ait_instruction) and
  7399. (taicpu(hp1).opcode = A_AND) and
  7400. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7401. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7402. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  7403. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  7404. begin
  7405. DebugMsg(SPeepholeOptimization + 'var10',p);
  7406. taicpu(p).opcode := A_MOV;
  7407. taicpu(p).changeopsize(S_L);
  7408. { do not use R_SUBWHOLE
  7409. as movl %rdx,%eax
  7410. is invalid in assembler PM }
  7411. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7412. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7413. Result := True;
  7414. end;
  7415. end;
  7416. {$endif i8086}
  7417. S_WL:
  7418. if not IsMOVZXAcceptable then
  7419. begin
  7420. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  7421. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  7422. begin
  7423. DebugMsg(SPeepholeOptimization + 'var11',p);
  7424. taicpu(p).opcode := A_AND;
  7425. taicpu(p).changeopsize(S_L);
  7426. taicpu(p).loadConst(0,$ffff);
  7427. Result := True;
  7428. end
  7429. else if GetNextInstruction(p, hp1) and
  7430. (tai(hp1).typ = ait_instruction) and
  7431. (taicpu(hp1).opcode = A_AND) and
  7432. (taicpu(hp1).oper[0]^.typ = top_const) and
  7433. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7434. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7435. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  7436. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  7437. begin
  7438. DebugMsg(SPeepholeOptimization + 'var12',p);
  7439. taicpu(p).opcode := A_MOV;
  7440. taicpu(p).changeopsize(S_L);
  7441. { do not use R_SUBWHOLE
  7442. as movl %rdx,%eax
  7443. is invalid in assembler PM }
  7444. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7445. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7446. Result := True;
  7447. end;
  7448. end;
  7449. else
  7450. InternalError(2017050705);
  7451. end;
  7452. end
  7453. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  7454. begin
  7455. if GetNextInstruction(p, hp1) and
  7456. (tai(hp1).typ = ait_instruction) and
  7457. (taicpu(hp1).opcode = A_AND) and
  7458. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7459. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7460. begin
  7461. //taicpu(p).opcode := A_MOV;
  7462. case taicpu(p).opsize Of
  7463. S_BL:
  7464. begin
  7465. DebugMsg(SPeepholeOptimization + 'var13',p);
  7466. taicpu(hp1).changeopsize(S_L);
  7467. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7468. end;
  7469. S_WL:
  7470. begin
  7471. DebugMsg(SPeepholeOptimization + 'var14',p);
  7472. taicpu(hp1).changeopsize(S_L);
  7473. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7474. end;
  7475. S_BW:
  7476. begin
  7477. DebugMsg(SPeepholeOptimization + 'var15',p);
  7478. taicpu(hp1).changeopsize(S_W);
  7479. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7480. end;
  7481. else
  7482. Internalerror(2017050704)
  7483. end;
  7484. Result := True;
  7485. end;
  7486. end;
  7487. end;
  7488. end;
  7489. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  7490. var
  7491. hp1, hp2 : tai;
  7492. MaskLength : Cardinal;
  7493. MaskedBits : TCgInt;
  7494. begin
  7495. Result:=false;
  7496. { There are no optimisations for reference targets }
  7497. if (taicpu(p).oper[1]^.typ <> top_reg) then
  7498. Exit;
  7499. while GetNextInstruction(p, hp1) and
  7500. (hp1.typ = ait_instruction) do
  7501. begin
  7502. if (taicpu(p).oper[0]^.typ = top_const) then
  7503. begin
  7504. if (taicpu(hp1).opcode = A_AND) and
  7505. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7506. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7507. { the second register must contain the first one, so compare their subreg types }
  7508. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  7509. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  7510. { change
  7511. and const1, reg
  7512. and const2, reg
  7513. to
  7514. and (const1 and const2), reg
  7515. }
  7516. begin
  7517. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  7518. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  7519. RemoveCurrentP(p, hp1);
  7520. Result:=true;
  7521. exit;
  7522. end
  7523. else if (taicpu(hp1).opcode = A_MOVZX) and
  7524. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7525. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  7526. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7527. (((taicpu(p).opsize=S_W) and
  7528. (taicpu(hp1).opsize=S_BW)) or
  7529. ((taicpu(p).opsize=S_L) and
  7530. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}]))
  7531. {$ifdef x86_64}
  7532. or
  7533. ((taicpu(p).opsize=S_Q) and
  7534. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL]))
  7535. {$endif x86_64}
  7536. ) then
  7537. begin
  7538. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7539. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  7540. ) or
  7541. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7542. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  7543. then
  7544. begin
  7545. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  7546. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  7547. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  7548. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  7549. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  7550. }
  7551. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  7552. RemoveInstruction(hp1);
  7553. { See if there are other optimisations possible }
  7554. Continue;
  7555. end;
  7556. end
  7557. else if (taicpu(hp1).opcode = A_SHL) and
  7558. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7559. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7560. begin
  7561. {$ifopt R+}
  7562. {$define RANGE_WAS_ON}
  7563. {$R-}
  7564. {$endif}
  7565. { get length of potential and mask }
  7566. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  7567. { really a mask? }
  7568. {$ifdef RANGE_WAS_ON}
  7569. {$R+}
  7570. {$endif}
  7571. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  7572. { unmasked part shifted out? }
  7573. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  7574. begin
  7575. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  7576. RemoveCurrentP(p, hp1);
  7577. Result:=true;
  7578. exit;
  7579. end;
  7580. end
  7581. else if (taicpu(hp1).opcode = A_SHR) and
  7582. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7583. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  7584. (taicpu(hp1).oper[0]^.val <= 63) then
  7585. begin
  7586. { Does SHR combined with the AND cover all the bits?
  7587. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  7588. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  7589. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  7590. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  7591. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  7592. begin
  7593. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  7594. RemoveCurrentP(p, hp1);
  7595. Result := True;
  7596. Exit;
  7597. end;
  7598. end
  7599. else if ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}) and
  7600. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7601. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7602. begin
  7603. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  7604. (
  7605. (
  7606. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7607. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  7608. ) or (
  7609. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7610. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  7611. {$ifdef x86_64}
  7612. ) or (
  7613. (taicpu(hp1).opsize = S_LQ) and
  7614. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  7615. {$endif x86_64}
  7616. )
  7617. ) then
  7618. begin
  7619. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  7620. begin
  7621. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  7622. RemoveInstruction(hp1);
  7623. { See if there are other optimisations possible }
  7624. Continue;
  7625. end;
  7626. { The super-registers are the same though.
  7627. Note that this change by itself doesn't improve
  7628. code speed, but it opens up other optimisations. }
  7629. {$ifdef x86_64}
  7630. { Convert 64-bit register to 32-bit }
  7631. case taicpu(hp1).opsize of
  7632. S_BQ:
  7633. begin
  7634. taicpu(hp1).opsize := S_BL;
  7635. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  7636. end;
  7637. S_WQ:
  7638. begin
  7639. taicpu(hp1).opsize := S_WL;
  7640. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  7641. end
  7642. else
  7643. ;
  7644. end;
  7645. {$endif x86_64}
  7646. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  7647. taicpu(hp1).opcode := A_MOVZX;
  7648. { See if there are other optimisations possible }
  7649. Continue;
  7650. end;
  7651. end;
  7652. end;
  7653. if (taicpu(hp1).is_jmp) and
  7654. (taicpu(hp1).opcode<>A_JMP) and
  7655. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  7656. begin
  7657. { change
  7658. and x, reg
  7659. jxx
  7660. to
  7661. test x, reg
  7662. jxx
  7663. if reg is deallocated before the
  7664. jump, but only if it's a conditional jump (PFV)
  7665. }
  7666. taicpu(p).opcode := A_TEST;
  7667. Exit;
  7668. end;
  7669. Break;
  7670. end;
  7671. { Lone AND tests }
  7672. if (taicpu(p).oper[0]^.typ = top_const) then
  7673. begin
  7674. {
  7675. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  7676. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  7677. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  7678. }
  7679. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  7680. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  7681. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  7682. begin
  7683. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7684. if taicpu(p).opsize = S_L then
  7685. begin
  7686. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  7687. Result := True;
  7688. end;
  7689. end;
  7690. end;
  7691. { Backward check to determine necessity of and %reg,%reg }
  7692. if (taicpu(p).oper[0]^.typ = top_reg) and
  7693. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  7694. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7695. GetLastInstruction(p, hp2) and
  7696. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  7697. { Check size of adjacent instruction to determine if the AND is
  7698. effectively a null operation }
  7699. (
  7700. (taicpu(p).opsize = taicpu(hp2).opsize) or
  7701. { Note: Don't include S_Q }
  7702. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  7703. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  7704. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  7705. ) then
  7706. begin
  7707. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  7708. { If GetNextInstruction returned False, hp1 will be nil }
  7709. RemoveCurrentP(p, hp1);
  7710. Result := True;
  7711. Exit;
  7712. end;
  7713. end;
  7714. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  7715. var
  7716. hp1: tai; NewRef: TReference;
  7717. { This entire nested function is used in an if-statement below, but we
  7718. want to avoid all the used reg transfers and GetNextInstruction calls
  7719. until we really have to check }
  7720. function MemRegisterNotUsedLater: Boolean; inline;
  7721. var
  7722. hp2: tai;
  7723. begin
  7724. TransferUsedRegs(TmpUsedRegs);
  7725. hp2 := p;
  7726. repeat
  7727. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7728. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7729. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  7730. end;
  7731. begin
  7732. Result := False;
  7733. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  7734. Exit;
  7735. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  7736. begin
  7737. { Change:
  7738. add %reg2,%reg1
  7739. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  7740. To:
  7741. mov/s/z #(%reg1,%reg2),%reg1
  7742. }
  7743. if MatchOpType(taicpu(p), top_reg, top_reg) and
  7744. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  7745. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  7746. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  7747. (
  7748. (
  7749. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  7750. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  7751. { r/esp cannot be an index }
  7752. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  7753. ) or (
  7754. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  7755. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  7756. )
  7757. ) and (
  7758. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  7759. (
  7760. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  7761. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  7762. MemRegisterNotUsedLater
  7763. )
  7764. ) then
  7765. begin
  7766. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  7767. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  7768. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  7769. RemoveCurrentp(p, hp1);
  7770. Result := True;
  7771. Exit;
  7772. end;
  7773. { Change:
  7774. addl/q $x,%reg1
  7775. movl/q %reg1,%reg2
  7776. To:
  7777. leal/q $x(%reg1),%reg2
  7778. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  7779. Breaks the dependency chain.
  7780. }
  7781. if MatchOpType(taicpu(p),top_const,top_reg) and
  7782. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  7783. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7784. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  7785. (
  7786. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  7787. not (cs_opt_size in current_settings.optimizerswitches) or
  7788. (
  7789. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  7790. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  7791. )
  7792. ) then
  7793. begin
  7794. { Change the MOV instruction to a LEA instruction, and update the
  7795. first operand }
  7796. reference_reset(NewRef, 1, []);
  7797. NewRef.base := taicpu(p).oper[1]^.reg;
  7798. NewRef.scalefactor := 1;
  7799. NewRef.offset := taicpu(p).oper[0]^.val;
  7800. taicpu(hp1).opcode := A_LEA;
  7801. taicpu(hp1).loadref(0, NewRef);
  7802. TransferUsedRegs(TmpUsedRegs);
  7803. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7804. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  7805. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7806. begin
  7807. { Move what is now the LEA instruction to before the SUB instruction }
  7808. Asml.Remove(hp1);
  7809. Asml.InsertBefore(hp1, p);
  7810. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  7811. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  7812. p := hp1;
  7813. end
  7814. else
  7815. begin
  7816. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  7817. RemoveCurrentP(p, hp1);
  7818. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  7819. end;
  7820. Result := True;
  7821. end;
  7822. end;
  7823. end;
  7824. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  7825. begin
  7826. Result:=false;
  7827. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  7828. begin
  7829. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  7830. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  7831. begin
  7832. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  7833. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  7834. taicpu(p).opcode:=A_ADD;
  7835. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  7836. result:=true;
  7837. end
  7838. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  7839. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  7840. begin
  7841. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  7842. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  7843. taicpu(p).opcode:=A_ADD;
  7844. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  7845. result:=true;
  7846. end;
  7847. end;
  7848. end;
  7849. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  7850. var
  7851. hp1: tai; NewRef: TReference;
  7852. begin
  7853. { Change:
  7854. subl/q $x,%reg1
  7855. movl/q %reg1,%reg2
  7856. To:
  7857. leal/q $-x(%reg1),%reg2
  7858. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  7859. Breaks the dependency chain and potentially permits the removal of
  7860. a CMP instruction if one follows.
  7861. }
  7862. Result := False;
  7863. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7864. MatchOpType(taicpu(p),top_const,top_reg) and
  7865. GetNextInstruction(p, hp1) and
  7866. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  7867. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7868. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  7869. (
  7870. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  7871. not (cs_opt_size in current_settings.optimizerswitches) or
  7872. (
  7873. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  7874. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  7875. )
  7876. ) then
  7877. begin
  7878. { Change the MOV instruction to a LEA instruction, and update the
  7879. first operand }
  7880. reference_reset(NewRef, 1, []);
  7881. NewRef.base := taicpu(p).oper[1]^.reg;
  7882. NewRef.scalefactor := 1;
  7883. NewRef.offset := -taicpu(p).oper[0]^.val;
  7884. taicpu(hp1).opcode := A_LEA;
  7885. taicpu(hp1).loadref(0, NewRef);
  7886. TransferUsedRegs(TmpUsedRegs);
  7887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7888. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  7889. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7890. begin
  7891. { Move what is now the LEA instruction to before the SUB instruction }
  7892. Asml.Remove(hp1);
  7893. Asml.InsertBefore(hp1, p);
  7894. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  7895. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  7896. p := hp1;
  7897. end
  7898. else
  7899. begin
  7900. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  7901. RemoveCurrentP(p, hp1);
  7902. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  7903. end;
  7904. Result := True;
  7905. end;
  7906. end;
  7907. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  7908. begin
  7909. { we can skip all instructions not messing with the stack pointer }
  7910. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  7911. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  7912. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  7913. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  7914. ({(taicpu(hp1).ops=0) or }
  7915. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  7916. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  7917. ) and }
  7918. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  7919. )
  7920. ) do
  7921. GetNextInstruction(hp1,hp1);
  7922. Result:=assigned(hp1);
  7923. end;
  7924. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  7925. var
  7926. hp1, hp2, hp3, hp4, hp5: tai;
  7927. begin
  7928. Result:=false;
  7929. hp5:=nil;
  7930. { replace
  7931. leal(q) x(<stackpointer>),<stackpointer>
  7932. call procname
  7933. leal(q) -x(<stackpointer>),<stackpointer>
  7934. ret
  7935. by
  7936. jmp procname
  7937. but do it only on level 4 because it destroys stack back traces
  7938. }
  7939. if (cs_opt_level4 in current_settings.optimizerswitches) and
  7940. MatchOpType(taicpu(p),top_ref,top_reg) and
  7941. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  7942. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  7943. { the -8 or -24 are not required, but bail out early if possible,
  7944. higher values are unlikely }
  7945. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  7946. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  7947. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  7948. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  7949. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  7950. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  7951. GetNextInstruction(p, hp1) and
  7952. { Take a copy of hp1 }
  7953. SetAndTest(hp1, hp4) and
  7954. { trick to skip label }
  7955. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  7956. SkipSimpleInstructions(hp1) and
  7957. MatchInstruction(hp1,A_CALL,[S_NO]) and
  7958. GetNextInstruction(hp1, hp2) and
  7959. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  7960. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  7961. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  7962. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  7963. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  7964. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  7965. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  7966. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  7967. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  7968. GetNextInstruction(hp2, hp3) and
  7969. { trick to skip label }
  7970. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  7971. (MatchInstruction(hp3,A_RET,[S_NO]) or
  7972. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  7973. SetAndTest(hp3,hp5) and
  7974. GetNextInstruction(hp3,hp3) and
  7975. MatchInstruction(hp3,A_RET,[S_NO])
  7976. )
  7977. ) and
  7978. (taicpu(hp3).ops=0) then
  7979. begin
  7980. taicpu(hp1).opcode := A_JMP;
  7981. taicpu(hp1).is_jmp := true;
  7982. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  7983. RemoveCurrentP(p, hp4);
  7984. RemoveInstruction(hp2);
  7985. RemoveInstruction(hp3);
  7986. if Assigned(hp5) then
  7987. begin
  7988. AsmL.Remove(hp5);
  7989. ASmL.InsertBefore(hp5,hp1)
  7990. end;
  7991. Result:=true;
  7992. end;
  7993. end;
  7994. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  7995. {$ifdef x86_64}
  7996. var
  7997. hp1, hp2, hp3, hp4, hp5: tai;
  7998. {$endif x86_64}
  7999. begin
  8000. Result:=false;
  8001. {$ifdef x86_64}
  8002. hp5:=nil;
  8003. { replace
  8004. push %rax
  8005. call procname
  8006. pop %rcx
  8007. ret
  8008. by
  8009. jmp procname
  8010. but do it only on level 4 because it destroys stack back traces
  8011. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8012. for all supported calling conventions
  8013. }
  8014. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8015. MatchOpType(taicpu(p),top_reg) and
  8016. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8017. GetNextInstruction(p, hp1) and
  8018. { Take a copy of hp1 }
  8019. SetAndTest(hp1, hp4) and
  8020. { trick to skip label }
  8021. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8022. SkipSimpleInstructions(hp1) and
  8023. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8024. GetNextInstruction(hp1, hp2) and
  8025. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8026. MatchOpType(taicpu(hp2),top_reg) and
  8027. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8028. GetNextInstruction(hp2, hp3) and
  8029. { trick to skip label }
  8030. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8031. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8032. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8033. SetAndTest(hp3,hp5) and
  8034. GetNextInstruction(hp3,hp3) and
  8035. MatchInstruction(hp3,A_RET,[S_NO])
  8036. )
  8037. ) and
  8038. (taicpu(hp3).ops=0) then
  8039. begin
  8040. taicpu(hp1).opcode := A_JMP;
  8041. taicpu(hp1).is_jmp := true;
  8042. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8043. RemoveCurrentP(p, hp4);
  8044. RemoveInstruction(hp2);
  8045. RemoveInstruction(hp3);
  8046. if Assigned(hp5) then
  8047. begin
  8048. AsmL.Remove(hp5);
  8049. ASmL.InsertBefore(hp5,hp1)
  8050. end;
  8051. Result:=true;
  8052. end;
  8053. {$endif x86_64}
  8054. end;
  8055. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8056. var
  8057. Value, RegName: string;
  8058. begin
  8059. Result:=false;
  8060. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8061. begin
  8062. case taicpu(p).oper[0]^.val of
  8063. 0:
  8064. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8065. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8066. begin
  8067. { change "mov $0,%reg" into "xor %reg,%reg" }
  8068. taicpu(p).opcode := A_XOR;
  8069. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8070. Result := True;
  8071. end;
  8072. $1..$FFFFFFFF:
  8073. begin
  8074. { Code size reduction by J. Gareth "Kit" Moreton }
  8075. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8076. case taicpu(p).opsize of
  8077. S_Q:
  8078. begin
  8079. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8080. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8081. { The actual optimization }
  8082. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8083. taicpu(p).changeopsize(S_L);
  8084. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8085. Result := True;
  8086. end;
  8087. else
  8088. { Do nothing };
  8089. end;
  8090. end;
  8091. -1:
  8092. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8093. if (cs_opt_size in current_settings.optimizerswitches) and
  8094. (taicpu(p).opsize <> S_B) and
  8095. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8096. begin
  8097. { change "mov $-1,%reg" into "or $-1,%reg" }
  8098. { NOTES:
  8099. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8100. - This operation creates a false dependency on the register, so only do it when optimising for size
  8101. - 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
  8102. }
  8103. taicpu(p).opcode := A_OR;
  8104. Result := True;
  8105. end;
  8106. end;
  8107. end;
  8108. end;
  8109. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8110. var
  8111. hp1: tai;
  8112. begin
  8113. { Detect:
  8114. andw x, %ax (0 <= x < $8000)
  8115. ...
  8116. movzwl %ax,%eax
  8117. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8118. }
  8119. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8120. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8121. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8122. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8123. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8124. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8125. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8126. begin
  8127. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8128. taicpu(hp1).opcode := A_CWDE;
  8129. taicpu(hp1).clearop(0);
  8130. taicpu(hp1).clearop(1);
  8131. taicpu(hp1).ops := 0;
  8132. { A change was made, but not with p, so move forward 1 }
  8133. p := tai(p.Next);
  8134. Result := True;
  8135. end;
  8136. end;
  8137. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8138. begin
  8139. Result := False;
  8140. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8141. Exit;
  8142. { Convert:
  8143. movswl %ax,%eax -> cwtl
  8144. movslq %eax,%rax -> cdqe
  8145. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8146. refer to the same opcode and depends only on the assembler's
  8147. current operand-size attribute. [Kit]
  8148. }
  8149. with taicpu(p) do
  8150. case opsize of
  8151. S_WL:
  8152. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8153. begin
  8154. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8155. opcode := A_CWDE;
  8156. clearop(0);
  8157. clearop(1);
  8158. ops := 0;
  8159. Result := True;
  8160. end;
  8161. {$ifdef x86_64}
  8162. S_LQ:
  8163. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8164. begin
  8165. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  8166. opcode := A_CDQE;
  8167. clearop(0);
  8168. clearop(1);
  8169. ops := 0;
  8170. Result := True;
  8171. end;
  8172. {$endif x86_64}
  8173. else
  8174. ;
  8175. end;
  8176. end;
  8177. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  8178. var
  8179. hp1: tai;
  8180. begin
  8181. { Detect:
  8182. shr x, %ax (x > 0)
  8183. ...
  8184. movzwl %ax,%eax
  8185. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8186. }
  8187. Result := False;
  8188. if MatchOpType(taicpu(p), top_const, top_reg) and
  8189. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8190. (taicpu(p).oper[0]^.val > 0) and
  8191. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8192. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8193. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8194. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8195. begin
  8196. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  8197. taicpu(hp1).opcode := A_CWDE;
  8198. taicpu(hp1).clearop(0);
  8199. taicpu(hp1).clearop(1);
  8200. taicpu(hp1).ops := 0;
  8201. { A change was made, but not with p, so move forward 1 }
  8202. p := tai(p.Next);
  8203. Result := True;
  8204. end;
  8205. end;
  8206. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  8207. begin
  8208. Result:=false;
  8209. { change "cmp $0, %reg" to "test %reg, %reg" }
  8210. if MatchOpType(taicpu(p),top_const,top_reg) and
  8211. (taicpu(p).oper[0]^.val = 0) then
  8212. begin
  8213. taicpu(p).opcode := A_TEST;
  8214. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8215. Result:=true;
  8216. end;
  8217. end;
  8218. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  8219. var
  8220. IsTestConstX : Boolean;
  8221. hp1,hp2 : tai;
  8222. begin
  8223. Result:=false;
  8224. { removes the line marked with (x) from the sequence
  8225. and/or/xor/add/sub/... $x, %y
  8226. test/or %y, %y | test $-1, %y (x)
  8227. j(n)z _Label
  8228. as the first instruction already adjusts the ZF
  8229. %y operand may also be a reference }
  8230. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  8231. MatchOperand(taicpu(p).oper[0]^,-1);
  8232. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  8233. GetLastInstruction(p, hp1) and
  8234. (tai(hp1).typ = ait_instruction) and
  8235. GetNextInstruction(p,hp2) and
  8236. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  8237. case taicpu(hp1).opcode Of
  8238. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  8239. begin
  8240. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8241. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8242. { and in case of carry for A(E)/B(E)/C/NC }
  8243. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  8244. ((taicpu(hp1).opcode <> A_ADD) and
  8245. (taicpu(hp1).opcode <> A_SUB))) then
  8246. begin
  8247. RemoveCurrentP(p, hp2);
  8248. Result:=true;
  8249. Exit;
  8250. end;
  8251. end;
  8252. A_SHL, A_SAL, A_SHR, A_SAR:
  8253. begin
  8254. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8255. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  8256. { therefore, it's only safe to do this optimization for }
  8257. { shifts by a (nonzero) constant }
  8258. (taicpu(hp1).oper[0]^.typ = top_const) and
  8259. (taicpu(hp1).oper[0]^.val <> 0) and
  8260. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8261. { and in case of carry for A(E)/B(E)/C/NC }
  8262. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8263. begin
  8264. RemoveCurrentP(p, hp2);
  8265. Result:=true;
  8266. Exit;
  8267. end;
  8268. end;
  8269. A_DEC, A_INC, A_NEG:
  8270. begin
  8271. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  8272. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8273. { and in case of carry for A(E)/B(E)/C/NC }
  8274. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8275. begin
  8276. case taicpu(hp1).opcode of
  8277. A_DEC, A_INC:
  8278. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  8279. begin
  8280. case taicpu(hp1).opcode Of
  8281. A_DEC: taicpu(hp1).opcode := A_SUB;
  8282. A_INC: taicpu(hp1).opcode := A_ADD;
  8283. else
  8284. ;
  8285. end;
  8286. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  8287. taicpu(hp1).loadConst(0,1);
  8288. taicpu(hp1).ops:=2;
  8289. end;
  8290. else
  8291. ;
  8292. end;
  8293. RemoveCurrentP(p, hp2);
  8294. Result:=true;
  8295. Exit;
  8296. end;
  8297. end
  8298. else
  8299. ;
  8300. end; { case }
  8301. { change "test $-1,%reg" into "test %reg,%reg" }
  8302. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  8303. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  8304. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  8305. if MatchInstruction(p, A_OR, []) and
  8306. { Can only match if they're both registers }
  8307. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  8308. begin
  8309. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  8310. taicpu(p).opcode := A_TEST;
  8311. { No need to set Result to True, as we've done all the optimisations we can }
  8312. end;
  8313. end;
  8314. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  8315. var
  8316. hp1,hp3 : tai;
  8317. {$ifndef x86_64}
  8318. hp2 : taicpu;
  8319. {$endif x86_64}
  8320. begin
  8321. Result:=false;
  8322. hp3:=nil;
  8323. {$ifndef x86_64}
  8324. { don't do this on modern CPUs, this really hurts them due to
  8325. broken call/ret pairing }
  8326. if (current_settings.optimizecputype < cpu_Pentium2) and
  8327. not(cs_create_pic in current_settings.moduleswitches) and
  8328. GetNextInstruction(p, hp1) and
  8329. MatchInstruction(hp1,A_JMP,[S_NO]) and
  8330. MatchOpType(taicpu(hp1),top_ref) and
  8331. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8332. begin
  8333. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  8334. InsertLLItem(p.previous, p, hp2);
  8335. taicpu(p).opcode := A_JMP;
  8336. taicpu(p).is_jmp := true;
  8337. RemoveInstruction(hp1);
  8338. Result:=true;
  8339. end
  8340. else
  8341. {$endif x86_64}
  8342. { replace
  8343. call procname
  8344. ret
  8345. by
  8346. jmp procname
  8347. but do it only on level 4 because it destroys stack back traces
  8348. else if the subroutine is marked as no return, remove the ret
  8349. }
  8350. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  8351. (po_noreturn in current_procinfo.procdef.procoptions)) and
  8352. GetNextInstruction(p, hp1) and
  8353. (MatchInstruction(hp1,A_RET,[S_NO]) or
  8354. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  8355. SetAndTest(hp1,hp3) and
  8356. GetNextInstruction(hp1,hp1) and
  8357. MatchInstruction(hp1,A_RET,[S_NO])
  8358. )
  8359. ) and
  8360. (taicpu(hp1).ops=0) then
  8361. begin
  8362. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8363. { we might destroy stack alignment here if we do not do a call }
  8364. (target_info.stackalign<=sizeof(SizeUInt)) then
  8365. begin
  8366. taicpu(p).opcode := A_JMP;
  8367. taicpu(p).is_jmp := true;
  8368. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  8369. end
  8370. else
  8371. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  8372. RemoveInstruction(hp1);
  8373. if Assigned(hp3) then
  8374. begin
  8375. AsmL.Remove(hp3);
  8376. AsmL.InsertBefore(hp3,p)
  8377. end;
  8378. Result:=true;
  8379. end;
  8380. end;
  8381. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  8382. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  8383. begin
  8384. case OpSize of
  8385. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8386. Result := (Val <= $FF) and (Val >= -128);
  8387. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8388. Result := (Val <= $FFFF) and (Val >= -32768);
  8389. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  8390. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  8391. else
  8392. Result := True;
  8393. end;
  8394. end;
  8395. var
  8396. hp1, hp2 : tai;
  8397. SizeChange: Boolean;
  8398. PreMessage: string;
  8399. begin
  8400. Result := False;
  8401. if (taicpu(p).oper[0]^.typ = top_reg) and
  8402. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8403. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  8404. begin
  8405. { Change (using movzbl %al,%eax as an example):
  8406. movzbl %al, %eax movzbl %al, %eax
  8407. cmpl x, %eax testl %eax,%eax
  8408. To:
  8409. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  8410. movzbl %al, %eax movzbl %al, %eax
  8411. Smaller instruction and minimises pipeline stall as the CPU
  8412. doesn't have to wait for the register to get zero-extended. [Kit]
  8413. Also allow if the smaller of the two registers is being checked,
  8414. as this still removes the false dependency.
  8415. }
  8416. if
  8417. (
  8418. (
  8419. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  8420. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  8421. ) or (
  8422. { If MatchOperand returns True, they must both be registers }
  8423. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  8424. )
  8425. ) and
  8426. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  8427. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  8428. begin
  8429. 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);
  8430. asml.Remove(hp1);
  8431. asml.InsertBefore(hp1, p);
  8432. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  8433. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  8434. begin
  8435. taicpu(hp1).opcode := A_TEST;
  8436. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  8437. end;
  8438. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8439. case taicpu(p).opsize of
  8440. S_BW, S_BL:
  8441. begin
  8442. SizeChange := taicpu(hp1).opsize <> S_B;
  8443. taicpu(hp1).changeopsize(S_B);
  8444. end;
  8445. S_WL:
  8446. begin
  8447. SizeChange := taicpu(hp1).opsize <> S_W;
  8448. taicpu(hp1).changeopsize(S_W);
  8449. end
  8450. else
  8451. InternalError(2020112701);
  8452. end;
  8453. UpdateUsedRegs(tai(p.Next));
  8454. { Check if the register is used aferwards - if not, we can
  8455. remove the movzx instruction completely }
  8456. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8457. begin
  8458. { Hp1 is a better position than p for debugging purposes }
  8459. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  8460. RemoveCurrentp(p, hp1);
  8461. Result := True;
  8462. end;
  8463. if SizeChange then
  8464. DebugMsg(SPeepholeOptimization + PreMessage +
  8465. 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)
  8466. else
  8467. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  8468. Exit;
  8469. end;
  8470. { Change (using movzwl %ax,%eax as an example):
  8471. movzwl %ax, %eax
  8472. movb %al, (dest) (Register is smaller than read register in movz)
  8473. To:
  8474. movb %al, (dest) (Move one back to avoid a false dependency)
  8475. movzwl %ax, %eax
  8476. }
  8477. if (taicpu(hp1).opcode = A_MOV) and
  8478. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8479. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  8480. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  8481. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  8482. begin
  8483. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  8484. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  8485. asml.Remove(hp1);
  8486. asml.InsertBefore(hp1, p);
  8487. if taicpu(hp1).oper[1]^.typ = top_reg then
  8488. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  8489. { Check if the register is used aferwards - if not, we can
  8490. remove the movzx instruction completely }
  8491. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  8492. begin
  8493. { Hp1 is a better position than p for debugging purposes }
  8494. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  8495. RemoveCurrentp(p, hp1);
  8496. Result := True;
  8497. end;
  8498. Exit;
  8499. end;
  8500. end;
  8501. {$ifdef x86_64}
  8502. { Code size reduction by J. Gareth "Kit" Moreton }
  8503. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  8504. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  8505. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  8506. then
  8507. begin
  8508. { Has 64-bit register name and opcode suffix }
  8509. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  8510. { The actual optimization }
  8511. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8512. if taicpu(p).opsize = S_BQ then
  8513. taicpu(p).changeopsize(S_BL)
  8514. else
  8515. taicpu(p).changeopsize(S_WL);
  8516. DebugMsg(SPeepholeOptimization + PreMessage +
  8517. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  8518. end;
  8519. {$endif}
  8520. end;
  8521. {$ifdef x86_64}
  8522. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  8523. var
  8524. PreMessage, RegName: string;
  8525. begin
  8526. { Code size reduction by J. Gareth "Kit" Moreton }
  8527. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  8528. as this removes the REX prefix }
  8529. Result := False;
  8530. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  8531. Exit;
  8532. if taicpu(p).oper[0]^.typ <> top_reg then
  8533. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  8534. InternalError(2018011500);
  8535. case taicpu(p).opsize of
  8536. S_Q:
  8537. begin
  8538. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  8539. begin
  8540. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  8541. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  8542. { The actual optimization }
  8543. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8544. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8545. taicpu(p).changeopsize(S_L);
  8546. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  8547. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  8548. end;
  8549. end;
  8550. else
  8551. ;
  8552. end;
  8553. end;
  8554. {$endif}
  8555. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  8556. var
  8557. OperIdx: Integer;
  8558. begin
  8559. for OperIdx := 0 to p.ops - 1 do
  8560. if p.oper[OperIdx]^.typ = top_ref then
  8561. optimize_ref(p.oper[OperIdx]^.ref^, False);
  8562. end;
  8563. end.