aoptx86.pas 561 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  108. function PrePeepholeOptSxx(var p : tai) : boolean;
  109. function PrePeepholeOptIMUL(var p : tai) : boolean;
  110. function PrePeepholeOptAND(var p : tai) : boolean;
  111. function OptPass1Test(var p: tai): boolean;
  112. function OptPass1Add(var p: tai): boolean;
  113. function OptPass1AND(var p : tai) : boolean;
  114. function OptPass1_V_MOVAP(var p : tai) : boolean;
  115. function OptPass1VOP(var p : tai) : boolean;
  116. function OptPass1MOV(var p : tai) : boolean;
  117. function OptPass1Movx(var p : tai) : boolean;
  118. function OptPass1MOVXX(var p : tai) : boolean;
  119. function OptPass1OP(var p : tai) : boolean;
  120. function OptPass1LEA(var p : tai) : boolean;
  121. function OptPass1Sub(var p : tai) : boolean;
  122. function OptPass1SHLSAL(var p : tai) : boolean;
  123. function OptPass1FSTP(var p : tai) : boolean;
  124. function OptPass1FLD(var p : tai) : boolean;
  125. function OptPass1Cmp(var p : tai) : boolean;
  126. function OptPass1PXor(var p : tai) : boolean;
  127. function OptPass1VPXor(var p: tai): boolean;
  128. function OptPass1Imul(var p : tai) : boolean;
  129. function OptPass1Jcc(var p : tai) : boolean;
  130. function OptPass1SHXX(var p: tai): boolean;
  131. function OptPass1VMOVDQ(var p: tai): Boolean;
  132. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  133. function OptPass2Movx(var p : tai): Boolean;
  134. function OptPass2MOV(var p : tai) : boolean;
  135. function OptPass2Imul(var p : tai) : boolean;
  136. function OptPass2Jmp(var p : tai) : boolean;
  137. function OptPass2Jcc(var p : tai) : boolean;
  138. function OptPass2Lea(var p: tai): Boolean;
  139. function OptPass2SUB(var p: tai): Boolean;
  140. function OptPass2ADD(var p : tai): Boolean;
  141. function OptPass2SETcc(var p : tai) : boolean;
  142. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  143. function PostPeepholeOptMov(var p : tai) : Boolean;
  144. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  145. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  146. function PostPeepholeOptXor(var p : tai) : Boolean;
  147. {$endif x86_64}
  148. function PostPeepholeOptAnd(var p : tai) : boolean;
  149. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  150. function PostPeepholeOptCmp(var p : tai) : Boolean;
  151. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  152. function PostPeepholeOptCall(var p : tai) : Boolean;
  153. function PostPeepholeOptLea(var p : tai) : Boolean;
  154. function PostPeepholeOptPush(var p: tai): Boolean;
  155. function PostPeepholeOptShr(var p : tai) : boolean;
  156. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  157. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  158. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  159. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  160. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  161. { Processor-dependent reference optimisation }
  162. class procedure OptimizeRefs(var p: taicpu); static;
  163. end;
  164. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  168. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  169. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  170. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  171. {$if max_operands>2}
  172. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  173. {$endif max_operands>2}
  174. function RefsEqual(const r1, r2: treference): boolean;
  175. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  176. { returns true, if ref is a reference using only the registers passed as base and index
  177. and having an offset }
  178. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  179. implementation
  180. uses
  181. cutils,verbose,
  182. systems,
  183. globals,
  184. cpuinfo,
  185. procinfo,
  186. paramgr,
  187. aasmbase,
  188. aoptbase,aoptutils,
  189. symconst,symsym,
  190. cgx86,
  191. itcpugas;
  192. {$ifdef DEBUG_AOPTCPU}
  193. const
  194. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  195. {$else DEBUG_AOPTCPU}
  196. { Empty strings help the optimizer to remove string concatenations that won't
  197. ever appear to the user on release builds. [Kit] }
  198. const
  199. SPeepholeOptimization = '';
  200. {$endif DEBUG_AOPTCPU}
  201. LIST_STEP_SIZE = 4;
  202. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  203. begin
  204. result :=
  205. (instr.typ = ait_instruction) and
  206. (taicpu(instr).opcode = op) and
  207. ((opsize = []) or (taicpu(instr).opsize in opsize));
  208. end;
  209. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  210. begin
  211. result :=
  212. (instr.typ = ait_instruction) and
  213. ((taicpu(instr).opcode = op1) or
  214. (taicpu(instr).opcode = op2)
  215. ) and
  216. ((opsize = []) or (taicpu(instr).opsize in opsize));
  217. end;
  218. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  219. begin
  220. result :=
  221. (instr.typ = ait_instruction) and
  222. ((taicpu(instr).opcode = op1) or
  223. (taicpu(instr).opcode = op2) or
  224. (taicpu(instr).opcode = op3)
  225. ) and
  226. ((opsize = []) or (taicpu(instr).opsize in opsize));
  227. end;
  228. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  229. const opsize : topsizes) : boolean;
  230. var
  231. op : TAsmOp;
  232. begin
  233. result:=false;
  234. if (instr.typ <> ait_instruction) or
  235. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  236. exit;
  237. for op in ops do
  238. begin
  239. if taicpu(instr).opcode = op then
  240. begin
  241. result:=true;
  242. exit;
  243. end;
  244. end;
  245. end;
  246. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  247. begin
  248. result := (oper.typ = top_reg) and (oper.reg = reg);
  249. end;
  250. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  251. begin
  252. result := (oper.typ = top_const) and (oper.val = a);
  253. end;
  254. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  255. begin
  256. result := oper1.typ = oper2.typ;
  257. if result then
  258. case oper1.typ of
  259. top_const:
  260. Result:=oper1.val = oper2.val;
  261. top_reg:
  262. Result:=oper1.reg = oper2.reg;
  263. top_ref:
  264. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  265. else
  266. internalerror(2013102801);
  267. end
  268. end;
  269. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  270. begin
  271. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  272. if result then
  273. case oper1.typ of
  274. top_const:
  275. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  276. top_reg:
  277. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  278. top_ref:
  279. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  280. else
  281. internalerror(2020052401);
  282. end
  283. end;
  284. function RefsEqual(const r1, r2: treference): boolean;
  285. begin
  286. RefsEqual :=
  287. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  288. (r1.relsymbol = r2.relsymbol) and
  289. (r1.segment = r2.segment) and (r1.base = r2.base) and
  290. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  291. (r1.offset = r2.offset) and
  292. (r1.volatility + r2.volatility = []);
  293. end;
  294. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  295. begin
  296. Result:=(ref.offset=0) and
  297. (ref.scalefactor in [0,1]) and
  298. (ref.segment=NR_NO) and
  299. (ref.symbol=nil) and
  300. (ref.relsymbol=nil) and
  301. ((base=NR_INVALID) or
  302. (ref.base=base)) and
  303. ((index=NR_INVALID) or
  304. (ref.index=index)) and
  305. (ref.volatility=[]);
  306. end;
  307. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  308. begin
  309. Result:=(ref.scalefactor in [0,1]) and
  310. (ref.segment=NR_NO) and
  311. (ref.symbol=nil) and
  312. (ref.relsymbol=nil) and
  313. ((base=NR_INVALID) or
  314. (ref.base=base)) and
  315. ((index=NR_INVALID) or
  316. (ref.index=index)) and
  317. (ref.volatility=[]);
  318. end;
  319. function InstrReadsFlags(p: tai): boolean;
  320. begin
  321. InstrReadsFlags := true;
  322. case p.typ of
  323. ait_instruction:
  324. if InsProp[taicpu(p).opcode].Ch*
  325. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  326. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  327. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  328. exit;
  329. ait_label:
  330. exit;
  331. else
  332. ;
  333. end;
  334. InstrReadsFlags := false;
  335. end;
  336. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  337. begin
  338. Next:=Current;
  339. repeat
  340. Result:=GetNextInstruction(Next,Next);
  341. until not (Result) or
  342. not(cs_opt_level3 in current_settings.optimizerswitches) or
  343. (Next.typ<>ait_instruction) or
  344. RegInInstruction(reg,Next) or
  345. is_calljmp(taicpu(Next).opcode);
  346. end;
  347. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  348. begin
  349. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  350. Next := Current;
  351. repeat
  352. Result := GetNextInstruction(Next,Next);
  353. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  354. if is_calljmpuncondret(taicpu(Next).opcode) then
  355. begin
  356. Result := False;
  357. Exit;
  358. end
  359. else
  360. CrossJump := True;
  361. until not Result or
  362. not (cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ <> ait_instruction) or
  364. RegInInstruction(reg,Next);
  365. end;
  366. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  367. begin
  368. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  369. begin
  370. Result:=GetNextInstruction(Current,Next);
  371. exit;
  372. end;
  373. Next:=tai(Current.Next);
  374. Result:=false;
  375. while assigned(Next) do
  376. begin
  377. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  378. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  379. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  380. exit
  381. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  382. begin
  383. Result:=true;
  384. exit;
  385. end;
  386. Next:=tai(Next.Next);
  387. end;
  388. end;
  389. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  390. begin
  391. Result:=RegReadByInstruction(reg,hp);
  392. end;
  393. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  394. var
  395. p: taicpu;
  396. opcount: longint;
  397. begin
  398. RegReadByInstruction := false;
  399. if hp.typ <> ait_instruction then
  400. exit;
  401. p := taicpu(hp);
  402. case p.opcode of
  403. A_CALL:
  404. regreadbyinstruction := true;
  405. A_IMUL:
  406. case p.ops of
  407. 1:
  408. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  409. (
  410. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  411. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  412. );
  413. 2,3:
  414. regReadByInstruction :=
  415. reginop(reg,p.oper[0]^) or
  416. reginop(reg,p.oper[1]^);
  417. else
  418. InternalError(2019112801);
  419. end;
  420. A_MUL:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  425. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  426. );
  427. end;
  428. A_IDIV,A_DIV:
  429. begin
  430. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  431. (
  432. (getregtype(reg)=R_INTREGISTER) and
  433. (
  434. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  435. )
  436. );
  437. end;
  438. else
  439. begin
  440. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  441. begin
  442. RegReadByInstruction := false;
  443. exit;
  444. end;
  445. for opcount := 0 to p.ops-1 do
  446. if (p.oper[opCount]^.typ = top_ref) and
  447. RegInRef(reg,p.oper[opcount]^.ref^) then
  448. begin
  449. RegReadByInstruction := true;
  450. exit
  451. end;
  452. { special handling for SSE MOVSD }
  453. if (p.opcode=A_MOVSD) and (p.ops>0) then
  454. begin
  455. if p.ops<>2 then
  456. internalerror(2017042702);
  457. regReadByInstruction := reginop(reg,p.oper[0]^) or
  458. (
  459. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  460. );
  461. exit;
  462. end;
  463. with insprop[p.opcode] do
  464. begin
  465. case getregtype(reg) of
  466. R_INTREGISTER:
  467. begin
  468. case getsupreg(reg) of
  469. RS_EAX:
  470. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ECX:
  476. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EDX:
  482. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_EBX:
  488. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_ESP:
  494. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. RS_EBP:
  500. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  501. begin
  502. RegReadByInstruction := true;
  503. exit
  504. end;
  505. RS_ESI:
  506. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  507. begin
  508. RegReadByInstruction := true;
  509. exit
  510. end;
  511. RS_EDI:
  512. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  513. begin
  514. RegReadByInstruction := true;
  515. exit
  516. end;
  517. end;
  518. end;
  519. R_MMREGISTER:
  520. begin
  521. case getsupreg(reg) of
  522. RS_XMM0:
  523. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  524. begin
  525. RegReadByInstruction := true;
  526. exit
  527. end;
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  534. begin
  535. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  536. begin
  537. case p.condition of
  538. C_A,C_NBE, { CF=0 and ZF=0 }
  539. C_BE,C_NA: { CF=1 or ZF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  541. C_AE,C_NB,C_NC, { CF=0 }
  542. C_B,C_NAE,C_C: { CF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  544. C_NE,C_NZ, { ZF=0 }
  545. C_E,C_Z: { ZF=1 }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  547. C_G,C_NLE, { ZF=0 and SF=OF }
  548. C_LE,C_NG: { ZF=1 or SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_GE,C_NL, { SF=OF }
  551. C_L,C_NGE: { SF<>OF }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  553. C_NO, { OF=0 }
  554. C_O: { OF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  556. C_NP,C_PO, { PF=0 }
  557. C_P,C_PE: { PF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  559. C_NS, { SF=0 }
  560. C_S: { SF=1 }
  561. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  562. else
  563. internalerror(2017042701);
  564. end;
  565. if RegReadByInstruction then
  566. exit;
  567. end;
  568. case getsubreg(reg) of
  569. R_SUBW,R_SUBD,R_SUBQ:
  570. RegReadByInstruction :=
  571. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  572. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  573. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  574. R_SUBFLAGCARRY:
  575. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  576. R_SUBFLAGPARITY:
  577. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  578. R_SUBFLAGAUXILIARY:
  579. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  580. R_SUBFLAGZERO:
  581. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  582. R_SUBFLAGSIGN:
  583. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  584. R_SUBFLAGOVERFLOW:
  585. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  586. R_SUBFLAGINTERRUPT:
  587. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  588. R_SUBFLAGDIRECTION:
  589. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  590. else
  591. internalerror(2017042601);
  592. end;
  593. exit;
  594. end;
  595. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  596. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  597. (p.oper[0]^.reg=p.oper[1]^.reg) then
  598. exit;
  599. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  615. begin
  616. RegReadByInstruction := true;
  617. exit
  618. end;
  619. end;
  620. end;
  621. end;
  622. end;
  623. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  624. begin
  625. result:=false;
  626. if p1.typ<>ait_instruction then
  627. exit;
  628. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  629. exit(true);
  630. if (getregtype(reg)=R_INTREGISTER) and
  631. { change information for xmm movsd are not correct }
  632. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  633. begin
  634. case getsupreg(reg) of
  635. { RS_EAX = RS_RAX on x86-64 }
  636. RS_EAX:
  637. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. RS_ECX:
  639. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. RS_EDX:
  641. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. RS_EBX:
  643. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. RS_ESP:
  645. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. RS_EBP:
  647. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. RS_ESI:
  649. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. RS_EDI:
  651. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. else
  653. ;
  654. end;
  655. if result then
  656. exit;
  657. end
  658. else if getregtype(reg)=R_MMREGISTER then
  659. begin
  660. case getsupreg(reg) of
  661. RS_XMM0:
  662. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  663. else
  664. ;
  665. end;
  666. if result then
  667. exit;
  668. end
  669. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  670. begin
  671. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  672. exit(true);
  673. case getsubreg(reg) of
  674. R_SUBFLAGCARRY:
  675. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  676. R_SUBFLAGPARITY:
  677. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  678. R_SUBFLAGAUXILIARY:
  679. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  680. R_SUBFLAGZERO:
  681. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  682. R_SUBFLAGSIGN:
  683. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  684. R_SUBFLAGOVERFLOW:
  685. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  686. R_SUBFLAGINTERRUPT:
  687. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  688. R_SUBFLAGDIRECTION:
  689. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  690. R_SUBW,R_SUBD,R_SUBQ:
  691. { Everything except the direction bits }
  692. Result:=
  693. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  694. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  695. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  696. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  697. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  698. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  699. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. else
  701. ;
  702. end;
  703. if result then
  704. exit;
  705. end
  706. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  707. exit(true);
  708. Result:=inherited RegInInstruction(Reg, p1);
  709. end;
  710. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  711. const
  712. WriteOps: array[0..3] of set of TInsChange =
  713. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  714. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  715. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  716. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  717. var
  718. OperIdx: Integer;
  719. begin
  720. Result := False;
  721. if p1.typ <> ait_instruction then
  722. exit;
  723. with insprop[taicpu(p1).opcode] do
  724. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  725. begin
  726. case getsubreg(reg) of
  727. R_SUBW,R_SUBD,R_SUBQ:
  728. Result :=
  729. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  730. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  731. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  732. R_SUBFLAGCARRY:
  733. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  734. R_SUBFLAGPARITY:
  735. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  736. R_SUBFLAGAUXILIARY:
  737. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  738. R_SUBFLAGZERO:
  739. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  740. R_SUBFLAGSIGN:
  741. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  742. R_SUBFLAGOVERFLOW:
  743. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  744. R_SUBFLAGINTERRUPT:
  745. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  746. R_SUBFLAGDIRECTION:
  747. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  748. else
  749. internalerror(2017042602);
  750. end;
  751. exit;
  752. end;
  753. case taicpu(p1).opcode of
  754. A_CALL:
  755. { We could potentially set Result to False if the register in
  756. question is non-volatile for the subroutine's calling convention,
  757. but this would require detecting the calling convention in use and
  758. also assuming that the routine doesn't contain malformed assembly
  759. language, for example... so it could only be done under -O4 as it
  760. would be considered a side-effect. [Kit] }
  761. Result := True;
  762. A_MOVSD:
  763. { special handling for SSE MOVSD }
  764. if (taicpu(p1).ops>0) then
  765. begin
  766. if taicpu(p1).ops<>2 then
  767. internalerror(2017042703);
  768. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  769. end;
  770. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  771. so fix it here (FK)
  772. }
  773. A_VMOVSS,
  774. A_VMOVSD:
  775. begin
  776. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  777. exit;
  778. end;
  779. A_IMUL:
  780. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  781. else
  782. ;
  783. end;
  784. if Result then
  785. exit;
  786. with insprop[taicpu(p1).opcode] do
  787. begin
  788. if getregtype(reg)=R_INTREGISTER then
  789. begin
  790. case getsupreg(reg) of
  791. RS_EAX:
  792. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  793. begin
  794. Result := True;
  795. exit
  796. end;
  797. RS_ECX:
  798. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  799. begin
  800. Result := True;
  801. exit
  802. end;
  803. RS_EDX:
  804. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  805. begin
  806. Result := True;
  807. exit
  808. end;
  809. RS_EBX:
  810. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  811. begin
  812. Result := True;
  813. exit
  814. end;
  815. RS_ESP:
  816. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  817. begin
  818. Result := True;
  819. exit
  820. end;
  821. RS_EBP:
  822. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  823. begin
  824. Result := True;
  825. exit
  826. end;
  827. RS_ESI:
  828. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  829. begin
  830. Result := True;
  831. exit
  832. end;
  833. RS_EDI:
  834. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  835. begin
  836. Result := True;
  837. exit
  838. end;
  839. end;
  840. end;
  841. for OperIdx := 0 to taicpu(p1).ops - 1 do
  842. if (WriteOps[OperIdx]*Ch<>[]) and
  843. { The register doesn't get modified inside a reference }
  844. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  845. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  846. begin
  847. Result := true;
  848. exit
  849. end;
  850. end;
  851. end;
  852. {$ifdef DEBUG_AOPTCPU}
  853. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  854. begin
  855. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  856. end;
  857. function debug_tostr(i: tcgint): string; inline;
  858. begin
  859. Result := tostr(i);
  860. end;
  861. function debug_regname(r: TRegister): string; inline;
  862. begin
  863. Result := '%' + std_regname(r);
  864. end;
  865. { Debug output function - creates a string representation of an operator }
  866. function debug_operstr(oper: TOper): string;
  867. begin
  868. case oper.typ of
  869. top_const:
  870. Result := '$' + debug_tostr(oper.val);
  871. top_reg:
  872. Result := debug_regname(oper.reg);
  873. top_ref:
  874. begin
  875. if oper.ref^.offset <> 0 then
  876. Result := debug_tostr(oper.ref^.offset) + '('
  877. else
  878. Result := '(';
  879. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  880. begin
  881. Result := Result + debug_regname(oper.ref^.base);
  882. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  883. Result := Result + ',' + debug_regname(oper.ref^.index);
  884. end
  885. else
  886. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  887. Result := Result + debug_regname(oper.ref^.index);
  888. if (oper.ref^.scalefactor > 1) then
  889. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  890. else
  891. Result := Result + ')';
  892. end;
  893. else
  894. Result := '[UNKNOWN]';
  895. end;
  896. end;
  897. function debug_op2str(opcode: tasmop): string; inline;
  898. begin
  899. Result := std_op2str[opcode];
  900. end;
  901. function debug_opsize2str(opsize: topsize): string; inline;
  902. begin
  903. Result := gas_opsize2str[opsize];
  904. end;
  905. {$else DEBUG_AOPTCPU}
  906. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  907. begin
  908. end;
  909. function debug_tostr(i: tcgint): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_regname(r: TRegister): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. function debug_operstr(oper: TOper): string; inline;
  918. begin
  919. Result := '';
  920. end;
  921. function debug_op2str(opcode: tasmop): string; inline;
  922. begin
  923. Result := '';
  924. end;
  925. function debug_opsize2str(opsize: topsize): string; inline;
  926. begin
  927. Result := '';
  928. end;
  929. {$endif DEBUG_AOPTCPU}
  930. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  931. begin
  932. {$ifdef x86_64}
  933. { Always fine on x86-64 }
  934. Result := True;
  935. {$else x86_64}
  936. Result :=
  937. {$ifdef i8086}
  938. (current_settings.cputype >= cpu_386) and
  939. {$endif i8086}
  940. (
  941. { Always accept if optimising for size }
  942. (cs_opt_size in current_settings.optimizerswitches) or
  943. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  944. (current_settings.optimizecputype >= cpu_Pentium2)
  945. );
  946. {$endif x86_64}
  947. end;
  948. { Attempts to allocate a volatile integer register for use between p and hp,
  949. using AUsedRegs for the current register usage information. Returns NR_NO
  950. if no free register could be found }
  951. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  952. var
  953. RegSet: TCPURegisterSet;
  954. CurrentSuperReg: Integer;
  955. CurrentReg: TRegister;
  956. Currentp: tai;
  957. Breakout: Boolean;
  958. begin
  959. Result := NR_NO;
  960. RegSet :=
  961. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  962. current_procinfo.saved_regs_int;
  963. for CurrentSuperReg in RegSet do
  964. begin
  965. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  966. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  967. {$if defined(i386) or defined(i8086)}
  968. { If the target size is 8-bit, make sure we can actually encode it }
  969. and (
  970. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  971. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  972. )
  973. {$endif i386 or i8086}
  974. then
  975. begin
  976. Currentp := p;
  977. Breakout := False;
  978. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  979. begin
  980. case Currentp.typ of
  981. ait_instruction:
  982. begin
  983. if RegInInstruction(CurrentReg, Currentp) then
  984. begin
  985. Breakout := True;
  986. Break;
  987. end;
  988. { Cannot allocate across an unconditional jump }
  989. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  990. Exit;
  991. end;
  992. ait_marker:
  993. { Don't try anything more if a marker is hit }
  994. Exit;
  995. ait_regalloc:
  996. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  997. begin
  998. Breakout := True;
  999. Break;
  1000. end;
  1001. else
  1002. ;
  1003. end;
  1004. end;
  1005. if Breakout then
  1006. { Try the next register }
  1007. Continue;
  1008. { We have a free register available }
  1009. Result := CurrentReg;
  1010. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1011. Exit;
  1012. end;
  1013. end;
  1014. end;
  1015. { Attempts to allocate a volatile MM register for use between p and hp,
  1016. using AUsedRegs for the current register usage information. Returns NR_NO
  1017. if no free register could be found }
  1018. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1019. var
  1020. RegSet: TCPURegisterSet;
  1021. CurrentSuperReg: Integer;
  1022. CurrentReg: TRegister;
  1023. Currentp: tai;
  1024. Breakout: Boolean;
  1025. begin
  1026. Result := NR_NO;
  1027. RegSet :=
  1028. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1029. current_procinfo.saved_regs_mm;
  1030. for CurrentSuperReg in RegSet do
  1031. begin
  1032. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1033. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1034. begin
  1035. Currentp := p;
  1036. Breakout := False;
  1037. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1038. begin
  1039. case Currentp.typ of
  1040. ait_instruction:
  1041. begin
  1042. if RegInInstruction(CurrentReg, Currentp) then
  1043. begin
  1044. Breakout := True;
  1045. Break;
  1046. end;
  1047. { Cannot allocate across an unconditional jump }
  1048. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1049. Exit;
  1050. end;
  1051. ait_marker:
  1052. { Don't try anything more if a marker is hit }
  1053. Exit;
  1054. ait_regalloc:
  1055. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1056. begin
  1057. Breakout := True;
  1058. Break;
  1059. end;
  1060. else
  1061. ;
  1062. end;
  1063. end;
  1064. if Breakout then
  1065. { Try the next register }
  1066. Continue;
  1067. { We have a free register available }
  1068. Result := CurrentReg;
  1069. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1070. Exit;
  1071. end;
  1072. end;
  1073. end;
  1074. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1075. begin
  1076. if not SuperRegistersEqual(reg1,reg2) then
  1077. exit(false);
  1078. if getregtype(reg1)<>R_INTREGISTER then
  1079. exit(true); {because SuperRegisterEqual is true}
  1080. case getsubreg(reg1) of
  1081. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1082. higher, it preserves the high bits, so the new value depends on
  1083. reg2's previous value. In other words, it is equivalent to doing:
  1084. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1085. R_SUBL:
  1086. exit(getsubreg(reg2)=R_SUBL);
  1087. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1088. higher, it actually does a:
  1089. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1090. R_SUBH:
  1091. exit(getsubreg(reg2)=R_SUBH);
  1092. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1093. bits of reg2:
  1094. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1095. R_SUBW:
  1096. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1097. { a write to R_SUBD always overwrites every other subregister,
  1098. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1099. R_SUBD,
  1100. R_SUBQ:
  1101. exit(true);
  1102. else
  1103. internalerror(2017042801);
  1104. end;
  1105. end;
  1106. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1107. begin
  1108. if not SuperRegistersEqual(reg1,reg2) then
  1109. exit(false);
  1110. if getregtype(reg1)<>R_INTREGISTER then
  1111. exit(true); {because SuperRegisterEqual is true}
  1112. case getsubreg(reg1) of
  1113. R_SUBL:
  1114. exit(getsubreg(reg2)<>R_SUBH);
  1115. R_SUBH:
  1116. exit(getsubreg(reg2)<>R_SUBL);
  1117. R_SUBW,
  1118. R_SUBD,
  1119. R_SUBQ:
  1120. exit(true);
  1121. else
  1122. internalerror(2017042802);
  1123. end;
  1124. end;
  1125. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1126. var
  1127. hp1 : tai;
  1128. l : TCGInt;
  1129. begin
  1130. result:=false;
  1131. { changes the code sequence
  1132. shr/sar const1, x
  1133. shl const2, x
  1134. to
  1135. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1136. if GetNextInstruction(p, hp1) and
  1137. MatchInstruction(hp1,A_SHL,[]) and
  1138. (taicpu(p).oper[0]^.typ = top_const) and
  1139. (taicpu(hp1).oper[0]^.typ = top_const) and
  1140. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1141. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1142. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1143. begin
  1144. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1145. not(cs_opt_size in current_settings.optimizerswitches) then
  1146. begin
  1147. { shr/sar const1, %reg
  1148. shl const2, %reg
  1149. with const1 > const2 }
  1150. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1151. taicpu(hp1).opcode := A_AND;
  1152. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1153. case taicpu(p).opsize Of
  1154. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1155. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1156. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1157. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1158. else
  1159. Internalerror(2017050703)
  1160. end;
  1161. end
  1162. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1163. not(cs_opt_size in current_settings.optimizerswitches) then
  1164. begin
  1165. { shr/sar const1, %reg
  1166. shl const2, %reg
  1167. with const1 < const2 }
  1168. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1169. taicpu(p).opcode := A_AND;
  1170. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1171. case taicpu(p).opsize Of
  1172. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1173. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1174. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1175. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1176. else
  1177. Internalerror(2017050702)
  1178. end;
  1179. end
  1180. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1181. begin
  1182. { shr/sar const1, %reg
  1183. shl const2, %reg
  1184. with const1 = const2 }
  1185. taicpu(p).opcode := A_AND;
  1186. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1187. case taicpu(p).opsize Of
  1188. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1189. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1190. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1191. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1192. else
  1193. Internalerror(2017050701)
  1194. end;
  1195. RemoveInstruction(hp1);
  1196. end;
  1197. end;
  1198. end;
  1199. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1200. var
  1201. opsize : topsize;
  1202. hp1 : tai;
  1203. tmpref : treference;
  1204. ShiftValue : Cardinal;
  1205. BaseValue : TCGInt;
  1206. begin
  1207. result:=false;
  1208. opsize:=taicpu(p).opsize;
  1209. { changes certain "imul const, %reg"'s to lea sequences }
  1210. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1211. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1212. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1213. if (taicpu(p).oper[0]^.val = 1) then
  1214. if (taicpu(p).ops = 2) then
  1215. { remove "imul $1, reg" }
  1216. begin
  1217. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1218. Result := RemoveCurrentP(p);
  1219. end
  1220. else
  1221. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1222. begin
  1223. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1224. InsertLLItem(p.previous, p.next, hp1);
  1225. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1226. p.free;
  1227. p := hp1;
  1228. end
  1229. else if ((taicpu(p).ops <= 2) or
  1230. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1231. not(cs_opt_size in current_settings.optimizerswitches) and
  1232. (not(GetNextInstruction(p, hp1)) or
  1233. not((tai(hp1).typ = ait_instruction) and
  1234. ((taicpu(hp1).opcode=A_Jcc) and
  1235. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1236. begin
  1237. {
  1238. imul X, reg1, reg2 to
  1239. lea (reg1,reg1,Y), reg2
  1240. shl ZZ,reg2
  1241. imul XX, reg1 to
  1242. lea (reg1,reg1,YY), reg1
  1243. shl ZZ,reg2
  1244. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1245. it does not exist as a separate optimization target in FPC though.
  1246. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1247. at most two zeros
  1248. }
  1249. reference_reset(tmpref,1,[]);
  1250. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1251. begin
  1252. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1253. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1254. TmpRef.base := taicpu(p).oper[1]^.reg;
  1255. TmpRef.index := taicpu(p).oper[1]^.reg;
  1256. if not(BaseValue in [3,5,9]) then
  1257. Internalerror(2018110101);
  1258. TmpRef.ScaleFactor := BaseValue-1;
  1259. if (taicpu(p).ops = 2) then
  1260. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1261. else
  1262. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1263. AsmL.InsertAfter(hp1,p);
  1264. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1265. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1266. RemoveCurrentP(p, hp1);
  1267. if ShiftValue>0 then
  1268. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1269. end;
  1270. end;
  1271. end;
  1272. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1273. begin
  1274. Result := False;
  1275. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1276. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1277. begin
  1278. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1279. taicpu(p).opcode := A_MOV;
  1280. Result := True;
  1281. end;
  1282. end;
  1283. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1284. var
  1285. p: taicpu absolute hp; { Implicit typecast }
  1286. i: Integer;
  1287. begin
  1288. Result := False;
  1289. if not assigned(hp) or
  1290. (hp.typ <> ait_instruction) then
  1291. Exit;
  1292. Prefetch(insprop[p.opcode]);
  1293. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1294. with insprop[p.opcode] do
  1295. begin
  1296. case getsubreg(reg) of
  1297. R_SUBW,R_SUBD,R_SUBQ:
  1298. Result:=
  1299. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1300. uncommon flags are checked first }
  1301. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1302. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1303. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1304. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1305. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1306. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1307. R_SUBFLAGCARRY:
  1308. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1309. R_SUBFLAGPARITY:
  1310. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1311. R_SUBFLAGAUXILIARY:
  1312. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1313. R_SUBFLAGZERO:
  1314. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1315. R_SUBFLAGSIGN:
  1316. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1317. R_SUBFLAGOVERFLOW:
  1318. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1319. R_SUBFLAGINTERRUPT:
  1320. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1321. R_SUBFLAGDIRECTION:
  1322. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1323. else
  1324. internalerror(2017050501);
  1325. end;
  1326. exit;
  1327. end;
  1328. { Handle special cases first }
  1329. case p.opcode of
  1330. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1331. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1332. begin
  1333. Result :=
  1334. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1335. (p.oper[1]^.typ = top_reg) and
  1336. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1337. (
  1338. (p.oper[0]^.typ = top_const) or
  1339. (
  1340. (p.oper[0]^.typ = top_reg) and
  1341. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1342. ) or (
  1343. (p.oper[0]^.typ = top_ref) and
  1344. not RegInRef(reg,p.oper[0]^.ref^)
  1345. )
  1346. );
  1347. end;
  1348. A_MUL, A_IMUL:
  1349. Result :=
  1350. (
  1351. (p.ops=3) and { IMUL only }
  1352. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1353. (
  1354. (
  1355. (p.oper[1]^.typ=top_reg) and
  1356. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1357. ) or (
  1358. (p.oper[1]^.typ=top_ref) and
  1359. not RegInRef(reg,p.oper[1]^.ref^)
  1360. )
  1361. )
  1362. ) or (
  1363. (
  1364. (p.ops=1) and
  1365. (
  1366. (
  1367. (
  1368. (p.oper[0]^.typ=top_reg) and
  1369. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1370. )
  1371. ) or (
  1372. (p.oper[0]^.typ=top_ref) and
  1373. not RegInRef(reg,p.oper[0]^.ref^)
  1374. )
  1375. ) and (
  1376. (
  1377. (p.opsize=S_B) and
  1378. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1379. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1380. ) or (
  1381. (p.opsize=S_W) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1383. ) or (
  1384. (p.opsize=S_L) and
  1385. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1386. {$ifdef x86_64}
  1387. ) or (
  1388. (p.opsize=S_Q) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1390. {$endif x86_64}
  1391. )
  1392. )
  1393. )
  1394. );
  1395. A_CBW:
  1396. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1397. {$ifndef x86_64}
  1398. A_LDS:
  1399. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LES:
  1401. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1402. {$endif not x86_64}
  1403. A_LFS:
  1404. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1405. A_LGS:
  1406. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1407. A_LSS:
  1408. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1410. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1411. A_LODSB:
  1412. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1413. A_LODSW:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1415. {$ifdef x86_64}
  1416. A_LODSQ:
  1417. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1418. {$endif x86_64}
  1419. A_LODSD:
  1420. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1421. A_FSTSW, A_FNSTSW:
  1422. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1423. else
  1424. begin
  1425. with insprop[p.opcode] do
  1426. begin
  1427. if (
  1428. { xor %reg,%reg etc. is classed as a new value }
  1429. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1430. MatchOpType(p, top_reg, top_reg) and
  1431. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1432. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1433. ) then
  1434. begin
  1435. Result := True;
  1436. Exit;
  1437. end;
  1438. { Make sure the entire register is overwritten }
  1439. if (getregtype(reg) = R_INTREGISTER) then
  1440. begin
  1441. if (p.ops > 0) then
  1442. begin
  1443. if RegInOp(reg, p.oper[0]^) then
  1444. begin
  1445. if (p.oper[0]^.typ = top_ref) then
  1446. begin
  1447. if RegInRef(reg, p.oper[0]^.ref^) then
  1448. begin
  1449. Result := False;
  1450. Exit;
  1451. end;
  1452. end
  1453. else if (p.oper[0]^.typ = top_reg) then
  1454. begin
  1455. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end
  1460. else if ([Ch_WOp1]*Ch<>[]) then
  1461. begin
  1462. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1463. Result := True
  1464. else
  1465. begin
  1466. Result := False;
  1467. Exit;
  1468. end;
  1469. end;
  1470. end;
  1471. end;
  1472. if (p.ops > 1) then
  1473. begin
  1474. if RegInOp(reg, p.oper[1]^) then
  1475. begin
  1476. if (p.oper[1]^.typ = top_ref) then
  1477. begin
  1478. if RegInRef(reg, p.oper[1]^.ref^) then
  1479. begin
  1480. Result := False;
  1481. Exit;
  1482. end;
  1483. end
  1484. else if (p.oper[1]^.typ = top_reg) then
  1485. begin
  1486. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end
  1491. else if ([Ch_WOp2]*Ch<>[]) then
  1492. begin
  1493. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1494. Result := True
  1495. else
  1496. begin
  1497. Result := False;
  1498. Exit;
  1499. end;
  1500. end;
  1501. end;
  1502. end;
  1503. if (p.ops > 2) then
  1504. begin
  1505. if RegInOp(reg, p.oper[2]^) then
  1506. begin
  1507. if (p.oper[2]^.typ = top_ref) then
  1508. begin
  1509. if RegInRef(reg, p.oper[2]^.ref^) then
  1510. begin
  1511. Result := False;
  1512. Exit;
  1513. end;
  1514. end
  1515. else if (p.oper[2]^.typ = top_reg) then
  1516. begin
  1517. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end
  1522. else if ([Ch_WOp3]*Ch<>[]) then
  1523. begin
  1524. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1525. Result := True
  1526. else
  1527. begin
  1528. Result := False;
  1529. Exit;
  1530. end;
  1531. end;
  1532. end;
  1533. end;
  1534. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1535. begin
  1536. if (p.oper[3]^.typ = top_ref) then
  1537. begin
  1538. if RegInRef(reg, p.oper[3]^.ref^) then
  1539. begin
  1540. Result := False;
  1541. Exit;
  1542. end;
  1543. end
  1544. else if (p.oper[3]^.typ = top_reg) then
  1545. begin
  1546. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end
  1551. else if ([Ch_WOp4]*Ch<>[]) then
  1552. begin
  1553. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1554. Result := True
  1555. else
  1556. begin
  1557. Result := False;
  1558. Exit;
  1559. end;
  1560. end;
  1561. end;
  1562. end;
  1563. end;
  1564. end;
  1565. end;
  1566. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1567. case getsupreg(reg) of
  1568. RS_EAX:
  1569. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1570. begin
  1571. Result := True;
  1572. Exit;
  1573. end;
  1574. RS_ECX:
  1575. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1576. begin
  1577. Result := True;
  1578. Exit;
  1579. end;
  1580. RS_EDX:
  1581. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1582. begin
  1583. Result := True;
  1584. Exit;
  1585. end;
  1586. RS_EBX:
  1587. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1588. begin
  1589. Result := True;
  1590. Exit;
  1591. end;
  1592. RS_ESP:
  1593. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1594. begin
  1595. Result := True;
  1596. Exit;
  1597. end;
  1598. RS_EBP:
  1599. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1600. begin
  1601. Result := True;
  1602. Exit;
  1603. end;
  1604. RS_ESI:
  1605. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1606. begin
  1607. Result := True;
  1608. Exit;
  1609. end;
  1610. RS_EDI:
  1611. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1612. begin
  1613. Result := True;
  1614. Exit;
  1615. end;
  1616. else
  1617. ;
  1618. end;
  1619. end;
  1620. end;
  1621. end;
  1622. end;
  1623. end;
  1624. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1625. var
  1626. hp2,hp3 : tai;
  1627. begin
  1628. { some x86-64 issue a NOP before the real exit code }
  1629. if MatchInstruction(p,A_NOP,[]) then
  1630. GetNextInstruction(p,p);
  1631. result:=assigned(p) and (p.typ=ait_instruction) and
  1632. ((taicpu(p).opcode = A_RET) or
  1633. ((taicpu(p).opcode=A_LEAVE) and
  1634. GetNextInstruction(p,hp2) and
  1635. MatchInstruction(hp2,A_RET,[S_NO])
  1636. ) or
  1637. (((taicpu(p).opcode=A_LEA) and
  1638. MatchOpType(taicpu(p),top_ref,top_reg) and
  1639. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1640. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1641. ) and
  1642. GetNextInstruction(p,hp2) and
  1643. MatchInstruction(hp2,A_RET,[S_NO])
  1644. ) or
  1645. ((((taicpu(p).opcode=A_MOV) and
  1646. MatchOpType(taicpu(p),top_reg,top_reg) and
  1647. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1648. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1649. ((taicpu(p).opcode=A_LEA) and
  1650. MatchOpType(taicpu(p),top_ref,top_reg) and
  1651. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1653. )
  1654. ) and
  1655. GetNextInstruction(p,hp2) and
  1656. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1657. MatchOpType(taicpu(hp2),top_reg) and
  1658. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1659. GetNextInstruction(hp2,hp3) and
  1660. MatchInstruction(hp3,A_RET,[S_NO])
  1661. )
  1662. );
  1663. end;
  1664. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1665. begin
  1666. isFoldableArithOp := False;
  1667. case hp1.opcode of
  1668. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1669. isFoldableArithOp :=
  1670. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1671. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1672. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1673. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1674. (taicpu(hp1).oper[1]^.reg = reg);
  1675. A_INC,A_DEC,A_NEG,A_NOT:
  1676. isFoldableArithOp :=
  1677. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[0]^.reg = reg);
  1679. else
  1680. ;
  1681. end;
  1682. end;
  1683. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1684. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1685. var
  1686. hp2: tai;
  1687. begin
  1688. hp2 := p;
  1689. repeat
  1690. hp2 := tai(hp2.previous);
  1691. if assigned(hp2) and
  1692. (hp2.typ = ait_regalloc) and
  1693. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1694. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1695. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1696. begin
  1697. RemoveInstruction(hp2);
  1698. break;
  1699. end;
  1700. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1701. end;
  1702. begin
  1703. case current_procinfo.procdef.returndef.typ of
  1704. arraydef,recorddef,pointerdef,
  1705. stringdef,enumdef,procdef,objectdef,errordef,
  1706. filedef,setdef,procvardef,
  1707. classrefdef,forwarddef:
  1708. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1709. orddef:
  1710. if current_procinfo.procdef.returndef.size <> 0 then
  1711. begin
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. { for int64/qword }
  1714. if current_procinfo.procdef.returndef.size = 8 then
  1715. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1716. end;
  1717. else
  1718. ;
  1719. end;
  1720. end;
  1721. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1722. var
  1723. hp1,hp2 : tai;
  1724. begin
  1725. result:=false;
  1726. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1727. begin
  1728. { vmova* reg1,reg1
  1729. =>
  1730. <nop> }
  1731. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1732. begin
  1733. RemoveCurrentP(p);
  1734. result:=true;
  1735. exit;
  1736. end
  1737. else if GetNextInstruction(p,hp1) then
  1738. begin
  1739. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1740. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1741. begin
  1742. { vmova* reg1,reg2
  1743. vmova* reg2,reg3
  1744. dealloc reg2
  1745. =>
  1746. vmova* reg1,reg3 }
  1747. TransferUsedRegs(TmpUsedRegs);
  1748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1749. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1750. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1751. begin
  1752. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1753. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1754. RemoveInstruction(hp1);
  1755. result:=true;
  1756. exit;
  1757. end
  1758. { special case:
  1759. vmova* reg1,<op>
  1760. vmova* <op>,reg1
  1761. =>
  1762. vmova* reg1,<op> }
  1763. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1764. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1765. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1766. ) then
  1767. begin
  1768. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1769. RemoveInstruction(hp1);
  1770. result:=true;
  1771. exit;
  1772. end
  1773. end
  1774. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1775. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1776. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1777. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1778. ) and
  1779. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1780. begin
  1781. { vmova* reg1,reg2
  1782. vmovs* reg2,<op>
  1783. dealloc reg2
  1784. =>
  1785. vmovs* reg1,reg3 }
  1786. TransferUsedRegs(TmpUsedRegs);
  1787. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1788. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1789. begin
  1790. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1791. taicpu(p).opcode:=taicpu(hp1).opcode;
  1792. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1793. RemoveInstruction(hp1);
  1794. result:=true;
  1795. exit;
  1796. end
  1797. end;
  1798. end;
  1799. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1800. begin
  1801. if MatchInstruction(hp1,[A_VFMADDPD,
  1802. A_VFMADD132PD,
  1803. A_VFMADD132PS,
  1804. A_VFMADD132SD,
  1805. A_VFMADD132SS,
  1806. A_VFMADD213PD,
  1807. A_VFMADD213PS,
  1808. A_VFMADD213SD,
  1809. A_VFMADD213SS,
  1810. A_VFMADD231PD,
  1811. A_VFMADD231PS,
  1812. A_VFMADD231SD,
  1813. A_VFMADD231SS,
  1814. A_VFMADDSUB132PD,
  1815. A_VFMADDSUB132PS,
  1816. A_VFMADDSUB213PD,
  1817. A_VFMADDSUB213PS,
  1818. A_VFMADDSUB231PD,
  1819. A_VFMADDSUB231PS,
  1820. A_VFMSUB132PD,
  1821. A_VFMSUB132PS,
  1822. A_VFMSUB132SD,
  1823. A_VFMSUB132SS,
  1824. A_VFMSUB213PD,
  1825. A_VFMSUB213PS,
  1826. A_VFMSUB213SD,
  1827. A_VFMSUB213SS,
  1828. A_VFMSUB231PD,
  1829. A_VFMSUB231PS,
  1830. A_VFMSUB231SD,
  1831. A_VFMSUB231SS,
  1832. A_VFMSUBADD132PD,
  1833. A_VFMSUBADD132PS,
  1834. A_VFMSUBADD213PD,
  1835. A_VFMSUBADD213PS,
  1836. A_VFMSUBADD231PD,
  1837. A_VFMSUBADD231PS,
  1838. A_VFNMADD132PD,
  1839. A_VFNMADD132PS,
  1840. A_VFNMADD132SD,
  1841. A_VFNMADD132SS,
  1842. A_VFNMADD213PD,
  1843. A_VFNMADD213PS,
  1844. A_VFNMADD213SD,
  1845. A_VFNMADD213SS,
  1846. A_VFNMADD231PD,
  1847. A_VFNMADD231PS,
  1848. A_VFNMADD231SD,
  1849. A_VFNMADD231SS,
  1850. A_VFNMSUB132PD,
  1851. A_VFNMSUB132PS,
  1852. A_VFNMSUB132SD,
  1853. A_VFNMSUB132SS,
  1854. A_VFNMSUB213PD,
  1855. A_VFNMSUB213PS,
  1856. A_VFNMSUB213SD,
  1857. A_VFNMSUB213SS,
  1858. A_VFNMSUB231PD,
  1859. A_VFNMSUB231PS,
  1860. A_VFNMSUB231SD,
  1861. A_VFNMSUB231SS],[S_NO]) and
  1862. { we mix single and double opperations here because we assume that the compiler
  1863. generates vmovapd only after double operations and vmovaps only after single operations }
  1864. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1865. GetNextInstruction(hp1,hp2) and
  1866. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1867. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1868. begin
  1869. TransferUsedRegs(TmpUsedRegs);
  1870. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1871. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1872. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1873. begin
  1874. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1875. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1876. RemoveInstruction(hp2);
  1877. end;
  1878. end
  1879. else if (hp1.typ = ait_instruction) and
  1880. GetNextInstruction(hp1, hp2) and
  1881. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1882. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1883. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1884. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1885. (((taicpu(p).opcode=A_MOVAPS) and
  1886. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1887. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1888. ((taicpu(p).opcode=A_MOVAPD) and
  1889. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1890. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1891. ) then
  1892. { change
  1893. movapX reg,reg2
  1894. addsX/subsX/... reg3, reg2
  1895. movapX reg2,reg
  1896. to
  1897. addsX/subsX/... reg3,reg
  1898. }
  1899. begin
  1900. TransferUsedRegs(TmpUsedRegs);
  1901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1903. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1904. begin
  1905. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1906. debug_op2str(taicpu(p).opcode)+' '+
  1907. debug_op2str(taicpu(hp1).opcode)+' '+
  1908. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1909. { we cannot eliminate the first move if
  1910. the operations uses the same register for source and dest }
  1911. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1912. RemoveCurrentP(p, nil);
  1913. p:=hp1;
  1914. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1915. RemoveInstruction(hp2);
  1916. result:=true;
  1917. end;
  1918. end
  1919. else if (hp1.typ = ait_instruction) and
  1920. (((taicpu(p).opcode=A_VMOVAPD) and
  1921. (taicpu(hp1).opcode=A_VCOMISD)) or
  1922. ((taicpu(p).opcode=A_VMOVAPS) and
  1923. ((taicpu(hp1).opcode=A_VCOMISS))
  1924. )
  1925. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1926. { change
  1927. movapX reg,reg1
  1928. vcomisX reg1,reg1
  1929. to
  1930. vcomisX reg,reg
  1931. }
  1932. begin
  1933. TransferUsedRegs(TmpUsedRegs);
  1934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1935. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1936. begin
  1937. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1938. debug_op2str(taicpu(p).opcode)+' '+
  1939. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1940. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1941. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  1942. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1943. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  1944. RemoveCurrentP(p, nil);
  1945. result:=true;
  1946. exit;
  1947. end;
  1948. end
  1949. end;
  1950. end;
  1951. end;
  1952. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1953. var
  1954. hp1 : tai;
  1955. begin
  1956. result:=false;
  1957. { replace
  1958. V<Op>X %mreg1,%mreg2,%mreg3
  1959. VMovX %mreg3,%mreg4
  1960. dealloc %mreg3
  1961. by
  1962. V<Op>X %mreg1,%mreg2,%mreg4
  1963. ?
  1964. }
  1965. if GetNextInstruction(p,hp1) and
  1966. { we mix single and double operations here because we assume that the compiler
  1967. generates vmovapd only after double operations and vmovaps only after single operations }
  1968. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1969. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1970. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1971. begin
  1972. TransferUsedRegs(TmpUsedRegs);
  1973. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1974. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1975. begin
  1976. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1977. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1978. RemoveInstruction(hp1);
  1979. result:=true;
  1980. end;
  1981. end;
  1982. end;
  1983. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1984. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1985. begin
  1986. Result := False;
  1987. { For safety reasons, only check for exact register matches }
  1988. { Check base register }
  1989. if (ref.base = AOldReg) then
  1990. begin
  1991. ref.base := ANewReg;
  1992. Result := True;
  1993. end;
  1994. { Check index register }
  1995. if (ref.index = AOldReg) then
  1996. begin
  1997. ref.index := ANewReg;
  1998. Result := True;
  1999. end;
  2000. end;
  2001. { Replaces all references to AOldReg in an operand to ANewReg }
  2002. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2003. var
  2004. OldSupReg, NewSupReg: TSuperRegister;
  2005. OldSubReg, NewSubReg: TSubRegister;
  2006. OldRegType: TRegisterType;
  2007. ThisOper: POper;
  2008. begin
  2009. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2010. Result := False;
  2011. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2012. InternalError(2020011801);
  2013. OldSupReg := getsupreg(AOldReg);
  2014. OldSubReg := getsubreg(AOldReg);
  2015. OldRegType := getregtype(AOldReg);
  2016. NewSupReg := getsupreg(ANewReg);
  2017. NewSubReg := getsubreg(ANewReg);
  2018. if OldRegType <> getregtype(ANewReg) then
  2019. InternalError(2020011802);
  2020. if OldSubReg <> NewSubReg then
  2021. InternalError(2020011803);
  2022. case ThisOper^.typ of
  2023. top_reg:
  2024. if (
  2025. (ThisOper^.reg = AOldReg) or
  2026. (
  2027. (OldRegType = R_INTREGISTER) and
  2028. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2029. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2030. (
  2031. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2032. {$ifndef x86_64}
  2033. and (
  2034. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2035. don't have an 8-bit representation }
  2036. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2037. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2038. )
  2039. {$endif x86_64}
  2040. )
  2041. )
  2042. ) then
  2043. begin
  2044. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2045. Result := True;
  2046. end;
  2047. top_ref:
  2048. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2049. Result := True;
  2050. else
  2051. ;
  2052. end;
  2053. end;
  2054. { Replaces all references to AOldReg in an instruction to ANewReg }
  2055. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2056. const
  2057. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2058. var
  2059. OperIdx: Integer;
  2060. begin
  2061. Result := False;
  2062. for OperIdx := 0 to p.ops - 1 do
  2063. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2064. begin
  2065. { The shift and rotate instructions can only use CL }
  2066. if not (
  2067. (OperIdx = 0) and
  2068. { This second condition just helps to avoid unnecessarily
  2069. calling MatchInstruction for 10 different opcodes }
  2070. (p.oper[0]^.reg = NR_CL) and
  2071. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2072. ) then
  2073. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2074. end
  2075. else if p.oper[OperIdx]^.typ = top_ref then
  2076. { It's okay to replace registers in references that get written to }
  2077. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2078. end;
  2079. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2080. begin
  2081. with ref^ do
  2082. Result :=
  2083. (index = NR_NO) and
  2084. (
  2085. {$ifdef x86_64}
  2086. (
  2087. (base = NR_RIP) and
  2088. (refaddr in [addr_pic, addr_pic_no_got])
  2089. ) or
  2090. {$endif x86_64}
  2091. (base = NR_STACK_POINTER_REG) or
  2092. (base = current_procinfo.framepointer)
  2093. );
  2094. end;
  2095. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2096. var
  2097. l: asizeint;
  2098. begin
  2099. Result := False;
  2100. { Should have been checked previously }
  2101. if p.opcode <> A_LEA then
  2102. InternalError(2020072501);
  2103. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2104. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2105. not(cs_opt_size in current_settings.optimizerswitches) then
  2106. exit;
  2107. with p.oper[0]^.ref^ do
  2108. begin
  2109. if (base <> p.oper[1]^.reg) or
  2110. (index <> NR_NO) or
  2111. assigned(symbol) then
  2112. exit;
  2113. l:=offset;
  2114. if (l=1) and UseIncDec then
  2115. begin
  2116. p.opcode:=A_INC;
  2117. p.loadreg(0,p.oper[1]^.reg);
  2118. p.ops:=1;
  2119. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2120. end
  2121. else if (l=-1) and UseIncDec then
  2122. begin
  2123. p.opcode:=A_DEC;
  2124. p.loadreg(0,p.oper[1]^.reg);
  2125. p.ops:=1;
  2126. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2127. end
  2128. else
  2129. begin
  2130. if (l<0) and (l<>-2147483648) then
  2131. begin
  2132. p.opcode:=A_SUB;
  2133. p.loadConst(0,-l);
  2134. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2135. end
  2136. else
  2137. begin
  2138. p.opcode:=A_ADD;
  2139. p.loadConst(0,l);
  2140. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2141. end;
  2142. end;
  2143. end;
  2144. Result := True;
  2145. end;
  2146. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2147. var
  2148. CurrentReg, ReplaceReg: TRegister;
  2149. begin
  2150. Result := False;
  2151. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2152. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2153. case hp.opcode of
  2154. A_FSTSW, A_FNSTSW,
  2155. A_IN, A_INS, A_OUT, A_OUTS,
  2156. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2157. { These routines have explicit operands, but they are restricted in
  2158. what they can be (e.g. IN and OUT can only read from AL, AX or
  2159. EAX. }
  2160. Exit;
  2161. A_IMUL:
  2162. begin
  2163. { The 1-operand version writes to implicit registers
  2164. The 2-operand version reads from the first operator, and reads
  2165. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2166. the 3-operand version reads from a register that it doesn't write to
  2167. }
  2168. case hp.ops of
  2169. 1:
  2170. if (
  2171. (
  2172. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2173. ) or
  2174. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2175. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2176. begin
  2177. Result := True;
  2178. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2179. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2180. end;
  2181. 2:
  2182. { Only modify the first parameter }
  2183. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2184. begin
  2185. Result := True;
  2186. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2187. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2188. end;
  2189. 3:
  2190. { Only modify the second parameter }
  2191. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2192. begin
  2193. Result := True;
  2194. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2195. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2196. end;
  2197. else
  2198. InternalError(2020012901);
  2199. end;
  2200. end;
  2201. else
  2202. if (hp.ops > 0) and
  2203. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2204. begin
  2205. Result := True;
  2206. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2207. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2208. end;
  2209. end;
  2210. end;
  2211. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2212. var
  2213. hp1, hp2, hp3: tai;
  2214. DoOptimisation, TempBool: Boolean;
  2215. {$ifdef x86_64}
  2216. NewConst: TCGInt;
  2217. {$endif x86_64}
  2218. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2219. begin
  2220. if taicpu(hp1).opcode = signed_movop then
  2221. begin
  2222. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2223. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2224. end
  2225. else
  2226. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2227. end;
  2228. function TryConstMerge(var p1, p2: tai): Boolean;
  2229. var
  2230. ThisRef: TReference;
  2231. begin
  2232. Result := False;
  2233. ThisRef := taicpu(p2).oper[1]^.ref^;
  2234. { Only permit writes to the stack, since we can guarantee alignment with that }
  2235. if (ThisRef.index = NR_NO) and
  2236. (
  2237. (ThisRef.base = NR_STACK_POINTER_REG) or
  2238. (ThisRef.base = current_procinfo.framepointer)
  2239. ) then
  2240. begin
  2241. case taicpu(p).opsize of
  2242. S_B:
  2243. begin
  2244. { Word writes must be on a 2-byte boundary }
  2245. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2246. begin
  2247. { Reduce offset of second reference to see if it is sequential with the first }
  2248. Dec(ThisRef.offset, 1);
  2249. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2250. begin
  2251. { Make sure the constants aren't represented as a
  2252. negative number, as these won't merge properly }
  2253. taicpu(p1).opsize := S_W;
  2254. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2255. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2256. RemoveInstruction(p2);
  2257. Result := True;
  2258. end;
  2259. end;
  2260. end;
  2261. S_W:
  2262. begin
  2263. { Longword writes must be on a 4-byte boundary }
  2264. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2265. begin
  2266. { Reduce offset of second reference to see if it is sequential with the first }
  2267. Dec(ThisRef.offset, 2);
  2268. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2269. begin
  2270. { Make sure the constants aren't represented as a
  2271. negative number, as these won't merge properly }
  2272. taicpu(p1).opsize := S_L;
  2273. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2274. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2275. RemoveInstruction(p2);
  2276. Result := True;
  2277. end;
  2278. end;
  2279. end;
  2280. {$ifdef x86_64}
  2281. S_L:
  2282. begin
  2283. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2284. see if the constants can be encoded this way. }
  2285. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2286. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2287. { Quadword writes must be on an 8-byte boundary }
  2288. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2289. begin
  2290. { Reduce offset of second reference to see if it is sequential with the first }
  2291. Dec(ThisRef.offset, 4);
  2292. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2293. begin
  2294. { Make sure the constants aren't represented as a
  2295. negative number, as these won't merge properly }
  2296. taicpu(p1).opsize := S_Q;
  2297. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2298. taicpu(p1).oper[0]^.val := NewConst;
  2299. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2300. RemoveInstruction(p2);
  2301. Result := True;
  2302. end;
  2303. end;
  2304. end;
  2305. {$endif x86_64}
  2306. else
  2307. ;
  2308. end;
  2309. end;
  2310. end;
  2311. var
  2312. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2313. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2314. NewSize: topsize;
  2315. CurrentReg, ActiveReg: TRegister;
  2316. SourceRef, TargetRef: TReference;
  2317. MovAligned, MovUnaligned: TAsmOp;
  2318. ThisRef: TReference;
  2319. begin
  2320. Result:=false;
  2321. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2322. { remove mov reg1,reg1? }
  2323. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2324. then
  2325. begin
  2326. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2327. { take care of the register (de)allocs following p }
  2328. RemoveCurrentP(p, hp1);
  2329. Result:=true;
  2330. exit;
  2331. end;
  2332. { All the next optimisations require a next instruction }
  2333. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2334. Exit;
  2335. { Look for:
  2336. mov %reg1,%reg2
  2337. ??? %reg2,r/m
  2338. Change to:
  2339. mov %reg1,%reg2
  2340. ??? %reg1,r/m
  2341. }
  2342. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2343. begin
  2344. CurrentReg := taicpu(p).oper[1]^.reg;
  2345. if RegReadByInstruction(CurrentReg, hp1) and
  2346. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2347. begin
  2348. { A change has occurred, just not in p }
  2349. Result := True;
  2350. TransferUsedRegs(TmpUsedRegs);
  2351. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2352. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2353. { Just in case something didn't get modified (e.g. an
  2354. implicit register) }
  2355. not RegReadByInstruction(CurrentReg, hp1) then
  2356. begin
  2357. { We can remove the original MOV }
  2358. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2359. RemoveCurrentp(p, hp1);
  2360. { UsedRegs got updated by RemoveCurrentp }
  2361. Result := True;
  2362. Exit;
  2363. end;
  2364. { If we know a MOV instruction has become a null operation, we might as well
  2365. get rid of it now to save time. }
  2366. if (taicpu(hp1).opcode = A_MOV) and
  2367. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2368. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2369. { Just being a register is enough to confirm it's a null operation }
  2370. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2371. begin
  2372. Result := True;
  2373. { Speed-up to reduce a pipeline stall... if we had something like...
  2374. movl %eax,%edx
  2375. movw %dx,%ax
  2376. ... the second instruction would change to movw %ax,%ax, but
  2377. given that it is now %ax that's active rather than %eax,
  2378. penalties might occur due to a partial register write, so instead,
  2379. change it to a MOVZX instruction when optimising for speed.
  2380. }
  2381. if not (cs_opt_size in current_settings.optimizerswitches) and
  2382. IsMOVZXAcceptable and
  2383. (taicpu(hp1).opsize < taicpu(p).opsize)
  2384. {$ifdef x86_64}
  2385. { operations already implicitly set the upper 64 bits to zero }
  2386. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2387. {$endif x86_64}
  2388. then
  2389. begin
  2390. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2391. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2392. case taicpu(p).opsize of
  2393. S_W:
  2394. if taicpu(hp1).opsize = S_B then
  2395. taicpu(hp1).opsize := S_BL
  2396. else
  2397. InternalError(2020012911);
  2398. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2399. case taicpu(hp1).opsize of
  2400. S_B:
  2401. taicpu(hp1).opsize := S_BL;
  2402. S_W:
  2403. taicpu(hp1).opsize := S_WL;
  2404. else
  2405. InternalError(2020012912);
  2406. end;
  2407. else
  2408. InternalError(2020012910);
  2409. end;
  2410. taicpu(hp1).opcode := A_MOVZX;
  2411. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2412. end
  2413. else
  2414. begin
  2415. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2416. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2417. RemoveInstruction(hp1);
  2418. { The instruction after what was hp1 is now the immediate next instruction,
  2419. so we can continue to make optimisations if it's present }
  2420. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2421. Exit;
  2422. hp1 := hp2;
  2423. end;
  2424. end;
  2425. end;
  2426. end;
  2427. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2428. overwrites the original destination register. e.g.
  2429. movl ###,%reg2d
  2430. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2431. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2432. }
  2433. if (taicpu(p).oper[1]^.typ = top_reg) and
  2434. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2435. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2436. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2437. begin
  2438. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2439. begin
  2440. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2441. case taicpu(p).oper[0]^.typ of
  2442. top_const:
  2443. { We have something like:
  2444. movb $x, %regb
  2445. movzbl %regb,%regd
  2446. Change to:
  2447. movl $x, %regd
  2448. }
  2449. begin
  2450. case taicpu(hp1).opsize of
  2451. S_BW:
  2452. begin
  2453. convert_mov_value(A_MOVSX, $FF);
  2454. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2455. taicpu(p).opsize := S_W;
  2456. end;
  2457. S_BL:
  2458. begin
  2459. convert_mov_value(A_MOVSX, $FF);
  2460. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2461. taicpu(p).opsize := S_L;
  2462. end;
  2463. S_WL:
  2464. begin
  2465. convert_mov_value(A_MOVSX, $FFFF);
  2466. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2467. taicpu(p).opsize := S_L;
  2468. end;
  2469. {$ifdef x86_64}
  2470. S_BQ:
  2471. begin
  2472. convert_mov_value(A_MOVSX, $FF);
  2473. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2474. taicpu(p).opsize := S_Q;
  2475. end;
  2476. S_WQ:
  2477. begin
  2478. convert_mov_value(A_MOVSX, $FFFF);
  2479. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2480. taicpu(p).opsize := S_Q;
  2481. end;
  2482. S_LQ:
  2483. begin
  2484. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2485. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2486. taicpu(p).opsize := S_Q;
  2487. end;
  2488. {$endif x86_64}
  2489. else
  2490. { If hp1 was a MOV instruction, it should have been
  2491. optimised already }
  2492. InternalError(2020021001);
  2493. end;
  2494. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2495. RemoveInstruction(hp1);
  2496. Result := True;
  2497. Exit;
  2498. end;
  2499. top_ref:
  2500. begin
  2501. { We have something like:
  2502. movb mem, %regb
  2503. movzbl %regb,%regd
  2504. Change to:
  2505. movzbl mem, %regd
  2506. }
  2507. ThisRef := taicpu(p).oper[0]^.ref^;
  2508. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2509. begin
  2510. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2511. taicpu(hp1).loadref(0, ThisRef);
  2512. { Make sure any registers in the references are properly tracked }
  2513. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2514. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2515. if (ThisRef.index <> NR_NO) then
  2516. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2517. RemoveCurrentP(p, hp1);
  2518. Result := True;
  2519. Exit;
  2520. end;
  2521. end;
  2522. else
  2523. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2524. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2525. Exit;
  2526. end;
  2527. end
  2528. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2529. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2530. optimised }
  2531. else
  2532. begin
  2533. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2534. RemoveCurrentP(p, hp1);
  2535. Result := True;
  2536. Exit;
  2537. end;
  2538. end;
  2539. if (taicpu(hp1).opcode = A_AND) and
  2540. (taicpu(p).oper[1]^.typ = top_reg) and
  2541. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2542. begin
  2543. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2544. begin
  2545. case taicpu(p).opsize of
  2546. S_L:
  2547. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2548. begin
  2549. { Optimize out:
  2550. mov x, %reg
  2551. and ffffffffh, %reg
  2552. }
  2553. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2554. RemoveInstruction(hp1);
  2555. Result:=true;
  2556. exit;
  2557. end;
  2558. S_Q: { TODO: Confirm if this is even possible }
  2559. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2560. begin
  2561. { Optimize out:
  2562. mov x, %reg
  2563. and ffffffffffffffffh, %reg
  2564. }
  2565. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2566. RemoveInstruction(hp1);
  2567. Result:=true;
  2568. exit;
  2569. end;
  2570. else
  2571. ;
  2572. end;
  2573. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2574. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2575. GetNextInstruction(hp1,hp2) and
  2576. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2577. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2578. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2579. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2580. GetNextInstruction(hp2,hp3) and
  2581. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2582. (taicpu(hp3).condition in [C_E,C_NE]) then
  2583. begin
  2584. TransferUsedRegs(TmpUsedRegs);
  2585. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2586. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2587. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2588. begin
  2589. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2590. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2591. taicpu(hp1).opcode:=A_TEST;
  2592. RemoveInstruction(hp2);
  2593. RemoveCurrentP(p, hp1);
  2594. Result:=true;
  2595. exit;
  2596. end;
  2597. end;
  2598. end
  2599. else if IsMOVZXAcceptable and
  2600. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2601. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2602. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2603. then
  2604. begin
  2605. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2606. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2607. case taicpu(p).opsize of
  2608. S_B:
  2609. if (taicpu(hp1).oper[0]^.val = $ff) then
  2610. begin
  2611. { Convert:
  2612. movb x, %regl movb x, %regl
  2613. andw ffh, %regw andl ffh, %regd
  2614. To:
  2615. movzbw x, %regd movzbl x, %regd
  2616. (Identical registers, just different sizes)
  2617. }
  2618. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2619. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2620. case taicpu(hp1).opsize of
  2621. S_W: NewSize := S_BW;
  2622. S_L: NewSize := S_BL;
  2623. {$ifdef x86_64}
  2624. S_Q: NewSize := S_BQ;
  2625. {$endif x86_64}
  2626. else
  2627. InternalError(2018011510);
  2628. end;
  2629. end
  2630. else
  2631. NewSize := S_NO;
  2632. S_W:
  2633. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2634. begin
  2635. { Convert:
  2636. movw x, %regw
  2637. andl ffffh, %regd
  2638. To:
  2639. movzwl x, %regd
  2640. (Identical registers, just different sizes)
  2641. }
  2642. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2643. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2644. case taicpu(hp1).opsize of
  2645. S_L: NewSize := S_WL;
  2646. {$ifdef x86_64}
  2647. S_Q: NewSize := S_WQ;
  2648. {$endif x86_64}
  2649. else
  2650. InternalError(2018011511);
  2651. end;
  2652. end
  2653. else
  2654. NewSize := S_NO;
  2655. else
  2656. NewSize := S_NO;
  2657. end;
  2658. if NewSize <> S_NO then
  2659. begin
  2660. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2661. { The actual optimization }
  2662. taicpu(p).opcode := A_MOVZX;
  2663. taicpu(p).changeopsize(NewSize);
  2664. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2665. { Safeguard if "and" is followed by a conditional command }
  2666. TransferUsedRegs(TmpUsedRegs);
  2667. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2668. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2669. begin
  2670. { At this point, the "and" command is effectively equivalent to
  2671. "test %reg,%reg". This will be handled separately by the
  2672. Peephole Optimizer. [Kit] }
  2673. DebugMsg(SPeepholeOptimization + PreMessage +
  2674. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2675. end
  2676. else
  2677. begin
  2678. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2679. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2680. RemoveInstruction(hp1);
  2681. end;
  2682. Result := True;
  2683. Exit;
  2684. end;
  2685. end;
  2686. end;
  2687. if (taicpu(hp1).opcode = A_OR) and
  2688. (taicpu(p).oper[1]^.typ = top_reg) and
  2689. MatchOperand(taicpu(p).oper[0]^, 0) and
  2690. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2691. begin
  2692. { mov 0, %reg
  2693. or ###,%reg
  2694. Change to (only if the flags are not used):
  2695. mov ###,%reg
  2696. }
  2697. TransferUsedRegs(TmpUsedRegs);
  2698. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2699. DoOptimisation := True;
  2700. { Even if the flags are used, we might be able to do the optimisation
  2701. if the conditions are predictable }
  2702. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2703. begin
  2704. { Only perform if ### = %reg (the same register) or equal to 0,
  2705. so %reg is guaranteed to still have a value of zero }
  2706. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2707. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2708. begin
  2709. hp2 := hp1;
  2710. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2711. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2712. GetNextInstruction(hp2, hp3) do
  2713. begin
  2714. { Don't continue modifying if the flags state is getting changed }
  2715. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2716. Break;
  2717. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2718. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2719. begin
  2720. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2721. begin
  2722. { Condition is always true }
  2723. case taicpu(hp3).opcode of
  2724. A_Jcc:
  2725. begin
  2726. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2727. { Check for jump shortcuts before we destroy the condition }
  2728. DoJumpOptimizations(hp3, TempBool);
  2729. MakeUnconditional(taicpu(hp3));
  2730. Result := True;
  2731. end;
  2732. A_CMOVcc:
  2733. begin
  2734. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2735. taicpu(hp3).opcode := A_MOV;
  2736. taicpu(hp3).condition := C_None;
  2737. Result := True;
  2738. end;
  2739. A_SETcc:
  2740. begin
  2741. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2742. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2743. taicpu(hp3).opcode := A_MOV;
  2744. taicpu(hp3).ops := 2;
  2745. taicpu(hp3).condition := C_None;
  2746. taicpu(hp3).opsize := S_B;
  2747. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2748. taicpu(hp3).loadconst(0, 1);
  2749. Result := True;
  2750. end;
  2751. else
  2752. InternalError(2021090701);
  2753. end;
  2754. end
  2755. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  2756. begin
  2757. { Condition is always false }
  2758. case taicpu(hp3).opcode of
  2759. A_Jcc:
  2760. begin
  2761. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2762. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2763. RemoveInstruction(hp3);
  2764. Result := True;
  2765. { Since hp3 was deleted, hp2 must not be updated }
  2766. Continue;
  2767. end;
  2768. A_CMOVcc:
  2769. begin
  2770. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2771. RemoveInstruction(hp3);
  2772. Result := True;
  2773. { Since hp3 was deleted, hp2 must not be updated }
  2774. Continue;
  2775. end;
  2776. A_SETcc:
  2777. begin
  2778. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2779. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2780. taicpu(hp3).opcode := A_MOV;
  2781. taicpu(hp3).ops := 2;
  2782. taicpu(hp3).condition := C_None;
  2783. taicpu(hp3).opsize := S_B;
  2784. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2785. taicpu(hp3).loadconst(0, 0);
  2786. Result := True;
  2787. end;
  2788. else
  2789. InternalError(2021090702);
  2790. end;
  2791. end
  2792. else
  2793. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2794. DoOptimisation := False;
  2795. end;
  2796. hp2 := hp3;
  2797. end;
  2798. { Flags are still in use - don't optimise }
  2799. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2800. DoOptimisation := False;
  2801. end
  2802. else
  2803. DoOptimisation := False;
  2804. end;
  2805. if DoOptimisation then
  2806. begin
  2807. {$ifdef x86_64}
  2808. { OR only supports 32-bit sign-extended constants for 64-bit
  2809. instructions, so compensate for this if the constant is
  2810. encoded as a value greater than or equal to 2^31 }
  2811. if (taicpu(hp1).opsize = S_Q) and
  2812. (taicpu(hp1).oper[0]^.typ = top_const) and
  2813. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2814. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2815. {$endif x86_64}
  2816. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2817. taicpu(hp1).opcode := A_MOV;
  2818. RemoveCurrentP(p, hp1);
  2819. Result := True;
  2820. Exit;
  2821. end;
  2822. end;
  2823. { Next instruction is also a MOV ? }
  2824. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2825. begin
  2826. if MatchOpType(taicpu(p), top_const, top_ref) and
  2827. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2828. TryConstMerge(p, hp1) then
  2829. begin
  2830. Result := True;
  2831. { In case we have four byte writes in a row, check for 2 more
  2832. right now so we don't have to wait for another iteration of
  2833. pass 1
  2834. }
  2835. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2836. case taicpu(p).opsize of
  2837. S_W:
  2838. begin
  2839. if GetNextInstruction(p, hp1) and
  2840. MatchInstruction(hp1, A_MOV, [S_B]) and
  2841. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2842. GetNextInstruction(hp1, hp2) and
  2843. MatchInstruction(hp2, A_MOV, [S_B]) and
  2844. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2845. { Try to merge the two bytes }
  2846. TryConstMerge(hp1, hp2) then
  2847. { Now try to merge the two words (hp2 will get deleted) }
  2848. TryConstMerge(p, hp1);
  2849. end;
  2850. S_L:
  2851. begin
  2852. { Though this only really benefits x86_64 and not i386, it
  2853. gets a potential optimisation done faster and hence
  2854. reduces the number of times OptPass1MOV is entered }
  2855. if GetNextInstruction(p, hp1) and
  2856. MatchInstruction(hp1, A_MOV, [S_W]) and
  2857. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2858. GetNextInstruction(hp1, hp2) and
  2859. MatchInstruction(hp2, A_MOV, [S_W]) and
  2860. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2861. { Try to merge the two words }
  2862. TryConstMerge(hp1, hp2) then
  2863. { This will always fail on i386, so don't bother
  2864. calling it unless we're doing x86_64 }
  2865. {$ifdef x86_64}
  2866. { Now try to merge the two longwords (hp2 will get deleted) }
  2867. TryConstMerge(p, hp1)
  2868. {$endif x86_64}
  2869. ;
  2870. end;
  2871. else
  2872. ;
  2873. end;
  2874. Exit;
  2875. end;
  2876. if (taicpu(p).oper[1]^.typ = top_reg) and
  2877. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2878. begin
  2879. CurrentReg := taicpu(p).oper[1]^.reg;
  2880. TransferUsedRegs(TmpUsedRegs);
  2881. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2882. { we have
  2883. mov x, %treg
  2884. mov %treg, y
  2885. }
  2886. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2887. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2888. { we've got
  2889. mov x, %treg
  2890. mov %treg, y
  2891. with %treg is not used after }
  2892. case taicpu(p).oper[0]^.typ Of
  2893. { top_reg is covered by DeepMOVOpt }
  2894. top_const:
  2895. begin
  2896. { change
  2897. mov const, %treg
  2898. mov %treg, y
  2899. to
  2900. mov const, y
  2901. }
  2902. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2903. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2904. begin
  2905. if taicpu(hp1).oper[1]^.typ=top_reg then
  2906. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2907. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2908. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2909. RemoveInstruction(hp1);
  2910. Result:=true;
  2911. Exit;
  2912. end;
  2913. end;
  2914. top_ref:
  2915. case taicpu(hp1).oper[1]^.typ of
  2916. top_reg:
  2917. begin
  2918. { change
  2919. mov mem, %treg
  2920. mov %treg, %reg
  2921. to
  2922. mov mem, %reg"
  2923. }
  2924. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2925. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2926. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2927. RemoveInstruction(hp1);
  2928. Result:=true;
  2929. Exit;
  2930. end;
  2931. top_ref:
  2932. begin
  2933. {$ifdef x86_64}
  2934. { Look for the following to simplify:
  2935. mov x(mem1), %reg
  2936. mov %reg, y(mem2)
  2937. mov x+8(mem1), %reg
  2938. mov %reg, y+8(mem2)
  2939. Change to:
  2940. movdqu x(mem1), %xmmreg
  2941. movdqu %xmmreg, y(mem2)
  2942. }
  2943. SourceRef := taicpu(p).oper[0]^.ref^;
  2944. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2945. if (taicpu(p).opsize = S_Q) and
  2946. GetNextInstruction(hp1, hp2) and
  2947. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2948. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2949. begin
  2950. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2951. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2952. Inc(SourceRef.offset, 8);
  2953. if UseAVX then
  2954. begin
  2955. MovAligned := A_VMOVDQA;
  2956. MovUnaligned := A_VMOVDQU;
  2957. end
  2958. else
  2959. begin
  2960. MovAligned := A_MOVDQA;
  2961. MovUnaligned := A_MOVDQU;
  2962. end;
  2963. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2964. begin
  2965. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2966. Inc(TargetRef.offset, 8);
  2967. if GetNextInstruction(hp2, hp3) and
  2968. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2969. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2970. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2971. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2972. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2973. begin
  2974. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2975. if CurrentReg <> NR_NO then
  2976. begin
  2977. { Remember that the offsets are 8 ahead }
  2978. if ((SourceRef.offset mod 16) = 8) and
  2979. (
  2980. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2981. (SourceRef.base = current_procinfo.framepointer) or
  2982. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2983. ) then
  2984. taicpu(p).opcode := MovAligned
  2985. else
  2986. taicpu(p).opcode := MovUnaligned;
  2987. taicpu(p).opsize := S_XMM;
  2988. taicpu(p).oper[1]^.reg := CurrentReg;
  2989. if ((TargetRef.offset mod 16) = 8) and
  2990. (
  2991. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2992. (TargetRef.base = current_procinfo.framepointer) or
  2993. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2994. ) then
  2995. taicpu(hp1).opcode := MovAligned
  2996. else
  2997. taicpu(hp1).opcode := MovUnaligned;
  2998. taicpu(hp1).opsize := S_XMM;
  2999. taicpu(hp1).oper[0]^.reg := CurrentReg;
  3000. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3001. RemoveInstruction(hp2);
  3002. RemoveInstruction(hp3);
  3003. Result := True;
  3004. Exit;
  3005. end;
  3006. end;
  3007. end
  3008. else
  3009. begin
  3010. { See if the next references are 8 less rather than 8 greater }
  3011. Dec(SourceRef.offset, 16); { -8 the other way }
  3012. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3013. begin
  3014. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3015. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3016. if GetNextInstruction(hp2, hp3) and
  3017. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3018. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3019. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3020. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3021. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3022. begin
  3023. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3024. if CurrentReg <> NR_NO then
  3025. begin
  3026. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3027. if ((SourceRef.offset mod 16) = 0) and
  3028. (
  3029. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3030. (SourceRef.base = current_procinfo.framepointer) or
  3031. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3032. ) then
  3033. taicpu(hp2).opcode := MovAligned
  3034. else
  3035. taicpu(hp2).opcode := MovUnaligned;
  3036. taicpu(hp2).opsize := S_XMM;
  3037. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3038. if ((TargetRef.offset mod 16) = 0) and
  3039. (
  3040. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3041. (TargetRef.base = current_procinfo.framepointer) or
  3042. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3043. ) then
  3044. taicpu(hp3).opcode := MovAligned
  3045. else
  3046. taicpu(hp3).opcode := MovUnaligned;
  3047. taicpu(hp3).opsize := S_XMM;
  3048. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3049. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3050. RemoveInstruction(hp1);
  3051. RemoveCurrentP(p, hp2);
  3052. Result := True;
  3053. Exit;
  3054. end;
  3055. end;
  3056. end;
  3057. end;
  3058. end;
  3059. {$endif x86_64}
  3060. end;
  3061. else
  3062. { The write target should be a reg or a ref }
  3063. InternalError(2021091601);
  3064. end;
  3065. else
  3066. ;
  3067. end
  3068. else
  3069. { %treg is used afterwards, but all eventualities
  3070. other than the first MOV instruction being a constant
  3071. are covered by DeepMOVOpt, so only check for that }
  3072. if (taicpu(p).oper[0]^.typ = top_const) and
  3073. (
  3074. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3075. not (cs_opt_size in current_settings.optimizerswitches) or
  3076. (taicpu(hp1).opsize = S_B)
  3077. ) and
  3078. (
  3079. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3080. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3081. ) then
  3082. begin
  3083. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3084. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3085. end;
  3086. end;
  3087. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3088. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3089. { mov reg1, mem1 or mov mem1, reg1
  3090. mov mem2, reg2 mov reg2, mem2}
  3091. begin
  3092. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3093. { mov reg1, mem1 or mov mem1, reg1
  3094. mov mem2, reg1 mov reg2, mem1}
  3095. begin
  3096. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3097. { Removes the second statement from
  3098. mov reg1, mem1/reg2
  3099. mov mem1/reg2, reg1 }
  3100. begin
  3101. if taicpu(p).oper[0]^.typ=top_reg then
  3102. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3103. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3104. RemoveInstruction(hp1);
  3105. Result:=true;
  3106. exit;
  3107. end
  3108. else
  3109. begin
  3110. TransferUsedRegs(TmpUsedRegs);
  3111. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3112. if (taicpu(p).oper[1]^.typ = top_ref) and
  3113. { mov reg1, mem1
  3114. mov mem2, reg1 }
  3115. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3116. GetNextInstruction(hp1, hp2) and
  3117. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3118. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3119. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3120. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3121. { change to
  3122. mov reg1, mem1 mov reg1, mem1
  3123. mov mem2, reg1 cmp reg1, mem2
  3124. cmp mem1, reg1
  3125. }
  3126. begin
  3127. RemoveInstruction(hp2);
  3128. taicpu(hp1).opcode := A_CMP;
  3129. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3130. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3131. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3132. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3133. end;
  3134. end;
  3135. end
  3136. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3137. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3138. begin
  3139. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3140. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3141. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3142. end
  3143. else
  3144. begin
  3145. TransferUsedRegs(TmpUsedRegs);
  3146. if GetNextInstruction(hp1, hp2) and
  3147. MatchOpType(taicpu(p),top_ref,top_reg) and
  3148. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3149. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3150. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3151. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3152. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3153. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3154. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3155. { mov mem1, %reg1
  3156. mov %reg1, mem2
  3157. mov mem2, reg2
  3158. to:
  3159. mov mem1, reg2
  3160. mov reg2, mem2}
  3161. begin
  3162. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3163. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3164. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3165. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3166. RemoveInstruction(hp2);
  3167. Result := True;
  3168. end
  3169. {$ifdef i386}
  3170. { this is enabled for i386 only, as the rules to create the reg sets below
  3171. are too complicated for x86-64, so this makes this code too error prone
  3172. on x86-64
  3173. }
  3174. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3175. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3176. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3177. { mov mem1, reg1 mov mem1, reg1
  3178. mov reg1, mem2 mov reg1, mem2
  3179. mov mem2, reg2 mov mem2, reg1
  3180. to: to:
  3181. mov mem1, reg1 mov mem1, reg1
  3182. mov mem1, reg2 mov reg1, mem2
  3183. mov reg1, mem2
  3184. or (if mem1 depends on reg1
  3185. and/or if mem2 depends on reg2)
  3186. to:
  3187. mov mem1, reg1
  3188. mov reg1, mem2
  3189. mov reg1, reg2
  3190. }
  3191. begin
  3192. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3193. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3194. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3195. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3196. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3197. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3198. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3199. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3200. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3201. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3202. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3203. end
  3204. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3205. begin
  3206. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3207. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3208. end
  3209. else
  3210. begin
  3211. RemoveInstruction(hp2);
  3212. end
  3213. {$endif i386}
  3214. ;
  3215. end;
  3216. end
  3217. { movl [mem1],reg1
  3218. movl [mem1],reg2
  3219. to
  3220. movl [mem1],reg1
  3221. movl reg1,reg2
  3222. }
  3223. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3224. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3225. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3226. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3227. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3228. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3229. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3230. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3231. begin
  3232. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3233. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3234. end;
  3235. { movl const1,[mem1]
  3236. movl [mem1],reg1
  3237. to
  3238. movl const1,reg1
  3239. movl reg1,[mem1]
  3240. }
  3241. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3242. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3243. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3244. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3245. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3246. begin
  3247. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3248. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3249. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3250. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3251. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3252. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3253. Result:=true;
  3254. exit;
  3255. end;
  3256. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3257. { Change:
  3258. movl %reg1,%reg2
  3259. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3260. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3261. To:
  3262. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3263. movl x(%reg1),%reg1
  3264. movl %reg1,%regX
  3265. }
  3266. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3267. begin
  3268. CurrentReg := taicpu(p).oper[0]^.reg;
  3269. ActiveReg := taicpu(p).oper[1]^.reg;
  3270. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3271. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3272. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3273. GetNextInstruction(hp1, hp2) and
  3274. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3275. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3276. begin
  3277. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3278. if RegInRef(ActiveReg, SourceRef) and
  3279. { If %reg1 also appears in the second reference, then it will
  3280. not refer to the same memory block as the first reference }
  3281. not RegInRef(CurrentReg, SourceRef) then
  3282. begin
  3283. { Check to see if the references match if %reg2 is changed to %reg1 }
  3284. if SourceRef.base = ActiveReg then
  3285. SourceRef.base := CurrentReg;
  3286. if SourceRef.index = ActiveReg then
  3287. SourceRef.index := CurrentReg;
  3288. { RefsEqual also checks to ensure both references are non-volatile }
  3289. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3290. begin
  3291. taicpu(hp2).loadreg(0, CurrentReg);
  3292. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3293. Result := True;
  3294. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3295. begin
  3296. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3297. RemoveCurrentP(p, hp1);
  3298. Exit;
  3299. end
  3300. else
  3301. begin
  3302. { Check to see if %reg2 is no longer in use }
  3303. TransferUsedRegs(TmpUsedRegs);
  3304. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3305. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3306. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3307. begin
  3308. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3309. RemoveCurrentP(p, hp1);
  3310. Exit;
  3311. end;
  3312. end;
  3313. { If we reach this point, p and hp1 weren't actually modified,
  3314. so we can do a bit more work on this pass }
  3315. end;
  3316. end;
  3317. end;
  3318. end;
  3319. end;
  3320. { search further than the next instruction for a mov (as long as it's not a jump) }
  3321. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3322. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3323. (taicpu(p).oper[1]^.typ = top_reg) and
  3324. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3325. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3326. begin
  3327. { we work with hp2 here, so hp1 can be still used later on when
  3328. checking for GetNextInstruction_p }
  3329. hp3 := hp1;
  3330. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3331. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3332. { Saves on a large number of dereferences }
  3333. ActiveReg := taicpu(p).oper[1]^.reg;
  3334. TransferUsedRegs(TmpUsedRegs);
  3335. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3336. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3337. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3338. (hp2.typ=ait_instruction) do
  3339. begin
  3340. case taicpu(hp2).opcode of
  3341. A_POP:
  3342. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3343. begin
  3344. if not CrossJump and
  3345. not RegUsedBetween(ActiveReg, p, hp2) then
  3346. begin
  3347. { We can remove the original MOV since the register
  3348. wasn't used between it and its popping from the stack }
  3349. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3350. RemoveCurrentp(p, hp1);
  3351. Result := True;
  3352. Exit;
  3353. end;
  3354. { Can't go any further }
  3355. Break;
  3356. end;
  3357. A_MOV:
  3358. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3359. ((taicpu(p).oper[0]^.typ=top_const) or
  3360. ((taicpu(p).oper[0]^.typ=top_reg) and
  3361. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3362. )
  3363. ) then
  3364. begin
  3365. { we have
  3366. mov x, %treg
  3367. mov %treg, y
  3368. }
  3369. { We don't need to call UpdateUsedRegs for every instruction between
  3370. p and hp2 because the register we're concerned about will not
  3371. become deallocated (otherwise GetNextInstructionUsingReg would
  3372. have stopped at an earlier instruction). [Kit] }
  3373. TempRegUsed :=
  3374. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3375. RegReadByInstruction(ActiveReg, hp3) or
  3376. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3377. case taicpu(p).oper[0]^.typ Of
  3378. top_reg:
  3379. begin
  3380. { change
  3381. mov %reg, %treg
  3382. mov %treg, y
  3383. to
  3384. mov %reg, y
  3385. }
  3386. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3387. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3388. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3389. begin
  3390. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3391. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3392. if TempRegUsed then
  3393. begin
  3394. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3395. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3396. { Set the start of the next GetNextInstructionUsingRegCond search
  3397. to start at the entry right before hp2 (which is about to be removed) }
  3398. hp3 := tai(hp2.Previous);
  3399. RemoveInstruction(hp2);
  3400. { See if there's more we can optimise }
  3401. Continue;
  3402. end
  3403. else
  3404. begin
  3405. RemoveInstruction(hp2);
  3406. { We can remove the original MOV too }
  3407. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3408. RemoveCurrentP(p, hp1);
  3409. Result:=true;
  3410. Exit;
  3411. end;
  3412. end
  3413. else
  3414. begin
  3415. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3416. taicpu(hp2).loadReg(0, CurrentReg);
  3417. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3418. { Check to see if the register also appears in the reference }
  3419. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3420. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3421. { Don't remove the first instruction if the temporary register is in use }
  3422. if not TempRegUsed and
  3423. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3424. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3425. begin
  3426. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3427. RemoveCurrentP(p, hp1);
  3428. Result:=true;
  3429. Exit;
  3430. end;
  3431. { No need to set Result to True here. If there's another instruction later
  3432. on that can be optimised, it will be detected when the main Pass 1 loop
  3433. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3434. end;
  3435. end;
  3436. top_const:
  3437. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3438. begin
  3439. { change
  3440. mov const, %treg
  3441. mov %treg, y
  3442. to
  3443. mov const, y
  3444. }
  3445. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3446. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3447. begin
  3448. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3449. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3450. if TempRegUsed then
  3451. begin
  3452. { Don't remove the first instruction if the temporary register is in use }
  3453. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3454. { No need to set Result to True. If there's another instruction later on
  3455. that can be optimised, it will be detected when the main Pass 1 loop
  3456. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3457. end
  3458. else
  3459. begin
  3460. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3461. RemoveCurrentP(p, hp1);
  3462. Result:=true;
  3463. Exit;
  3464. end;
  3465. end;
  3466. end;
  3467. else
  3468. Internalerror(2019103001);
  3469. end;
  3470. end
  3471. else
  3472. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3473. begin
  3474. if not CrossJump and
  3475. not RegUsedBetween(ActiveReg, p, hp2) and
  3476. not RegReadByInstruction(ActiveReg, hp2) then
  3477. begin
  3478. { Register is not used before it is overwritten }
  3479. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3480. RemoveCurrentp(p, hp1);
  3481. Result := True;
  3482. Exit;
  3483. end;
  3484. if (taicpu(p).oper[0]^.typ = top_const) and
  3485. (taicpu(hp2).oper[0]^.typ = top_const) then
  3486. begin
  3487. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3488. begin
  3489. { Same value - register hasn't changed }
  3490. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3491. RemoveInstruction(hp2);
  3492. Result := True;
  3493. { See if there's more we can optimise }
  3494. Continue;
  3495. end;
  3496. end;
  3497. end;
  3498. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3499. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3500. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3501. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3502. begin
  3503. {
  3504. Change from:
  3505. mov ###, %reg
  3506. ...
  3507. movs/z %reg,%reg (Same register, just different sizes)
  3508. To:
  3509. movs/z ###, %reg (Longer version)
  3510. ...
  3511. (remove)
  3512. }
  3513. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3514. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3515. { Keep the first instruction as mov if ### is a constant }
  3516. if taicpu(p).oper[0]^.typ = top_const then
  3517. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3518. else
  3519. begin
  3520. taicpu(p).opcode := taicpu(hp2).opcode;
  3521. taicpu(p).opsize := taicpu(hp2).opsize;
  3522. end;
  3523. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3524. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3525. RemoveInstruction(hp2);
  3526. Result := True;
  3527. Exit;
  3528. end;
  3529. else
  3530. { Move down to the MatchOpType if-block below };
  3531. end;
  3532. { Also catches MOV/S/Z instructions that aren't modified }
  3533. if taicpu(p).oper[0]^.typ = top_reg then
  3534. begin
  3535. CurrentReg := taicpu(p).oper[0]^.reg;
  3536. if
  3537. not RegModifiedByInstruction(CurrentReg, hp3) and
  3538. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3539. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3540. begin
  3541. Result := True;
  3542. { Just in case something didn't get modified (e.g. an
  3543. implicit register). Also, if it does read from this
  3544. register, then there's no longer an advantage to
  3545. changing the register on subsequent instructions.}
  3546. if not RegReadByInstruction(ActiveReg, hp2) then
  3547. begin
  3548. { If a conditional jump was crossed, do not delete
  3549. the original MOV no matter what }
  3550. if not CrossJump and
  3551. { RegEndOfLife returns True if the register is
  3552. deallocated before the next instruction or has
  3553. been loaded with a new value }
  3554. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3555. begin
  3556. { We can remove the original MOV }
  3557. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3558. RemoveCurrentp(p, hp1);
  3559. Exit;
  3560. end;
  3561. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3562. begin
  3563. { See if there's more we can optimise }
  3564. hp3 := hp2;
  3565. Continue;
  3566. end;
  3567. end;
  3568. end;
  3569. end;
  3570. { Break out of the while loop under normal circumstances }
  3571. Break;
  3572. end;
  3573. end;
  3574. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3575. (taicpu(p).oper[1]^.typ = top_reg) and
  3576. (taicpu(p).opsize = S_L) and
  3577. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3578. (taicpu(hp2).opcode = A_AND) and
  3579. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3580. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3581. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3582. ) then
  3583. begin
  3584. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3585. begin
  3586. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3587. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3588. begin
  3589. { Optimize out:
  3590. mov x, %reg
  3591. and ffffffffh, %reg
  3592. }
  3593. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3594. RemoveInstruction(hp2);
  3595. Result:=true;
  3596. exit;
  3597. end;
  3598. end;
  3599. end;
  3600. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3601. x >= RetOffset) as it doesn't do anything (it writes either to a
  3602. parameter or to the temporary storage room for the function
  3603. result)
  3604. }
  3605. if IsExitCode(hp1) and
  3606. (taicpu(p).oper[1]^.typ = top_ref) and
  3607. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3608. (
  3609. (
  3610. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3611. not (
  3612. assigned(current_procinfo.procdef.funcretsym) and
  3613. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3614. )
  3615. ) or
  3616. { Also discard writes to the stack that are below the base pointer,
  3617. as this is temporary storage rather than a function result on the
  3618. stack, say. }
  3619. (
  3620. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3621. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3622. )
  3623. ) then
  3624. begin
  3625. RemoveCurrentp(p, hp1);
  3626. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3627. RemoveLastDeallocForFuncRes(p);
  3628. Result:=true;
  3629. exit;
  3630. end;
  3631. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3632. begin
  3633. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3634. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3635. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3636. begin
  3637. { change
  3638. mov reg1, mem1
  3639. test/cmp x, mem1
  3640. to
  3641. mov reg1, mem1
  3642. test/cmp x, reg1
  3643. }
  3644. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3645. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3646. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3647. Result := True;
  3648. Exit;
  3649. end;
  3650. if DoMovCmpMemOpt(p, hp1, True) then
  3651. begin
  3652. Result := True;
  3653. Exit;
  3654. end;
  3655. end;
  3656. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3657. { If the flags register is in use, don't change the instruction to an
  3658. ADD otherwise this will scramble the flags. [Kit] }
  3659. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3660. begin
  3661. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3662. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3663. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3664. ) or
  3665. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3666. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3667. )
  3668. ) then
  3669. { mov reg1,ref
  3670. lea reg2,[reg1,reg2]
  3671. to
  3672. add reg2,ref}
  3673. begin
  3674. TransferUsedRegs(TmpUsedRegs);
  3675. { reg1 may not be used afterwards }
  3676. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3677. begin
  3678. Taicpu(hp1).opcode:=A_ADD;
  3679. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3680. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3681. RemoveCurrentp(p, hp1);
  3682. result:=true;
  3683. exit;
  3684. end;
  3685. end;
  3686. { If the LEA instruction can be converted into an arithmetic instruction,
  3687. it may be possible to then fold it in the next optimisation, otherwise
  3688. there's nothing more that can be optimised here. }
  3689. if not ConvertLEA(taicpu(hp1)) then
  3690. Exit;
  3691. end;
  3692. if (taicpu(p).oper[1]^.typ = top_reg) and
  3693. (hp1.typ = ait_instruction) and
  3694. GetNextInstruction(hp1, hp2) and
  3695. MatchInstruction(hp2,A_MOV,[]) and
  3696. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3697. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3698. (
  3699. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3700. {$ifdef x86_64}
  3701. or
  3702. (
  3703. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3704. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3705. )
  3706. {$endif x86_64}
  3707. ) then
  3708. begin
  3709. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3710. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3711. { change movsX/movzX reg/ref, reg2
  3712. add/sub/or/... reg3/$const, reg2
  3713. mov reg2 reg/ref
  3714. dealloc reg2
  3715. to
  3716. add/sub/or/... reg3/$const, reg/ref }
  3717. begin
  3718. TransferUsedRegs(TmpUsedRegs);
  3719. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3720. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3721. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3722. begin
  3723. { by example:
  3724. movswl %si,%eax movswl %si,%eax p
  3725. decl %eax addl %edx,%eax hp1
  3726. movw %ax,%si movw %ax,%si hp2
  3727. ->
  3728. movswl %si,%eax movswl %si,%eax p
  3729. decw %eax addw %edx,%eax hp1
  3730. movw %ax,%si movw %ax,%si hp2
  3731. }
  3732. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3733. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3734. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3735. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3736. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3737. {
  3738. ->
  3739. movswl %si,%eax movswl %si,%eax p
  3740. decw %si addw %dx,%si hp1
  3741. movw %ax,%si movw %ax,%si hp2
  3742. }
  3743. case taicpu(hp1).ops of
  3744. 1:
  3745. begin
  3746. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3747. if taicpu(hp1).oper[0]^.typ=top_reg then
  3748. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3749. end;
  3750. 2:
  3751. begin
  3752. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3753. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3754. (taicpu(hp1).opcode<>A_SHL) and
  3755. (taicpu(hp1).opcode<>A_SHR) and
  3756. (taicpu(hp1).opcode<>A_SAR) then
  3757. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3758. end;
  3759. else
  3760. internalerror(2008042701);
  3761. end;
  3762. {
  3763. ->
  3764. decw %si addw %dx,%si p
  3765. }
  3766. RemoveInstruction(hp2);
  3767. RemoveCurrentP(p, hp1);
  3768. Result:=True;
  3769. Exit;
  3770. end;
  3771. end;
  3772. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3773. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3774. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3775. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3776. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3777. )
  3778. {$ifdef i386}
  3779. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3780. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3781. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3782. {$endif i386}
  3783. then
  3784. { change movsX/movzX reg/ref, reg2
  3785. add/sub/or/... regX/$const, reg2
  3786. mov reg2, reg3
  3787. dealloc reg2
  3788. to
  3789. movsX/movzX reg/ref, reg3
  3790. add/sub/or/... reg3/$const, reg3
  3791. }
  3792. begin
  3793. TransferUsedRegs(TmpUsedRegs);
  3794. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3795. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3796. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3797. begin
  3798. { by example:
  3799. movswl %si,%eax movswl %si,%eax p
  3800. decl %eax addl %edx,%eax hp1
  3801. movw %ax,%si movw %ax,%si hp2
  3802. ->
  3803. movswl %si,%eax movswl %si,%eax p
  3804. decw %eax addw %edx,%eax hp1
  3805. movw %ax,%si movw %ax,%si hp2
  3806. }
  3807. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3808. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3809. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3810. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3811. { limit size of constants as well to avoid assembler errors, but
  3812. check opsize to avoid overflow when left shifting the 1 }
  3813. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3814. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3815. {$ifdef x86_64}
  3816. { Be careful of, for example:
  3817. movl %reg1,%reg2
  3818. addl %reg3,%reg2
  3819. movq %reg2,%reg4
  3820. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3821. }
  3822. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3823. begin
  3824. taicpu(hp2).changeopsize(S_L);
  3825. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3826. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3827. end;
  3828. {$endif x86_64}
  3829. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3830. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3831. if taicpu(p).oper[0]^.typ=top_reg then
  3832. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3833. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3834. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3835. {
  3836. ->
  3837. movswl %si,%eax movswl %si,%eax p
  3838. decw %si addw %dx,%si hp1
  3839. movw %ax,%si movw %ax,%si hp2
  3840. }
  3841. case taicpu(hp1).ops of
  3842. 1:
  3843. begin
  3844. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3845. if taicpu(hp1).oper[0]^.typ=top_reg then
  3846. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3847. end;
  3848. 2:
  3849. begin
  3850. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3851. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3852. (taicpu(hp1).opcode<>A_SHL) and
  3853. (taicpu(hp1).opcode<>A_SHR) and
  3854. (taicpu(hp1).opcode<>A_SAR) then
  3855. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3856. end;
  3857. else
  3858. internalerror(2018111801);
  3859. end;
  3860. {
  3861. ->
  3862. decw %si addw %dx,%si p
  3863. }
  3864. RemoveInstruction(hp2);
  3865. end;
  3866. end;
  3867. end;
  3868. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3869. GetNextInstruction(hp1, hp2) and
  3870. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3871. MatchOperand(Taicpu(p).oper[0]^,0) and
  3872. (Taicpu(p).oper[1]^.typ = top_reg) and
  3873. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3874. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3875. { mov reg1,0
  3876. bts reg1,operand1 --> mov reg1,operand2
  3877. or reg1,operand2 bts reg1,operand1}
  3878. begin
  3879. Taicpu(hp2).opcode:=A_MOV;
  3880. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3881. asml.remove(hp1);
  3882. insertllitem(hp2,hp2.next,hp1);
  3883. RemoveCurrentp(p, hp1);
  3884. Result:=true;
  3885. exit;
  3886. end;
  3887. {
  3888. mov ref,reg0
  3889. <op> reg0,reg1
  3890. dealloc reg0
  3891. to
  3892. <op> ref,reg1
  3893. }
  3894. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3895. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3896. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3897. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3898. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3899. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3900. begin
  3901. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3902. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3903. RemoveCurrentp(p, hp1);
  3904. Result:=true;
  3905. exit;
  3906. end;
  3907. {$ifdef x86_64}
  3908. { Convert:
  3909. movq x(ref),%reg64
  3910. shrq y,%reg64
  3911. To:
  3912. movl x+4(ref),%reg32
  3913. shrl y-32,%reg32 (Remove if y = 32)
  3914. }
  3915. if (taicpu(p).opsize = S_Q) and
  3916. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3917. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3918. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3919. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3920. (taicpu(hp1).oper[0]^.val >= 32) and
  3921. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3922. begin
  3923. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3924. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3925. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3926. { Convert to 32-bit }
  3927. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3928. taicpu(p).opsize := S_L;
  3929. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3930. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3931. if (taicpu(hp1).oper[0]^.val = 32) then
  3932. begin
  3933. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3934. RemoveInstruction(hp1);
  3935. end
  3936. else
  3937. begin
  3938. { This will potentially open up more arithmetic operations since
  3939. the peephole optimizer now has a big hint that only the lower
  3940. 32 bits are currently in use (and opcodes are smaller in size) }
  3941. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3942. taicpu(hp1).opsize := S_L;
  3943. Dec(taicpu(hp1).oper[0]^.val, 32);
  3944. DebugMsg(SPeepholeOptimization + PreMessage +
  3945. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3946. end;
  3947. Result := True;
  3948. Exit;
  3949. end;
  3950. {$endif x86_64}
  3951. { Backward optimisation. If we have:
  3952. func. %reg1,%reg2
  3953. mov %reg2,%reg3
  3954. (dealloc %reg2)
  3955. Change to:
  3956. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3957. }
  3958. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3959. begin
  3960. CurrentReg := taicpu(p).oper[0]^.reg;
  3961. ActiveReg := taicpu(p).oper[1]^.reg;
  3962. TransferUsedRegs(TmpUsedRegs);
  3963. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3964. GetLastInstruction(p, hp2) and
  3965. (hp2.typ = ait_instruction) and
  3966. { Have to make sure it's an instruction that only reads from
  3967. operand 1 and only writes (not reads or modifies) from operand 2;
  3968. in essence, a one-operand pure function such as BSR or POPCNT }
  3969. (taicpu(hp2).ops = 2) and
  3970. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3971. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3972. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3973. begin
  3974. case taicpu(hp2).opcode of
  3975. A_FSTSW, A_FNSTSW,
  3976. A_IN, A_INS, A_OUT, A_OUTS,
  3977. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3978. { These routines have explicit operands, but they are restricted in
  3979. what they can be (e.g. IN and OUT can only read from AL, AX or
  3980. EAX. }
  3981. A_CMOVcc:
  3982. { CMOV is not valid either because then CurrentReg will depend
  3983. on an unknown value if the condition is False and hence is
  3984. not a pure write }
  3985. ;
  3986. else
  3987. begin
  3988. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3989. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3990. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3991. RemoveCurrentp(p, hp1);
  3992. Result := True;
  3993. Exit;
  3994. end;
  3995. end;
  3996. end;
  3997. end;
  3998. end;
  3999. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4000. var
  4001. hp1 : tai;
  4002. begin
  4003. Result:=false;
  4004. if taicpu(p).ops <> 2 then
  4005. exit;
  4006. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4007. GetNextInstruction(p,hp1) then
  4008. begin
  4009. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4010. (taicpu(hp1).ops = 2) then
  4011. begin
  4012. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4013. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4014. { movXX reg1, mem1 or movXX mem1, reg1
  4015. movXX mem2, reg2 movXX reg2, mem2}
  4016. begin
  4017. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4018. { movXX reg1, mem1 or movXX mem1, reg1
  4019. movXX mem2, reg1 movXX reg2, mem1}
  4020. begin
  4021. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4022. begin
  4023. { Removes the second statement from
  4024. movXX reg1, mem1/reg2
  4025. movXX mem1/reg2, reg1
  4026. }
  4027. if taicpu(p).oper[0]^.typ=top_reg then
  4028. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4029. { Removes the second statement from
  4030. movXX mem1/reg1, reg2
  4031. movXX reg2, mem1/reg1
  4032. }
  4033. if (taicpu(p).oper[1]^.typ=top_reg) and
  4034. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4035. begin
  4036. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4037. RemoveInstruction(hp1);
  4038. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4039. Result:=true;
  4040. exit;
  4041. end
  4042. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4043. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4044. begin
  4045. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4046. RemoveInstruction(hp1);
  4047. Result:=true;
  4048. exit;
  4049. end;
  4050. end
  4051. end;
  4052. end;
  4053. end;
  4054. end;
  4055. end;
  4056. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4057. var
  4058. hp1 : tai;
  4059. begin
  4060. result:=false;
  4061. { replace
  4062. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4063. MovX %mreg2,%mreg1
  4064. dealloc %mreg2
  4065. by
  4066. <Op>X %mreg2,%mreg1
  4067. ?
  4068. }
  4069. if GetNextInstruction(p,hp1) and
  4070. { we mix single and double opperations here because we assume that the compiler
  4071. generates vmovapd only after double operations and vmovaps only after single operations }
  4072. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4073. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4074. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4075. (taicpu(p).oper[0]^.typ=top_reg) then
  4076. begin
  4077. TransferUsedRegs(TmpUsedRegs);
  4078. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4079. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4080. begin
  4081. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4082. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4083. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4084. RemoveInstruction(hp1);
  4085. result:=true;
  4086. end;
  4087. end;
  4088. end;
  4089. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4090. var
  4091. hp1, p_label, p_dist, hp1_dist: tai;
  4092. JumpLabel, JumpLabel_dist: TAsmLabel;
  4093. FirstValue, SecondValue: TCGInt;
  4094. begin
  4095. Result := False;
  4096. if (taicpu(p).oper[0]^.typ = top_const) and
  4097. (taicpu(p).oper[0]^.val <> -1) then
  4098. begin
  4099. { Convert unsigned maximum constants to -1 to aid optimisation }
  4100. case taicpu(p).opsize of
  4101. S_B:
  4102. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4103. begin
  4104. taicpu(p).oper[0]^.val := -1;
  4105. Result := True;
  4106. Exit;
  4107. end;
  4108. S_W:
  4109. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4110. begin
  4111. taicpu(p).oper[0]^.val := -1;
  4112. Result := True;
  4113. Exit;
  4114. end;
  4115. S_L:
  4116. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4117. begin
  4118. taicpu(p).oper[0]^.val := -1;
  4119. Result := True;
  4120. Exit;
  4121. end;
  4122. {$ifdef x86_64}
  4123. S_Q:
  4124. { Storing anything greater than $7FFFFFFF is not possible so do
  4125. nothing };
  4126. {$endif x86_64}
  4127. else
  4128. InternalError(2021121001);
  4129. end;
  4130. end;
  4131. if GetNextInstruction(p, hp1) and
  4132. TrySwapMovCmp(p, hp1) then
  4133. begin
  4134. Result := True;
  4135. Exit;
  4136. end;
  4137. { Search for:
  4138. test $x,(reg/ref)
  4139. jne @lbl1
  4140. test $y,(reg/ref) (same register or reference)
  4141. jne @lbl1
  4142. Change to:
  4143. test $(x or y),(reg/ref)
  4144. jne @lbl1
  4145. (Note, this doesn't work with je instead of jne)
  4146. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4147. Also search for:
  4148. test $x,(reg/ref)
  4149. je @lbl1
  4150. test $y,(reg/ref)
  4151. je/jne @lbl2
  4152. If (x or y) = x, then the second jump is deterministic
  4153. }
  4154. if (
  4155. (
  4156. (taicpu(p).oper[0]^.typ = top_const) or
  4157. (
  4158. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4159. (taicpu(p).oper[0]^.typ = top_reg) and
  4160. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4161. )
  4162. ) and
  4163. MatchInstruction(hp1, A_JCC, [])
  4164. ) then
  4165. begin
  4166. if (taicpu(p).oper[0]^.typ = top_reg) and
  4167. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4168. FirstValue := -1
  4169. else
  4170. FirstValue := taicpu(p).oper[0]^.val;
  4171. { If we have several test/jne's in a row, it might be the case that
  4172. the second label doesn't go to the same location, but the one
  4173. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4174. so accommodate for this with a while loop.
  4175. }
  4176. hp1_dist := hp1;
  4177. if GetNextInstruction(hp1, p_dist) and
  4178. (p_dist.typ = ait_instruction) and
  4179. (
  4180. (
  4181. (taicpu(p_dist).opcode = A_TEST) and
  4182. (
  4183. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4184. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4185. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4186. )
  4187. ) or
  4188. (
  4189. { cmp 0,%reg = test %reg,%reg }
  4190. (taicpu(p_dist).opcode = A_CMP) and
  4191. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4192. )
  4193. ) and
  4194. { Make sure the destination operands are actually the same }
  4195. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4196. GetNextInstruction(p_dist, hp1_dist) and
  4197. MatchInstruction(hp1_dist, A_JCC, []) then
  4198. begin
  4199. if
  4200. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4201. (
  4202. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4203. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4204. ) then
  4205. SecondValue := -1
  4206. else
  4207. SecondValue := taicpu(p_dist).oper[0]^.val;
  4208. { If both of the TEST constants are identical, delete the second
  4209. TEST that is unnecessary. }
  4210. if (FirstValue = SecondValue) then
  4211. begin
  4212. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4213. RemoveInstruction(p_dist);
  4214. { Don't let the flags register become deallocated and reallocated between the jumps }
  4215. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4216. Result := True;
  4217. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4218. begin
  4219. { Since the second jump's condition is a subset of the first, we
  4220. know it will never branch because the first jump dominates it.
  4221. Get it out of the way now rather than wait for the jump
  4222. optimisations for a speed boost. }
  4223. if IsJumpToLabel(taicpu(hp1_dist)) then
  4224. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4225. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4226. RemoveInstruction(hp1_dist);
  4227. end
  4228. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4229. begin
  4230. { If the inverse of the first condition is a subset of the second,
  4231. the second one will definitely branch if the first one doesn't }
  4232. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4233. MakeUnconditional(taicpu(hp1_dist));
  4234. RemoveDeadCodeAfterJump(hp1_dist);
  4235. end;
  4236. Exit;
  4237. end;
  4238. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4239. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4240. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4241. then the second jump will never branch, so it can also be
  4242. removed regardless of where it goes }
  4243. (
  4244. (FirstValue = -1) or
  4245. (SecondValue = -1) or
  4246. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4247. ) then
  4248. begin
  4249. { Same jump location... can be a register since nothing's changed }
  4250. { If any of the entries are equivalent to test %reg,%reg, then the
  4251. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4252. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4253. if IsJumpToLabel(taicpu(hp1_dist)) then
  4254. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4255. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4256. RemoveInstruction(hp1_dist);
  4257. { Only remove the second test if no jumps or other conditional instructions follow }
  4258. TransferUsedRegs(TmpUsedRegs);
  4259. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4260. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4261. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4262. RemoveInstruction(p_dist);
  4263. Result := True;
  4264. Exit;
  4265. end;
  4266. end;
  4267. end;
  4268. { Search for:
  4269. test %reg,%reg
  4270. j(c1) @lbl1
  4271. ...
  4272. @lbl:
  4273. test %reg,%reg (same register)
  4274. j(c2) @lbl2
  4275. If c2 is a subset of c1, change to:
  4276. test %reg,%reg
  4277. j(c1) @lbl2
  4278. (@lbl1 may become a dead label as a result)
  4279. }
  4280. if (taicpu(p).oper[1]^.typ = top_reg) and
  4281. (taicpu(p).oper[0]^.typ = top_reg) and
  4282. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4283. MatchInstruction(hp1, A_JCC, []) and
  4284. IsJumpToLabel(taicpu(hp1)) then
  4285. begin
  4286. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4287. p_label := nil;
  4288. if Assigned(JumpLabel) then
  4289. p_label := getlabelwithsym(JumpLabel);
  4290. if Assigned(p_label) and
  4291. GetNextInstruction(p_label, p_dist) and
  4292. MatchInstruction(p_dist, A_TEST, []) and
  4293. { It's fine if the second test uses smaller sub-registers }
  4294. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4295. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4296. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4297. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4298. GetNextInstruction(p_dist, hp1_dist) and
  4299. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4300. begin
  4301. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4302. if JumpLabel = JumpLabel_dist then
  4303. { This is an infinite loop }
  4304. Exit;
  4305. { Best optimisation when the first condition is a subset (or equal) of the second }
  4306. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4307. begin
  4308. { Any registers used here will already be allocated }
  4309. if Assigned(JumpLabel_dist) then
  4310. JumpLabel_dist.IncRefs;
  4311. if Assigned(JumpLabel) then
  4312. JumpLabel.DecRefs;
  4313. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4314. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4315. Result := True;
  4316. Exit;
  4317. end;
  4318. end;
  4319. end;
  4320. end;
  4321. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4322. var
  4323. hp1, hp2: tai;
  4324. ActiveReg: TRegister;
  4325. OldOffset: asizeint;
  4326. ThisConst: TCGInt;
  4327. function RegDeallocated: Boolean;
  4328. begin
  4329. TransferUsedRegs(TmpUsedRegs);
  4330. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4331. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4332. end;
  4333. begin
  4334. result:=false;
  4335. hp1 := nil;
  4336. { replace
  4337. addX const,%reg1
  4338. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4339. dealloc %reg1
  4340. by
  4341. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4342. }
  4343. if MatchOpType(taicpu(p),top_const,top_reg) then
  4344. begin
  4345. ActiveReg := taicpu(p).oper[1]^.reg;
  4346. { Ensures the entire register was updated }
  4347. if (taicpu(p).opsize >= S_L) and
  4348. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4349. MatchInstruction(hp1,A_LEA,[]) and
  4350. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4351. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4352. (
  4353. { Cover the case where the register in the reference is also the destination register }
  4354. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4355. (
  4356. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4357. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4358. RegDeallocated
  4359. )
  4360. ) then
  4361. begin
  4362. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4363. {$push}
  4364. {$R-}{$Q-}
  4365. { Explicitly disable overflow checking for these offset calculation
  4366. as those do not matter for the final result }
  4367. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4368. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4369. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4370. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4371. {$pop}
  4372. {$ifdef x86_64}
  4373. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4374. begin
  4375. { Overflow; abort }
  4376. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4377. end
  4378. else
  4379. {$endif x86_64}
  4380. begin
  4381. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4382. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4383. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4384. RemoveCurrentP(p, hp1)
  4385. else
  4386. RemoveCurrentP(p);
  4387. result:=true;
  4388. Exit;
  4389. end;
  4390. end;
  4391. if (
  4392. { Save calling GetNextInstructionUsingReg again }
  4393. Assigned(hp1) or
  4394. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4395. ) and
  4396. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4397. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4398. begin
  4399. if taicpu(hp1).oper[0]^.typ = top_const then
  4400. begin
  4401. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4402. if taicpu(hp1).opcode = A_ADD then
  4403. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4404. else
  4405. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4406. Result := True;
  4407. { Handle any overflows }
  4408. case taicpu(p).opsize of
  4409. S_B:
  4410. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4411. S_W:
  4412. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4413. S_L:
  4414. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4415. {$ifdef x86_64}
  4416. S_Q:
  4417. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4418. { Overflow; abort }
  4419. Result := False
  4420. else
  4421. taicpu(p).oper[0]^.val := ThisConst;
  4422. {$endif x86_64}
  4423. else
  4424. InternalError(2021102610);
  4425. end;
  4426. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4427. if Result then
  4428. begin
  4429. if (taicpu(p).oper[0]^.val < 0) and
  4430. (
  4431. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4432. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4433. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4434. ) then
  4435. begin
  4436. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4437. taicpu(p).opcode := A_SUB;
  4438. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4439. end
  4440. else
  4441. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4442. RemoveInstruction(hp1);
  4443. end;
  4444. end
  4445. else
  4446. begin
  4447. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4448. TransferUsedRegs(TmpUsedRegs);
  4449. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4450. hp2 := p;
  4451. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4452. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4453. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4454. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4455. begin
  4456. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4457. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4458. Asml.Remove(p);
  4459. Asml.InsertAfter(p, hp1);
  4460. p := hp1;
  4461. Result := True;
  4462. end;
  4463. end;
  4464. end;
  4465. end;
  4466. end;
  4467. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4468. var
  4469. hp1: tai;
  4470. ref: Integer;
  4471. saveref: treference;
  4472. TempReg: TRegister;
  4473. Multiple: TCGInt;
  4474. begin
  4475. Result:=false;
  4476. { play save and throw an error if LEA uses a seg register prefix,
  4477. this is most likely an error somewhere else }
  4478. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4479. internalerror(2022022001);
  4480. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4481. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4482. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4483. (
  4484. { do not mess with leas accessing the stack pointer
  4485. unless it's a null operation }
  4486. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4487. (
  4488. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4489. (taicpu(p).oper[0]^.ref^.offset = 0)
  4490. )
  4491. ) and
  4492. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4493. begin
  4494. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4495. begin
  4496. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4497. begin
  4498. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4499. taicpu(p).oper[1]^.reg);
  4500. InsertLLItem(p.previous,p.next, hp1);
  4501. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4502. p.free;
  4503. p:=hp1;
  4504. end
  4505. else
  4506. begin
  4507. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4508. RemoveCurrentP(p);
  4509. end;
  4510. Result:=true;
  4511. exit;
  4512. end
  4513. else if (
  4514. { continue to use lea to adjust the stack pointer,
  4515. it is the recommended way, but only if not optimizing for size }
  4516. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4517. (cs_opt_size in current_settings.optimizerswitches)
  4518. ) and
  4519. { If the flags register is in use, don't change the instruction
  4520. to an ADD otherwise this will scramble the flags. [Kit] }
  4521. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4522. ConvertLEA(taicpu(p)) then
  4523. begin
  4524. Result:=true;
  4525. exit;
  4526. end;
  4527. end;
  4528. if GetNextInstruction(p,hp1) and
  4529. (hp1.typ=ait_instruction) then
  4530. begin
  4531. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4532. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4533. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4534. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4535. begin
  4536. TransferUsedRegs(TmpUsedRegs);
  4537. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4538. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4539. begin
  4540. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4541. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4542. RemoveInstruction(hp1);
  4543. result:=true;
  4544. exit;
  4545. end;
  4546. end;
  4547. { changes
  4548. lea <ref1>, reg1
  4549. <op> ...,<ref. with reg1>,...
  4550. to
  4551. <op> ...,<ref1>,... }
  4552. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4553. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4554. not(MatchInstruction(hp1,A_LEA,[])) then
  4555. begin
  4556. { find a reference which uses reg1 }
  4557. 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
  4558. ref:=0
  4559. 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
  4560. ref:=1
  4561. else
  4562. ref:=-1;
  4563. if (ref<>-1) and
  4564. { reg1 must be either the base or the index }
  4565. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4566. begin
  4567. { reg1 can be removed from the reference }
  4568. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4569. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4570. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4571. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4572. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4573. else
  4574. Internalerror(2019111201);
  4575. { check if the can insert all data of the lea into the second instruction }
  4576. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4577. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4578. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4579. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4580. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4581. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4582. { Segment register of p.oper[0]^.ref will be NR_NO already }
  4583. (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4584. {$ifdef x86_64}
  4585. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4586. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4587. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4588. )
  4589. {$endif x86_64}
  4590. then
  4591. begin
  4592. { reg1 might not used by the second instruction after it is remove from the reference }
  4593. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4594. begin
  4595. TransferUsedRegs(TmpUsedRegs);
  4596. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4597. { reg1 is not updated so it might not be used afterwards }
  4598. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4599. begin
  4600. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4601. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4602. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4603. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4604. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4605. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4606. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4607. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4608. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4609. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4610. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4611. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4612. RemoveCurrentP(p, hp1);
  4613. result:=true;
  4614. exit;
  4615. end
  4616. end;
  4617. end;
  4618. { recover }
  4619. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4620. end;
  4621. end;
  4622. end;
  4623. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4624. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4625. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4626. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4627. begin
  4628. { Check common LEA/LEA conditions }
  4629. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4630. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4631. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4632. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4633. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4634. { Since we're merging two LEA instructions, the segment registers don't matter }
  4635. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4636. (
  4637. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4638. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4639. ) and (
  4640. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4641. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4642. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4643. ) then
  4644. begin
  4645. { changes
  4646. lea (regX,scale), reg1
  4647. lea offset(reg1,reg1), reg1
  4648. to
  4649. lea offset(regX,scale*2), reg1
  4650. and
  4651. lea (regX,scale1), reg1
  4652. lea offset(reg1,scale2), reg1
  4653. to
  4654. lea offset(regX,scale1*scale2), reg1
  4655. ... so long as the final scale does not exceed 8
  4656. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4657. }
  4658. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4659. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4660. (
  4661. (
  4662. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4663. ) or (
  4664. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4665. (
  4666. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4667. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4668. )
  4669. )
  4670. ) and (
  4671. (
  4672. { lea (reg1,scale2), reg1 variant }
  4673. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4674. (
  4675. (
  4676. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4677. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4678. ) or (
  4679. { lea (regX,regX), reg1 variant }
  4680. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4681. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4682. )
  4683. )
  4684. ) or (
  4685. { lea (reg1,reg1), reg1 variant }
  4686. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4687. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4688. )
  4689. ) then
  4690. begin
  4691. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4692. { Make everything homogeneous to make calculations easier }
  4693. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4694. begin
  4695. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4696. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4697. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4698. else
  4699. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4700. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4701. end;
  4702. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4703. begin
  4704. { Just to prevent miscalculations }
  4705. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4706. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4707. else
  4708. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4709. end
  4710. else
  4711. begin
  4712. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4713. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4714. end;
  4715. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4716. RemoveCurrentP(p);
  4717. result:=true;
  4718. exit;
  4719. end
  4720. { changes
  4721. lea offset1(regX), reg1
  4722. lea offset2(reg1), reg1
  4723. to
  4724. lea offset1+offset2(regX), reg1 }
  4725. else if
  4726. (
  4727. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4728. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4729. ) or (
  4730. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4731. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4732. (
  4733. (
  4734. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4735. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4736. ) or (
  4737. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4738. (
  4739. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4740. (
  4741. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4742. (
  4743. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4744. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4745. )
  4746. )
  4747. )
  4748. )
  4749. )
  4750. ) then
  4751. begin
  4752. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4753. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4754. begin
  4755. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4756. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4757. { if the register is used as index and base, we have to increase for base as well
  4758. and adapt base }
  4759. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4760. begin
  4761. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4762. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4763. end;
  4764. end
  4765. else
  4766. begin
  4767. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4768. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4769. end;
  4770. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4771. begin
  4772. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4773. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4774. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4775. end;
  4776. RemoveCurrentP(p);
  4777. result:=true;
  4778. exit;
  4779. end;
  4780. end;
  4781. { Change:
  4782. leal/q $x(%reg1),%reg2
  4783. ...
  4784. shll/q $y,%reg2
  4785. To:
  4786. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4787. }
  4788. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4789. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4790. (taicpu(hp1).oper[0]^.val <= 3) then
  4791. begin
  4792. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4793. TransferUsedRegs(TmpUsedRegs);
  4794. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4795. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4796. if
  4797. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4798. (this works even if scalefactor is zero) }
  4799. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4800. { Ensure offset doesn't go out of bounds }
  4801. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4802. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4803. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4804. (
  4805. (
  4806. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4807. (
  4808. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4809. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4810. (
  4811. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4812. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4813. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4814. )
  4815. )
  4816. ) or (
  4817. (
  4818. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4819. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4820. ) and
  4821. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4822. )
  4823. ) then
  4824. begin
  4825. repeat
  4826. with taicpu(p).oper[0]^.ref^ do
  4827. begin
  4828. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4829. if index = base then
  4830. begin
  4831. if Multiple > 4 then
  4832. { Optimisation will no longer work because resultant
  4833. scale factor will exceed 8 }
  4834. Break;
  4835. base := NR_NO;
  4836. scalefactor := 2;
  4837. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4838. end
  4839. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4840. begin
  4841. { Scale factor only works on the index register }
  4842. index := base;
  4843. base := NR_NO;
  4844. end;
  4845. { For safety }
  4846. if scalefactor <= 1 then
  4847. begin
  4848. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4849. scalefactor := Multiple;
  4850. end
  4851. else
  4852. begin
  4853. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4854. scalefactor := scalefactor * Multiple;
  4855. end;
  4856. offset := offset * Multiple;
  4857. end;
  4858. RemoveInstruction(hp1);
  4859. Result := True;
  4860. Exit;
  4861. { This repeat..until loop exists for the benefit of Break }
  4862. until True;
  4863. end;
  4864. end;
  4865. end;
  4866. end;
  4867. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4868. var
  4869. hp1 : tai;
  4870. begin
  4871. DoSubAddOpt := False;
  4872. if taicpu(p).oper[0]^.typ <> top_const then
  4873. { Should have been confirmed before calling }
  4874. InternalError(2021102601);
  4875. if GetLastInstruction(p, hp1) and
  4876. (hp1.typ = ait_instruction) and
  4877. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4878. case taicpu(hp1).opcode Of
  4879. A_DEC:
  4880. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4881. begin
  4882. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4883. RemoveInstruction(hp1);
  4884. end;
  4885. A_SUB:
  4886. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4887. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4888. begin
  4889. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4890. RemoveInstruction(hp1);
  4891. end;
  4892. A_ADD:
  4893. begin
  4894. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4895. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4896. begin
  4897. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4898. RemoveInstruction(hp1);
  4899. if (taicpu(p).oper[0]^.val = 0) then
  4900. begin
  4901. hp1 := tai(p.next);
  4902. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4903. if not GetLastInstruction(hp1, p) then
  4904. p := hp1;
  4905. DoSubAddOpt := True;
  4906. end
  4907. end;
  4908. end;
  4909. else
  4910. ;
  4911. end;
  4912. end;
  4913. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4914. begin
  4915. Result := False;
  4916. if UpdateTmpUsedRegs then
  4917. TransferUsedRegs(TmpUsedRegs);
  4918. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4919. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4920. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4921. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4922. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4923. (
  4924. (
  4925. (taicpu(hp1).opcode = A_TEST)
  4926. ) or (
  4927. (taicpu(hp1).opcode = A_CMP) and
  4928. { A sanity check more than anything }
  4929. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4930. )
  4931. ) then
  4932. begin
  4933. { change
  4934. mov mem, %reg
  4935. cmp/test x, %reg / test %reg,%reg
  4936. (reg deallocated)
  4937. to
  4938. cmp/test x, mem / cmp 0, mem
  4939. }
  4940. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4941. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4942. begin
  4943. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4944. if (taicpu(hp1).opcode = A_TEST) and
  4945. (
  4946. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4947. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4948. ) then
  4949. begin
  4950. taicpu(hp1).opcode := A_CMP;
  4951. taicpu(hp1).loadconst(0, 0);
  4952. end;
  4953. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4954. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4955. RemoveCurrentP(p, hp1);
  4956. Result := True;
  4957. Exit;
  4958. end;
  4959. end;
  4960. end;
  4961. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  4962. var
  4963. hp2, hp3, hp4, hp5, hp6: tai;
  4964. ThisReg: TRegister;
  4965. JumpLoc: TAsmLabel;
  4966. begin
  4967. Result := False;
  4968. {
  4969. Convert:
  4970. j<c> .L1
  4971. .L2:
  4972. mov 1,reg
  4973. jmp .L3 (or ret, although it might not be a RET yet)
  4974. .L1:
  4975. mov 0,reg
  4976. jmp .L3 (or ret)
  4977. ( As long as .L3 <> .L1 or .L2)
  4978. To:
  4979. mov 0,reg
  4980. set<not(c)> reg
  4981. jmp .L3 (or ret)
  4982. .L2:
  4983. mov 1,reg
  4984. jmp .L3 (or ret)
  4985. .L1:
  4986. mov 0,reg
  4987. jmp .L3 (or ret)
  4988. }
  4989. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  4990. Exit;
  4991. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  4992. if GetNextInstruction(hp_label, hp2) and
  4993. MatchInstruction(hp2,A_MOV,[]) and
  4994. (taicpu(hp2).oper[0]^.typ = top_const) and
  4995. (
  4996. (
  4997. (taicpu(hp2).oper[1]^.typ = top_reg)
  4998. {$ifdef i386}
  4999. { Under i386, ESI, EDI, EBP and ESP
  5000. don't have an 8-bit representation }
  5001. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5002. {$endif i386}
  5003. ) or (
  5004. {$ifdef i386}
  5005. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5006. {$endif i386}
  5007. (taicpu(hp2).opsize = S_B)
  5008. )
  5009. ) and
  5010. GetNextInstruction(hp2, hp3) and
  5011. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5012. (
  5013. (taicpu(hp3).opcode=A_RET) or
  5014. (
  5015. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5016. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5017. )
  5018. ) and
  5019. GetNextInstruction(hp3, hp4) and
  5020. SkipAligns(hp4, hp4) and
  5021. (hp4.typ=ait_label) and
  5022. (tai_label(hp4).labsym=JumpLoc) and
  5023. (
  5024. not (cs_opt_size in current_settings.optimizerswitches) or
  5025. { If the initial jump is the label's only reference, then it will
  5026. become a dead label if the other conditions are met and hence
  5027. remove at least 2 instructions, including a jump }
  5028. (JumpLoc.getrefs = 1)
  5029. ) and
  5030. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5031. that will be optimised out }
  5032. GetNextInstruction(hp4, hp5) and
  5033. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5034. (taicpu(hp5).oper[0]^.typ = top_const) and
  5035. (
  5036. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5037. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5038. ) and
  5039. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5040. GetNextInstruction(hp5,hp6) and
  5041. (
  5042. (hp6.typ<>ait_label) or
  5043. SkipLabels(hp6, hp6)
  5044. ) and
  5045. (hp6.typ=ait_instruction) then
  5046. begin
  5047. { First, let's look at the two jumps that are hp3 and hp6 }
  5048. if not
  5049. (
  5050. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5051. (
  5052. (taicpu(hp6).opcode=A_RET) or
  5053. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5054. )
  5055. ) then
  5056. { If condition is False, then the JMP/RET instructions matched conventionally }
  5057. begin
  5058. { See if one of the jumps can be instantly converted into a RET }
  5059. if (taicpu(hp3).opcode=A_JMP) then
  5060. begin
  5061. { Reuse hp5 }
  5062. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5063. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5064. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5065. Exit;
  5066. if MatchInstruction(hp5, A_RET, []) then
  5067. begin
  5068. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5069. ConvertJumpToRET(hp3, hp5);
  5070. Result := True;
  5071. end
  5072. else
  5073. Exit;
  5074. end;
  5075. if (taicpu(hp6).opcode=A_JMP) then
  5076. begin
  5077. { Reuse hp5 }
  5078. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5079. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5080. Exit;
  5081. if MatchInstruction(hp5, A_RET, []) then
  5082. begin
  5083. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5084. ConvertJumpToRET(hp6, hp5);
  5085. Result := True;
  5086. end
  5087. else
  5088. Exit;
  5089. end;
  5090. if not
  5091. (
  5092. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5093. (
  5094. (taicpu(hp6).opcode=A_RET) or
  5095. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5096. )
  5097. ) then
  5098. { Still doesn't match }
  5099. Exit;
  5100. end;
  5101. if (taicpu(hp2).oper[0]^.val = 1) then
  5102. begin
  5103. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5104. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5105. end
  5106. else
  5107. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5108. if taicpu(hp2).opsize=S_B then
  5109. begin
  5110. if taicpu(hp2).oper[1]^.typ = top_reg then
  5111. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5112. else
  5113. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5114. hp2 := p;
  5115. end
  5116. else
  5117. begin
  5118. { Will be a register because the size can't be S_B otherwise }
  5119. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5120. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5121. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5122. { Inserting it right before p will guarantee that the flags are also tracked }
  5123. Asml.InsertBefore(hp2, p);
  5124. end;
  5125. taicpu(hp4).condition:=taicpu(p).condition;
  5126. asml.InsertBefore(hp4, hp2);
  5127. JumpLoc.decrefs;
  5128. if taicpu(hp3).opcode = A_JMP then
  5129. begin
  5130. MakeUnconditional(taicpu(p));
  5131. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5132. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5133. end
  5134. else
  5135. begin
  5136. taicpu(p).condition := C_None;
  5137. taicpu(p).opcode := A_RET;
  5138. taicpu(p).clearop(0);
  5139. taicpu(p).ops := 0;
  5140. end;
  5141. if (JumpLoc.getrefs = 0) then
  5142. RemoveDeadCodeAfterJump(hp3);
  5143. Result:=true;
  5144. exit;
  5145. end;
  5146. end;
  5147. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5148. var
  5149. hp1, hp2: tai;
  5150. ActiveReg: TRegister;
  5151. OldOffset: asizeint;
  5152. ThisConst: TCGInt;
  5153. function RegDeallocated: Boolean;
  5154. begin
  5155. TransferUsedRegs(TmpUsedRegs);
  5156. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5157. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5158. end;
  5159. begin
  5160. Result:=false;
  5161. hp1 := nil;
  5162. { replace
  5163. subX const,%reg1
  5164. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5165. dealloc %reg1
  5166. by
  5167. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5168. }
  5169. if MatchOpType(taicpu(p),top_const,top_reg) then
  5170. begin
  5171. ActiveReg := taicpu(p).oper[1]^.reg;
  5172. { Ensures the entire register was updated }
  5173. if (taicpu(p).opsize >= S_L) and
  5174. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5175. MatchInstruction(hp1,A_LEA,[]) and
  5176. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5177. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5178. (
  5179. { Cover the case where the register in the reference is also the destination register }
  5180. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5181. (
  5182. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5183. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5184. RegDeallocated
  5185. )
  5186. ) then
  5187. begin
  5188. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5189. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5190. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5191. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5192. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5193. {$ifdef x86_64}
  5194. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5195. begin
  5196. { Overflow; abort }
  5197. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5198. end
  5199. else
  5200. {$endif x86_64}
  5201. begin
  5202. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5203. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5204. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5205. RemoveCurrentP(p, hp1)
  5206. else
  5207. RemoveCurrentP(p);
  5208. result:=true;
  5209. Exit;
  5210. end;
  5211. end;
  5212. if (
  5213. { Save calling GetNextInstructionUsingReg again }
  5214. Assigned(hp1) or
  5215. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5216. ) and
  5217. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5218. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5219. begin
  5220. if taicpu(hp1).oper[0]^.typ = top_const then
  5221. begin
  5222. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5223. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5224. Result := True;
  5225. { Handle any overflows }
  5226. case taicpu(p).opsize of
  5227. S_B:
  5228. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5229. S_W:
  5230. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5231. S_L:
  5232. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5233. {$ifdef x86_64}
  5234. S_Q:
  5235. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5236. { Overflow; abort }
  5237. Result := False
  5238. else
  5239. taicpu(p).oper[0]^.val := ThisConst;
  5240. {$endif x86_64}
  5241. else
  5242. InternalError(2021102610);
  5243. end;
  5244. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5245. if Result then
  5246. begin
  5247. if (taicpu(p).oper[0]^.val < 0) and
  5248. (
  5249. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5250. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5251. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5252. ) then
  5253. begin
  5254. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5255. taicpu(p).opcode := A_SUB;
  5256. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5257. end
  5258. else
  5259. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5260. RemoveInstruction(hp1);
  5261. end;
  5262. end
  5263. else
  5264. begin
  5265. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5266. TransferUsedRegs(TmpUsedRegs);
  5267. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5268. hp2 := p;
  5269. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5270. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5271. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5272. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5273. begin
  5274. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5275. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5276. Asml.Remove(p);
  5277. Asml.InsertAfter(p, hp1);
  5278. p := hp1;
  5279. Result := True;
  5280. Exit;
  5281. end;
  5282. end;
  5283. end;
  5284. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5285. { * change "sub/add const1, reg" or "dec reg" followed by
  5286. "sub const2, reg" to one "sub ..., reg" }
  5287. {$ifdef i386}
  5288. if (taicpu(p).oper[0]^.val = 2) and
  5289. (ActiveReg = NR_ESP) and
  5290. { Don't do the sub/push optimization if the sub }
  5291. { comes from setting up the stack frame (JM) }
  5292. (not(GetLastInstruction(p,hp1)) or
  5293. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5294. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5295. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5296. begin
  5297. hp1 := tai(p.next);
  5298. while Assigned(hp1) and
  5299. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5300. not RegReadByInstruction(NR_ESP,hp1) and
  5301. not RegModifiedByInstruction(NR_ESP,hp1) do
  5302. hp1 := tai(hp1.next);
  5303. if Assigned(hp1) and
  5304. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5305. begin
  5306. taicpu(hp1).changeopsize(S_L);
  5307. if taicpu(hp1).oper[0]^.typ=top_reg then
  5308. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5309. hp1 := tai(p.next);
  5310. RemoveCurrentp(p, hp1);
  5311. Result:=true;
  5312. exit;
  5313. end;
  5314. end;
  5315. {$endif i386}
  5316. if DoSubAddOpt(p) then
  5317. Result:=true;
  5318. end;
  5319. end;
  5320. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5321. var
  5322. TmpBool1,TmpBool2 : Boolean;
  5323. tmpref : treference;
  5324. hp1,hp2: tai;
  5325. mask: tcgint;
  5326. begin
  5327. Result:=false;
  5328. { All these optimisations work on "shl/sal const,%reg" }
  5329. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5330. Exit;
  5331. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5332. (taicpu(p).oper[0]^.val <= 3) then
  5333. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5334. begin
  5335. { should we check the next instruction? }
  5336. TmpBool1 := True;
  5337. { have we found an add/sub which could be
  5338. integrated in the lea? }
  5339. TmpBool2 := False;
  5340. reference_reset(tmpref,2,[]);
  5341. TmpRef.index := taicpu(p).oper[1]^.reg;
  5342. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5343. while TmpBool1 and
  5344. GetNextInstruction(p, hp1) and
  5345. (tai(hp1).typ = ait_instruction) and
  5346. ((((taicpu(hp1).opcode = A_ADD) or
  5347. (taicpu(hp1).opcode = A_SUB)) and
  5348. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5349. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5350. (((taicpu(hp1).opcode = A_INC) or
  5351. (taicpu(hp1).opcode = A_DEC)) and
  5352. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5353. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5354. ((taicpu(hp1).opcode = A_LEA) and
  5355. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5356. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5357. (not GetNextInstruction(hp1,hp2) or
  5358. not instrReadsFlags(hp2)) Do
  5359. begin
  5360. TmpBool1 := False;
  5361. if taicpu(hp1).opcode=A_LEA then
  5362. begin
  5363. if (TmpRef.base = NR_NO) and
  5364. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5365. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5366. { Segment register isn't a concern here }
  5367. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5368. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5369. begin
  5370. TmpBool1 := True;
  5371. TmpBool2 := True;
  5372. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5373. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5374. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5375. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5376. RemoveInstruction(hp1);
  5377. end
  5378. end
  5379. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5380. begin
  5381. TmpBool1 := True;
  5382. TmpBool2 := True;
  5383. case taicpu(hp1).opcode of
  5384. A_ADD:
  5385. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5386. A_SUB:
  5387. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5388. else
  5389. internalerror(2019050536);
  5390. end;
  5391. RemoveInstruction(hp1);
  5392. end
  5393. else
  5394. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5395. (((taicpu(hp1).opcode = A_ADD) and
  5396. (TmpRef.base = NR_NO)) or
  5397. (taicpu(hp1).opcode = A_INC) or
  5398. (taicpu(hp1).opcode = A_DEC)) then
  5399. begin
  5400. TmpBool1 := True;
  5401. TmpBool2 := True;
  5402. case taicpu(hp1).opcode of
  5403. A_ADD:
  5404. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5405. A_INC:
  5406. inc(TmpRef.offset);
  5407. A_DEC:
  5408. dec(TmpRef.offset);
  5409. else
  5410. internalerror(2019050535);
  5411. end;
  5412. RemoveInstruction(hp1);
  5413. end;
  5414. end;
  5415. if TmpBool2
  5416. {$ifndef x86_64}
  5417. or
  5418. ((current_settings.optimizecputype < cpu_Pentium2) and
  5419. (taicpu(p).oper[0]^.val <= 3) and
  5420. not(cs_opt_size in current_settings.optimizerswitches))
  5421. {$endif x86_64}
  5422. then
  5423. begin
  5424. if not(TmpBool2) and
  5425. (taicpu(p).oper[0]^.val=1) then
  5426. begin
  5427. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5428. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5429. end
  5430. else
  5431. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5432. taicpu(p).oper[1]^.reg);
  5433. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5434. InsertLLItem(p.previous, p.next, hp1);
  5435. p.free;
  5436. p := hp1;
  5437. end;
  5438. end
  5439. {$ifndef x86_64}
  5440. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5441. begin
  5442. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5443. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5444. (unlike shl, which is only Tairable in the U pipe) }
  5445. if taicpu(p).oper[0]^.val=1 then
  5446. begin
  5447. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5448. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5449. InsertLLItem(p.previous, p.next, hp1);
  5450. p.free;
  5451. p := hp1;
  5452. end
  5453. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5454. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5455. else if (taicpu(p).opsize = S_L) and
  5456. (taicpu(p).oper[0]^.val<= 3) then
  5457. begin
  5458. reference_reset(tmpref,2,[]);
  5459. TmpRef.index := taicpu(p).oper[1]^.reg;
  5460. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5461. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5462. InsertLLItem(p.previous, p.next, hp1);
  5463. p.free;
  5464. p := hp1;
  5465. end;
  5466. end
  5467. {$endif x86_64}
  5468. else if
  5469. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5470. (
  5471. (
  5472. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5473. SetAndTest(hp1, hp2)
  5474. {$ifdef x86_64}
  5475. ) or
  5476. (
  5477. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5478. GetNextInstruction(hp1, hp2) and
  5479. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5480. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5481. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5482. {$endif x86_64}
  5483. )
  5484. ) and
  5485. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5486. begin
  5487. { Change:
  5488. shl x, %reg1
  5489. mov -(1<<x), %reg2
  5490. and %reg2, %reg1
  5491. Or:
  5492. shl x, %reg1
  5493. and -(1<<x), %reg1
  5494. To just:
  5495. shl x, %reg1
  5496. Since the and operation only zeroes bits that are already zero from the shl operation
  5497. }
  5498. case taicpu(p).oper[0]^.val of
  5499. 8:
  5500. mask:=$FFFFFFFFFFFFFF00;
  5501. 16:
  5502. mask:=$FFFFFFFFFFFF0000;
  5503. 32:
  5504. mask:=$FFFFFFFF00000000;
  5505. 63:
  5506. { Constant pre-calculated to prevent overflow errors with Int64 }
  5507. mask:=$8000000000000000;
  5508. else
  5509. begin
  5510. if taicpu(p).oper[0]^.val >= 64 then
  5511. { Shouldn't happen realistically, since the register
  5512. is guaranteed to be set to zero at this point }
  5513. mask := 0
  5514. else
  5515. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5516. end;
  5517. end;
  5518. if taicpu(hp1).oper[0]^.val = mask then
  5519. begin
  5520. { Everything checks out, perform the optimisation, as long as
  5521. the FLAGS register isn't being used}
  5522. TransferUsedRegs(TmpUsedRegs);
  5523. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5524. {$ifdef x86_64}
  5525. if (hp1 <> hp2) then
  5526. begin
  5527. { "shl/mov/and" version }
  5528. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5529. { Don't do the optimisation if the FLAGS register is in use }
  5530. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5531. begin
  5532. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5533. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5534. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5535. begin
  5536. RemoveInstruction(hp1);
  5537. Result := True;
  5538. end;
  5539. { Only set Result to True if the 'mov' instruction was removed }
  5540. RemoveInstruction(hp2);
  5541. end;
  5542. end
  5543. else
  5544. {$endif x86_64}
  5545. begin
  5546. { "shl/and" version }
  5547. { Don't do the optimisation if the FLAGS register is in use }
  5548. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5549. begin
  5550. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5551. RemoveInstruction(hp1);
  5552. Result := True;
  5553. end;
  5554. end;
  5555. Exit;
  5556. end
  5557. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5558. begin
  5559. { Even if the mask doesn't allow for its removal, we might be
  5560. able to optimise the mask for the "shl/and" version, which
  5561. may permit other peephole optimisations }
  5562. {$ifdef DEBUG_AOPTCPU}
  5563. mask := taicpu(hp1).oper[0]^.val and mask;
  5564. if taicpu(hp1).oper[0]^.val <> mask then
  5565. begin
  5566. DebugMsg(
  5567. SPeepholeOptimization +
  5568. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5569. ' to $' + debug_tostr(mask) +
  5570. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5571. taicpu(hp1).oper[0]^.val := mask;
  5572. end;
  5573. {$else DEBUG_AOPTCPU}
  5574. { If debugging is off, just set the operand even if it's the same }
  5575. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5576. {$endif DEBUG_AOPTCPU}
  5577. end;
  5578. end;
  5579. {
  5580. change
  5581. shl/sal const,reg
  5582. <op> ...(...,reg,1),...
  5583. into
  5584. <op> ...(...,reg,1 shl const),...
  5585. if const in 1..3
  5586. }
  5587. if MatchOpType(taicpu(p), top_const, top_reg) and
  5588. (taicpu(p).oper[0]^.val in [1..3]) and
  5589. GetNextInstruction(p, hp1) and
  5590. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5591. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5592. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5593. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5594. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5595. begin
  5596. TransferUsedRegs(TmpUsedRegs);
  5597. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5598. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5599. begin
  5600. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5601. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5602. RemoveCurrentP(p);
  5603. Result:=true;
  5604. end;
  5605. end;
  5606. end;
  5607. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5608. var
  5609. CurrentRef: TReference;
  5610. FullReg: TRegister;
  5611. hp1, hp2: tai;
  5612. begin
  5613. Result := False;
  5614. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5615. Exit;
  5616. { We assume you've checked if the operand is actually a reference by
  5617. this point. If it isn't, you'll most likely get an access violation }
  5618. CurrentRef := first_mov.oper[1]^.ref^;
  5619. { Memory must be aligned }
  5620. if (CurrentRef.offset mod 4) <> 0 then
  5621. Exit;
  5622. Inc(CurrentRef.offset);
  5623. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5624. if MatchOperand(second_mov.oper[0]^, 0) and
  5625. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5626. GetNextInstruction(second_mov, hp1) and
  5627. (hp1.typ = ait_instruction) and
  5628. (taicpu(hp1).opcode = A_MOV) and
  5629. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5630. (taicpu(hp1).oper[0]^.val = 0) then
  5631. begin
  5632. Inc(CurrentRef.offset);
  5633. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5634. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5635. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5636. begin
  5637. case taicpu(hp1).opsize of
  5638. S_B:
  5639. if GetNextInstruction(hp1, hp2) and
  5640. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5641. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5642. (taicpu(hp2).oper[0]^.val = 0) then
  5643. begin
  5644. Inc(CurrentRef.offset);
  5645. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5646. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5647. (taicpu(hp2).opsize = S_B) then
  5648. begin
  5649. RemoveInstruction(hp1);
  5650. RemoveInstruction(hp2);
  5651. first_mov.opsize := S_L;
  5652. if first_mov.oper[0]^.typ = top_reg then
  5653. begin
  5654. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5655. { Reuse second_mov as a MOVZX instruction }
  5656. second_mov.opcode := A_MOVZX;
  5657. second_mov.opsize := S_BL;
  5658. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5659. second_mov.loadreg(1, FullReg);
  5660. first_mov.oper[0]^.reg := FullReg;
  5661. asml.Remove(second_mov);
  5662. asml.InsertBefore(second_mov, first_mov);
  5663. end
  5664. else
  5665. { It's a value }
  5666. begin
  5667. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5668. RemoveInstruction(second_mov);
  5669. end;
  5670. Result := True;
  5671. Exit;
  5672. end;
  5673. end;
  5674. S_W:
  5675. begin
  5676. RemoveInstruction(hp1);
  5677. first_mov.opsize := S_L;
  5678. if first_mov.oper[0]^.typ = top_reg then
  5679. begin
  5680. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5681. { Reuse second_mov as a MOVZX instruction }
  5682. second_mov.opcode := A_MOVZX;
  5683. second_mov.opsize := S_BL;
  5684. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5685. second_mov.loadreg(1, FullReg);
  5686. first_mov.oper[0]^.reg := FullReg;
  5687. asml.Remove(second_mov);
  5688. asml.InsertBefore(second_mov, first_mov);
  5689. end
  5690. else
  5691. { It's a value }
  5692. begin
  5693. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5694. RemoveInstruction(second_mov);
  5695. end;
  5696. Result := True;
  5697. Exit;
  5698. end;
  5699. else
  5700. ;
  5701. end;
  5702. end;
  5703. end;
  5704. end;
  5705. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5706. { returns true if a "continue" should be done after this optimization }
  5707. var
  5708. hp1, hp2: tai;
  5709. begin
  5710. Result := false;
  5711. if MatchOpType(taicpu(p),top_ref) and
  5712. GetNextInstruction(p, hp1) and
  5713. (hp1.typ = ait_instruction) and
  5714. (((taicpu(hp1).opcode = A_FLD) and
  5715. (taicpu(p).opcode = A_FSTP)) or
  5716. ((taicpu(p).opcode = A_FISTP) and
  5717. (taicpu(hp1).opcode = A_FILD))) and
  5718. MatchOpType(taicpu(hp1),top_ref) and
  5719. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5720. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5721. begin
  5722. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5723. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5724. GetNextInstruction(hp1, hp2) and
  5725. (hp2.typ = ait_instruction) and
  5726. IsExitCode(hp2) and
  5727. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5728. not(assigned(current_procinfo.procdef.funcretsym) and
  5729. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5730. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5731. begin
  5732. RemoveInstruction(hp1);
  5733. RemoveCurrentP(p, hp2);
  5734. RemoveLastDeallocForFuncRes(p);
  5735. Result := true;
  5736. end
  5737. else
  5738. { we can do this only in fast math mode as fstp is rounding ...
  5739. ... still disabled as it breaks the compiler and/or rtl }
  5740. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5741. { ... or if another fstp equal to the first one follows }
  5742. (GetNextInstruction(hp1,hp2) and
  5743. (hp2.typ = ait_instruction) and
  5744. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5745. (taicpu(p).opsize=taicpu(hp2).opsize))
  5746. ) and
  5747. { fst can't store an extended/comp value }
  5748. (taicpu(p).opsize <> S_FX) and
  5749. (taicpu(p).opsize <> S_IQ) then
  5750. begin
  5751. if (taicpu(p).opcode = A_FSTP) then
  5752. taicpu(p).opcode := A_FST
  5753. else
  5754. taicpu(p).opcode := A_FIST;
  5755. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5756. RemoveInstruction(hp1);
  5757. end;
  5758. end;
  5759. end;
  5760. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5761. var
  5762. hp1, hp2: tai;
  5763. begin
  5764. result:=false;
  5765. if MatchOpType(taicpu(p),top_reg) and
  5766. GetNextInstruction(p, hp1) and
  5767. (hp1.typ = Ait_Instruction) and
  5768. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5769. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5770. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5771. { change to
  5772. fld reg fxxx reg,st
  5773. fxxxp st, st1 (hp1)
  5774. Remark: non commutative operations must be reversed!
  5775. }
  5776. begin
  5777. case taicpu(hp1).opcode Of
  5778. A_FMULP,A_FADDP,
  5779. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5780. begin
  5781. case taicpu(hp1).opcode Of
  5782. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5783. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5784. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5785. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5786. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5787. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5788. else
  5789. internalerror(2019050534);
  5790. end;
  5791. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5792. taicpu(hp1).oper[1]^.reg := NR_ST;
  5793. RemoveCurrentP(p, hp1);
  5794. Result:=true;
  5795. exit;
  5796. end;
  5797. else
  5798. ;
  5799. end;
  5800. end
  5801. else
  5802. if MatchOpType(taicpu(p),top_ref) and
  5803. GetNextInstruction(p, hp2) and
  5804. (hp2.typ = Ait_Instruction) and
  5805. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5806. (taicpu(p).opsize in [S_FS, S_FL]) and
  5807. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5808. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5809. if GetLastInstruction(p, hp1) and
  5810. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5811. MatchOpType(taicpu(hp1),top_ref) and
  5812. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5813. if ((taicpu(hp2).opcode = A_FMULP) or
  5814. (taicpu(hp2).opcode = A_FADDP)) then
  5815. { change to
  5816. fld/fst mem1 (hp1) fld/fst mem1
  5817. fld mem1 (p) fadd/
  5818. faddp/ fmul st, st
  5819. fmulp st, st1 (hp2) }
  5820. begin
  5821. RemoveCurrentP(p, hp1);
  5822. if (taicpu(hp2).opcode = A_FADDP) then
  5823. taicpu(hp2).opcode := A_FADD
  5824. else
  5825. taicpu(hp2).opcode := A_FMUL;
  5826. taicpu(hp2).oper[1]^.reg := NR_ST;
  5827. end
  5828. else
  5829. { change to
  5830. fld/fst mem1 (hp1) fld/fst mem1
  5831. fld mem1 (p) fld st}
  5832. begin
  5833. taicpu(p).changeopsize(S_FL);
  5834. taicpu(p).loadreg(0,NR_ST);
  5835. end
  5836. else
  5837. begin
  5838. case taicpu(hp2).opcode Of
  5839. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5840. { change to
  5841. fld/fst mem1 (hp1) fld/fst mem1
  5842. fld mem2 (p) fxxx mem2
  5843. fxxxp st, st1 (hp2) }
  5844. begin
  5845. case taicpu(hp2).opcode Of
  5846. A_FADDP: taicpu(p).opcode := A_FADD;
  5847. A_FMULP: taicpu(p).opcode := A_FMUL;
  5848. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5849. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5850. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5851. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5852. else
  5853. internalerror(2019050533);
  5854. end;
  5855. RemoveInstruction(hp2);
  5856. end
  5857. else
  5858. ;
  5859. end
  5860. end
  5861. end;
  5862. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5863. begin
  5864. Result := condition_in(cond1, cond2) or
  5865. { Not strictly subsets due to the actual flags checked, but because we're
  5866. comparing integers, E is a subset of AE and GE and their aliases }
  5867. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5868. end;
  5869. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5870. var
  5871. v: TCGInt;
  5872. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5873. FirstMatch: Boolean;
  5874. NewReg: TRegister;
  5875. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5876. begin
  5877. Result:=false;
  5878. { All these optimisations need a next instruction }
  5879. if not GetNextInstruction(p, hp1) then
  5880. Exit;
  5881. { Search for:
  5882. cmp ###,###
  5883. j(c1) @lbl1
  5884. ...
  5885. @lbl:
  5886. cmp ###.### (same comparison as above)
  5887. j(c2) @lbl2
  5888. If c1 is a subset of c2, change to:
  5889. cmp ###,###
  5890. j(c2) @lbl2
  5891. (@lbl1 may become a dead label as a result)
  5892. }
  5893. { Also handle cases where there are multiple jumps in a row }
  5894. p_jump := hp1;
  5895. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5896. begin
  5897. if IsJumpToLabel(taicpu(p_jump)) then
  5898. begin
  5899. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5900. p_label := nil;
  5901. if Assigned(JumpLabel) then
  5902. p_label := getlabelwithsym(JumpLabel);
  5903. if Assigned(p_label) and
  5904. GetNextInstruction(p_label, p_dist) and
  5905. MatchInstruction(p_dist, A_CMP, []) and
  5906. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5907. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5908. GetNextInstruction(p_dist, hp1_dist) and
  5909. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5910. begin
  5911. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5912. if JumpLabel = JumpLabel_dist then
  5913. { This is an infinite loop }
  5914. Exit;
  5915. { Best optimisation when the first condition is a subset (or equal) of the second }
  5916. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5917. begin
  5918. { Any registers used here will already be allocated }
  5919. if Assigned(JumpLabel_dist) then
  5920. JumpLabel_dist.IncRefs;
  5921. if Assigned(JumpLabel) then
  5922. JumpLabel.DecRefs;
  5923. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5924. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5925. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5926. Result := True;
  5927. { Don't exit yet. Since p and p_jump haven't actually been
  5928. removed, we can check for more on this iteration }
  5929. end
  5930. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5931. GetNextInstruction(hp1_dist, hp1_label) and
  5932. SkipAligns(hp1_label, hp1_label) and
  5933. (hp1_label.typ = ait_label) then
  5934. begin
  5935. JumpLabel_far := tai_label(hp1_label).labsym;
  5936. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5937. { This is an infinite loop }
  5938. Exit;
  5939. if Assigned(JumpLabel_far) then
  5940. begin
  5941. { In this situation, if the first jump branches, the second one will never,
  5942. branch so change the destination label to after the second jump }
  5943. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5944. if Assigned(JumpLabel) then
  5945. JumpLabel.DecRefs;
  5946. JumpLabel_far.IncRefs;
  5947. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5948. Result := True;
  5949. { Don't exit yet. Since p and p_jump haven't actually been
  5950. removed, we can check for more on this iteration }
  5951. Continue;
  5952. end;
  5953. end;
  5954. end;
  5955. end;
  5956. { Search for:
  5957. cmp ###,###
  5958. j(c1) @lbl1
  5959. cmp ###,### (same as first)
  5960. Remove second cmp
  5961. }
  5962. if GetNextInstruction(p_jump, hp2) and
  5963. (
  5964. (
  5965. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5966. (
  5967. (
  5968. MatchOpType(taicpu(p), top_const, top_reg) and
  5969. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5970. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5971. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5972. ) or (
  5973. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5974. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5975. )
  5976. )
  5977. ) or (
  5978. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5979. MatchOperand(taicpu(p).oper[0]^, 0) and
  5980. (taicpu(p).oper[1]^.typ = top_reg) and
  5981. MatchInstruction(hp2, A_TEST, []) and
  5982. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5983. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5984. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5985. )
  5986. ) then
  5987. begin
  5988. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5989. RemoveInstruction(hp2);
  5990. Result := True;
  5991. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5992. end;
  5993. GetNextInstruction(p_jump, p_jump);
  5994. end;
  5995. {
  5996. Try to optimise the following:
  5997. cmp $x,### ($x and $y can be registers or constants)
  5998. je @lbl1 (only reference)
  5999. cmp $y,### (### are identical)
  6000. @Lbl:
  6001. sete %reg1
  6002. Change to:
  6003. cmp $x,###
  6004. sete %reg2 (allocate new %reg2)
  6005. cmp $y,###
  6006. sete %reg1
  6007. orb %reg2,%reg1
  6008. (dealloc %reg2)
  6009. This adds an instruction (so don't perform under -Os), but it removes
  6010. a conditional branch.
  6011. }
  6012. if not (cs_opt_size in current_settings.optimizerswitches) and
  6013. (
  6014. (hp1 = p_jump) or
  6015. GetNextInstruction(p, hp1)
  6016. ) and
  6017. MatchInstruction(hp1, A_Jcc, []) and
  6018. IsJumpToLabel(taicpu(hp1)) and
  6019. (taicpu(hp1).condition in [C_E, C_Z]) and
  6020. GetNextInstruction(hp1, hp2) and
  6021. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6022. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6023. { The first operand of CMP instructions can only be a register or
  6024. immediate anyway, so no need to check }
  6025. GetNextInstruction(hp2, p_label) and
  6026. (p_label.typ = ait_label) and
  6027. (tai_label(p_label).labsym.getrefs = 1) and
  6028. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6029. GetNextInstruction(p_label, p_dist) and
  6030. MatchInstruction(p_dist, A_SETcc, []) and
  6031. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6032. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6033. begin
  6034. TransferUsedRegs(TmpUsedRegs);
  6035. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6036. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6037. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6038. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6039. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6040. { Get the instruction after the SETcc instruction so we can
  6041. allocate a new register over the entire range }
  6042. GetNextInstruction(p_dist, hp1_dist) then
  6043. begin
  6044. { Register can appear in p if it's not used afterwards, so only
  6045. allocate between hp1 and hp1_dist }
  6046. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6047. if NewReg <> NR_NO then
  6048. begin
  6049. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6050. { Change the jump instruction into a SETcc instruction }
  6051. taicpu(hp1).opcode := A_SETcc;
  6052. taicpu(hp1).opsize := S_B;
  6053. taicpu(hp1).loadreg(0, NewReg);
  6054. { This is now a dead label }
  6055. tai_label(p_label).labsym.decrefs;
  6056. { Prefer adding before the next instruction so the FLAGS
  6057. register is deallicated first }
  6058. AsmL.InsertBefore(
  6059. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6060. hp1_dist
  6061. );
  6062. Result := True;
  6063. { Don't exit yet, as p wasn't changed and hp1, while
  6064. modified, is still intact and might be optimised by the
  6065. SETcc optimisation below }
  6066. end;
  6067. end;
  6068. end;
  6069. if taicpu(p).oper[0]^.typ = top_const then
  6070. begin
  6071. if (taicpu(p).oper[0]^.val = 0) and
  6072. (taicpu(p).oper[1]^.typ = top_reg) and
  6073. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6074. begin
  6075. hp2 := p;
  6076. FirstMatch := True;
  6077. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6078. anything meaningful once it's converted to "test %reg,%reg";
  6079. additionally, some jumps will always (or never) branch, so
  6080. evaluate every jump immediately following the
  6081. comparison, optimising the conditions if possible.
  6082. Similarly with SETcc... those that are always set to 0 or 1
  6083. are changed to MOV instructions }
  6084. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6085. (
  6086. GetNextInstruction(hp2, hp1) and
  6087. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6088. ) do
  6089. begin
  6090. FirstMatch := False;
  6091. case taicpu(hp1).condition of
  6092. C_B, C_C, C_NAE, C_O:
  6093. { For B/NAE:
  6094. Will never branch since an unsigned integer can never be below zero
  6095. For C/O:
  6096. Result cannot overflow because 0 is being subtracted
  6097. }
  6098. begin
  6099. if taicpu(hp1).opcode = A_Jcc then
  6100. begin
  6101. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6102. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6103. RemoveInstruction(hp1);
  6104. { Since hp1 was deleted, hp2 must not be updated }
  6105. Continue;
  6106. end
  6107. else
  6108. begin
  6109. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6110. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6111. taicpu(hp1).opcode := A_MOV;
  6112. taicpu(hp1).ops := 2;
  6113. taicpu(hp1).condition := C_None;
  6114. taicpu(hp1).opsize := S_B;
  6115. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6116. taicpu(hp1).loadconst(0, 0);
  6117. end;
  6118. end;
  6119. C_BE, C_NA:
  6120. begin
  6121. { Will only branch if equal to zero }
  6122. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6123. taicpu(hp1).condition := C_E;
  6124. end;
  6125. C_A, C_NBE:
  6126. begin
  6127. { Will only branch if not equal to zero }
  6128. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6129. taicpu(hp1).condition := C_NE;
  6130. end;
  6131. C_AE, C_NB, C_NC, C_NO:
  6132. begin
  6133. { Will always branch }
  6134. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6135. if taicpu(hp1).opcode = A_Jcc then
  6136. begin
  6137. MakeUnconditional(taicpu(hp1));
  6138. { Any jumps/set that follow will now be dead code }
  6139. RemoveDeadCodeAfterJump(taicpu(hp1));
  6140. Break;
  6141. end
  6142. else
  6143. begin
  6144. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6145. taicpu(hp1).opcode := A_MOV;
  6146. taicpu(hp1).ops := 2;
  6147. taicpu(hp1).condition := C_None;
  6148. taicpu(hp1).opsize := S_B;
  6149. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6150. taicpu(hp1).loadconst(0, 1);
  6151. end;
  6152. end;
  6153. C_None:
  6154. InternalError(2020012201);
  6155. C_P, C_PE, C_NP, C_PO:
  6156. { We can't handle parity checks and they should never be generated
  6157. after a general-purpose CMP (it's used in some floating-point
  6158. comparisons that don't use CMP) }
  6159. InternalError(2020012202);
  6160. else
  6161. { Zero/Equality, Sign, their complements and all of the
  6162. signed comparisons do not need to be converted };
  6163. end;
  6164. hp2 := hp1;
  6165. end;
  6166. { Convert the instruction to a TEST }
  6167. taicpu(p).opcode := A_TEST;
  6168. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6169. Result := True;
  6170. Exit;
  6171. end
  6172. else if (taicpu(p).oper[0]^.val = 1) and
  6173. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6174. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6175. begin
  6176. { Convert; To:
  6177. cmp $1,r/m cmp $0,r/m
  6178. jl @lbl jle @lbl
  6179. }
  6180. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6181. taicpu(p).oper[0]^.val := 0;
  6182. taicpu(hp1).condition := C_LE;
  6183. { If the instruction is now "cmp $0,%reg", convert it to a
  6184. TEST (and effectively do the work of the "cmp $0,%reg" in
  6185. the block above)
  6186. If it's a reference, we can get away with not setting
  6187. Result to True because he haven't evaluated the jump
  6188. in this pass yet.
  6189. }
  6190. if (taicpu(p).oper[1]^.typ = top_reg) then
  6191. begin
  6192. taicpu(p).opcode := A_TEST;
  6193. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6194. Result := True;
  6195. end;
  6196. Exit;
  6197. end
  6198. else if (taicpu(p).oper[1]^.typ = top_reg)
  6199. {$ifdef x86_64}
  6200. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6201. {$endif x86_64}
  6202. then
  6203. begin
  6204. { cmp register,$8000 neg register
  6205. je target --> jo target
  6206. .... only if register is deallocated before jump.}
  6207. case Taicpu(p).opsize of
  6208. S_B: v:=$80;
  6209. S_W: v:=$8000;
  6210. S_L: v:=qword($80000000);
  6211. else
  6212. internalerror(2013112905);
  6213. end;
  6214. if (taicpu(p).oper[0]^.val=v) and
  6215. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6216. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6217. begin
  6218. TransferUsedRegs(TmpUsedRegs);
  6219. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6220. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6221. begin
  6222. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6223. Taicpu(p).opcode:=A_NEG;
  6224. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6225. Taicpu(p).clearop(1);
  6226. Taicpu(p).ops:=1;
  6227. if Taicpu(hp1).condition=C_E then
  6228. Taicpu(hp1).condition:=C_O
  6229. else
  6230. Taicpu(hp1).condition:=C_NO;
  6231. Result:=true;
  6232. exit;
  6233. end;
  6234. end;
  6235. end;
  6236. end;
  6237. if TrySwapMovCmp(p, hp1) then
  6238. begin
  6239. Result := True;
  6240. Exit;
  6241. end;
  6242. end;
  6243. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6244. var
  6245. hp1: tai;
  6246. begin
  6247. {
  6248. remove the second (v)pxor from
  6249. pxor reg,reg
  6250. ...
  6251. pxor reg,reg
  6252. }
  6253. Result:=false;
  6254. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6255. MatchOpType(taicpu(p),top_reg,top_reg) and
  6256. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6257. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6258. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6259. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6260. begin
  6261. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6262. RemoveInstruction(hp1);
  6263. Result:=true;
  6264. Exit;
  6265. end
  6266. {
  6267. replace
  6268. pxor reg1,reg1
  6269. movapd/s reg1,reg2
  6270. dealloc reg1
  6271. by
  6272. pxor reg2,reg2
  6273. }
  6274. else if GetNextInstruction(p,hp1) and
  6275. { we mix single and double opperations here because we assume that the compiler
  6276. generates vmovapd only after double operations and vmovaps only after single operations }
  6277. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6278. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6279. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6280. (taicpu(p).oper[0]^.typ=top_reg) then
  6281. begin
  6282. TransferUsedRegs(TmpUsedRegs);
  6283. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6284. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6285. begin
  6286. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6287. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6288. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6289. RemoveInstruction(hp1);
  6290. result:=true;
  6291. end;
  6292. end;
  6293. end;
  6294. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6295. var
  6296. hp1: tai;
  6297. begin
  6298. {
  6299. remove the second (v)pxor from
  6300. (v)pxor reg,reg
  6301. ...
  6302. (v)pxor reg,reg
  6303. }
  6304. Result:=false;
  6305. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6306. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6307. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6308. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6309. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6310. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6311. begin
  6312. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6313. RemoveInstruction(hp1);
  6314. Result:=true;
  6315. Exit;
  6316. end
  6317. else
  6318. Result:=OptPass1VOP(p);
  6319. end;
  6320. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6321. var
  6322. hp1 : tai;
  6323. begin
  6324. result:=false;
  6325. { replace
  6326. IMul const,%mreg1,%mreg2
  6327. Mov %reg2,%mreg3
  6328. dealloc %mreg3
  6329. by
  6330. Imul const,%mreg1,%mreg23
  6331. }
  6332. if (taicpu(p).ops=3) and
  6333. GetNextInstruction(p,hp1) and
  6334. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6335. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6336. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6337. begin
  6338. TransferUsedRegs(TmpUsedRegs);
  6339. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6340. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6341. begin
  6342. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6343. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6344. RemoveInstruction(hp1);
  6345. result:=true;
  6346. end;
  6347. end;
  6348. end;
  6349. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6350. var
  6351. hp1 : tai;
  6352. begin
  6353. result:=false;
  6354. { replace
  6355. IMul %reg0,%reg1,%reg2
  6356. Mov %reg2,%reg3
  6357. dealloc %reg2
  6358. by
  6359. Imul %reg0,%reg1,%reg3
  6360. }
  6361. if GetNextInstruction(p,hp1) and
  6362. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6363. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6364. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6365. begin
  6366. TransferUsedRegs(TmpUsedRegs);
  6367. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6368. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6369. begin
  6370. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6371. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6372. RemoveInstruction(hp1);
  6373. result:=true;
  6374. end;
  6375. end;
  6376. end;
  6377. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6378. var
  6379. hp1: tai;
  6380. begin
  6381. Result:=false;
  6382. { get rid of
  6383. (v)cvtss2sd reg0,<reg1,>reg2
  6384. (v)cvtss2sd reg2,<reg2,>reg0
  6385. }
  6386. if GetNextInstruction(p,hp1) and
  6387. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6388. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6389. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6390. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6391. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6392. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6393. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6394. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6395. )
  6396. ) then
  6397. begin
  6398. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6399. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6400. begin
  6401. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6402. RemoveCurrentP(p);
  6403. RemoveInstruction(hp1);
  6404. end
  6405. else
  6406. begin
  6407. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6408. if taicpu(hp1).opcode=A_CVTSD2SS then
  6409. begin
  6410. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6411. taicpu(p).opcode:=A_MOVAPS;
  6412. end
  6413. else
  6414. begin
  6415. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6416. taicpu(p).opcode:=A_VMOVAPS;
  6417. end;
  6418. taicpu(p).ops:=2;
  6419. RemoveInstruction(hp1);
  6420. end;
  6421. Result:=true;
  6422. Exit;
  6423. end;
  6424. end;
  6425. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6426. var
  6427. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6428. ThisReg: TRegister;
  6429. begin
  6430. Result := False;
  6431. if not GetNextInstruction(p,hp1) then
  6432. Exit;
  6433. {
  6434. convert
  6435. j<c> .L1
  6436. mov 1,reg
  6437. jmp .L2
  6438. .L1
  6439. mov 0,reg
  6440. .L2
  6441. into
  6442. mov 0,reg
  6443. set<not(c)> reg
  6444. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6445. would destroy the flag contents
  6446. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6447. executed at the same time as a previous comparison.
  6448. set<not(c)> reg
  6449. movzx reg, reg
  6450. }
  6451. if MatchInstruction(hp1,A_MOV,[]) and
  6452. (taicpu(hp1).oper[0]^.typ = top_const) and
  6453. (
  6454. (
  6455. (taicpu(hp1).oper[1]^.typ = top_reg)
  6456. {$ifdef i386}
  6457. { Under i386, ESI, EDI, EBP and ESP
  6458. don't have an 8-bit representation }
  6459. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6460. {$endif i386}
  6461. ) or (
  6462. {$ifdef i386}
  6463. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6464. {$endif i386}
  6465. (taicpu(hp1).opsize = S_B)
  6466. )
  6467. ) and
  6468. GetNextInstruction(hp1,hp2) and
  6469. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6470. GetNextInstruction(hp2,hp3) and
  6471. SkipAligns(hp3, hp3) and
  6472. (hp3.typ=ait_label) and
  6473. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6474. GetNextInstruction(hp3,hp4) and
  6475. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6476. (taicpu(hp4).oper[0]^.typ = top_const) and
  6477. (
  6478. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6479. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6480. ) and
  6481. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6482. GetNextInstruction(hp4,hp5) and
  6483. SkipAligns(hp5, hp5) and
  6484. (hp5.typ=ait_label) and
  6485. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6486. begin
  6487. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6488. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6489. tai_label(hp3).labsym.DecRefs;
  6490. { If this isn't the only reference to the middle label, we can
  6491. still make a saving - only that the first jump and everything
  6492. that follows will remain. }
  6493. if (tai_label(hp3).labsym.getrefs = 0) then
  6494. begin
  6495. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6496. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6497. else
  6498. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6499. { remove jump, first label and second MOV (also catching any aligns) }
  6500. repeat
  6501. if not GetNextInstruction(hp2, hp3) then
  6502. InternalError(2021040810);
  6503. RemoveInstruction(hp2);
  6504. hp2 := hp3;
  6505. until hp2 = hp5;
  6506. { Don't decrement reference count before the removal loop
  6507. above, otherwise GetNextInstruction won't stop on the
  6508. the label }
  6509. tai_label(hp5).labsym.DecRefs;
  6510. end
  6511. else
  6512. begin
  6513. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6514. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6515. else
  6516. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6517. end;
  6518. taicpu(p).opcode:=A_SETcc;
  6519. taicpu(p).opsize:=S_B;
  6520. taicpu(p).is_jmp:=False;
  6521. if taicpu(hp1).opsize=S_B then
  6522. begin
  6523. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6524. if taicpu(hp1).oper[1]^.typ = top_reg then
  6525. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6526. RemoveInstruction(hp1);
  6527. end
  6528. else
  6529. begin
  6530. { Will be a register because the size can't be S_B otherwise }
  6531. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6532. taicpu(p).loadreg(0, ThisReg);
  6533. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6534. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6535. begin
  6536. case taicpu(hp1).opsize of
  6537. S_W:
  6538. taicpu(hp1).opsize := S_BW;
  6539. S_L:
  6540. taicpu(hp1).opsize := S_BL;
  6541. {$ifdef x86_64}
  6542. S_Q:
  6543. begin
  6544. taicpu(hp1).opsize := S_BL;
  6545. { Change the destination register to 32-bit }
  6546. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6547. end;
  6548. {$endif x86_64}
  6549. else
  6550. InternalError(2021040820);
  6551. end;
  6552. taicpu(hp1).opcode := A_MOVZX;
  6553. taicpu(hp1).loadreg(0, ThisReg);
  6554. end
  6555. else
  6556. begin
  6557. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6558. { hp1 is already a MOV instruction with the correct register }
  6559. taicpu(hp1).loadconst(0, 0);
  6560. { Inserting it right before p will guarantee that the flags are also tracked }
  6561. asml.Remove(hp1);
  6562. asml.InsertBefore(hp1, p);
  6563. end;
  6564. end;
  6565. Result:=true;
  6566. exit;
  6567. end
  6568. else if (hp1.typ = ait_label) then
  6569. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6570. end;
  6571. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6572. var
  6573. hp1, hp2, hp3: tai;
  6574. SourceRef, TargetRef: TReference;
  6575. CurrentReg: TRegister;
  6576. begin
  6577. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6578. if not UseAVX then
  6579. InternalError(2021100501);
  6580. Result := False;
  6581. { Look for the following to simplify:
  6582. vmovdqa/u x(mem1), %xmmreg
  6583. vmovdqa/u %xmmreg, y(mem2)
  6584. vmovdqa/u x+16(mem1), %xmmreg
  6585. vmovdqa/u %xmmreg, y+16(mem2)
  6586. Change to:
  6587. vmovdqa/u x(mem1), %ymmreg
  6588. vmovdqa/u %ymmreg, y(mem2)
  6589. vpxor %ymmreg, %ymmreg, %ymmreg
  6590. ( The VPXOR instruction is to zero the upper half, thus removing the
  6591. need to call the potentially expensive VZEROUPPER instruction. Other
  6592. peephole optimisations can remove VPXOR if it's unnecessary )
  6593. }
  6594. TransferUsedRegs(TmpUsedRegs);
  6595. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6596. { NOTE: In the optimisations below, if the references dictate that an
  6597. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6598. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6599. if (taicpu(p).opsize = S_XMM) and
  6600. MatchOpType(taicpu(p), top_ref, top_reg) and
  6601. GetNextInstruction(p, hp1) and
  6602. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6603. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6604. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6605. begin
  6606. SourceRef := taicpu(p).oper[0]^.ref^;
  6607. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6608. if GetNextInstruction(hp1, hp2) and
  6609. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6610. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6611. begin
  6612. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6613. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6614. Inc(SourceRef.offset, 16);
  6615. { Reuse the register in the first block move }
  6616. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6617. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6618. begin
  6619. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6620. Inc(TargetRef.offset, 16);
  6621. if GetNextInstruction(hp2, hp3) and
  6622. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6623. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6624. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6625. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6626. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6627. begin
  6628. { Update the register tracking to the new size }
  6629. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6630. { Remember that the offsets are 16 ahead }
  6631. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6632. if not (
  6633. ((SourceRef.offset mod 32) = 16) and
  6634. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6635. ) then
  6636. taicpu(p).opcode := A_VMOVDQU;
  6637. taicpu(p).opsize := S_YMM;
  6638. taicpu(p).oper[1]^.reg := CurrentReg;
  6639. if not (
  6640. ((TargetRef.offset mod 32) = 16) and
  6641. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6642. ) then
  6643. taicpu(hp1).opcode := A_VMOVDQU;
  6644. taicpu(hp1).opsize := S_YMM;
  6645. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6646. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6647. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6648. if (pi_uses_ymm in current_procinfo.flags) then
  6649. RemoveInstruction(hp2)
  6650. else
  6651. begin
  6652. taicpu(hp2).opcode := A_VPXOR;
  6653. taicpu(hp2).opsize := S_YMM;
  6654. taicpu(hp2).loadreg(0, CurrentReg);
  6655. taicpu(hp2).loadreg(1, CurrentReg);
  6656. taicpu(hp2).loadreg(2, CurrentReg);
  6657. taicpu(hp2).ops := 3;
  6658. end;
  6659. RemoveInstruction(hp3);
  6660. Result := True;
  6661. Exit;
  6662. end;
  6663. end
  6664. else
  6665. begin
  6666. { See if the next references are 16 less rather than 16 greater }
  6667. Dec(SourceRef.offset, 32); { -16 the other way }
  6668. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6669. begin
  6670. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6671. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6672. if GetNextInstruction(hp2, hp3) and
  6673. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6674. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6675. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6676. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6677. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6678. begin
  6679. { Update the register tracking to the new size }
  6680. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6681. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6682. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6683. if not(
  6684. ((SourceRef.offset mod 32) = 0) and
  6685. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6686. ) then
  6687. taicpu(hp2).opcode := A_VMOVDQU;
  6688. taicpu(hp2).opsize := S_YMM;
  6689. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6690. if not (
  6691. ((TargetRef.offset mod 32) = 0) and
  6692. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6693. ) then
  6694. taicpu(hp3).opcode := A_VMOVDQU;
  6695. taicpu(hp3).opsize := S_YMM;
  6696. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6697. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6698. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6699. if (pi_uses_ymm in current_procinfo.flags) then
  6700. RemoveInstruction(hp1)
  6701. else
  6702. begin
  6703. taicpu(hp1).opcode := A_VPXOR;
  6704. taicpu(hp1).opsize := S_YMM;
  6705. taicpu(hp1).loadreg(0, CurrentReg);
  6706. taicpu(hp1).loadreg(1, CurrentReg);
  6707. taicpu(hp1).loadreg(2, CurrentReg);
  6708. taicpu(hp1).ops := 3;
  6709. Asml.Remove(hp1);
  6710. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6711. end;
  6712. RemoveCurrentP(p, hp2);
  6713. Result := True;
  6714. Exit;
  6715. end;
  6716. end;
  6717. end;
  6718. end;
  6719. end;
  6720. end;
  6721. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6722. var
  6723. hp2, hp3, first_assignment: tai;
  6724. IncCount, OperIdx: Integer;
  6725. OrigLabel: TAsmLabel;
  6726. begin
  6727. Count := 0;
  6728. Result := False;
  6729. first_assignment := nil;
  6730. if (LoopCount >= 20) then
  6731. begin
  6732. { Guard against infinite loops }
  6733. Exit;
  6734. end;
  6735. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6736. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6737. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6738. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6739. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6740. Exit;
  6741. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6742. {
  6743. change
  6744. jmp .L1
  6745. ...
  6746. .L1:
  6747. mov ##, ## ( multiple movs possible )
  6748. jmp/ret
  6749. into
  6750. mov ##, ##
  6751. jmp/ret
  6752. }
  6753. if not Assigned(hp1) then
  6754. begin
  6755. hp1 := GetLabelWithSym(OrigLabel);
  6756. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6757. Exit;
  6758. end;
  6759. hp2 := hp1;
  6760. while Assigned(hp2) do
  6761. begin
  6762. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6763. SkipLabels(hp2,hp2);
  6764. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6765. Break;
  6766. case taicpu(hp2).opcode of
  6767. A_MOVSS:
  6768. begin
  6769. if taicpu(hp2).ops = 0 then
  6770. { Wrong MOVSS }
  6771. Break;
  6772. Inc(Count);
  6773. if Count >= 5 then
  6774. { Too many to be worthwhile }
  6775. Break;
  6776. GetNextInstruction(hp2, hp2);
  6777. Continue;
  6778. end;
  6779. A_MOV,
  6780. A_MOVD,
  6781. A_MOVQ,
  6782. A_MOVSX,
  6783. {$ifdef x86_64}
  6784. A_MOVSXD,
  6785. {$endif x86_64}
  6786. A_MOVZX,
  6787. A_MOVAPS,
  6788. A_MOVUPS,
  6789. A_MOVSD,
  6790. A_MOVAPD,
  6791. A_MOVUPD,
  6792. A_MOVDQA,
  6793. A_MOVDQU,
  6794. A_VMOVSS,
  6795. A_VMOVAPS,
  6796. A_VMOVUPS,
  6797. A_VMOVSD,
  6798. A_VMOVAPD,
  6799. A_VMOVUPD,
  6800. A_VMOVDQA,
  6801. A_VMOVDQU:
  6802. begin
  6803. Inc(Count);
  6804. if Count >= 5 then
  6805. { Too many to be worthwhile }
  6806. Break;
  6807. GetNextInstruction(hp2, hp2);
  6808. Continue;
  6809. end;
  6810. A_JMP:
  6811. begin
  6812. { Guard against infinite loops }
  6813. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6814. Exit;
  6815. { Analyse this jump first in case it also duplicates assignments }
  6816. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6817. begin
  6818. { Something did change! }
  6819. Result := True;
  6820. Inc(Count, IncCount);
  6821. if Count >= 5 then
  6822. begin
  6823. { Too many to be worthwhile }
  6824. Exit;
  6825. end;
  6826. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6827. Break;
  6828. end;
  6829. Result := True;
  6830. Break;
  6831. end;
  6832. A_RET:
  6833. begin
  6834. Result := True;
  6835. Break;
  6836. end;
  6837. else
  6838. Break;
  6839. end;
  6840. end;
  6841. if Result then
  6842. begin
  6843. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6844. if Count = 0 then
  6845. begin
  6846. Result := False;
  6847. Exit;
  6848. end;
  6849. hp3 := p;
  6850. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6851. while True do
  6852. begin
  6853. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6854. SkipLabels(hp1,hp1);
  6855. if (hp1.typ <> ait_instruction) then
  6856. InternalError(2021040720);
  6857. case taicpu(hp1).opcode of
  6858. A_JMP:
  6859. begin
  6860. { Change the original jump to the new destination }
  6861. OrigLabel.decrefs;
  6862. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6863. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6864. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6865. if not Assigned(first_assignment) then
  6866. InternalError(2021040810)
  6867. else
  6868. p := first_assignment;
  6869. Exit;
  6870. end;
  6871. A_RET:
  6872. begin
  6873. { Now change the jump into a RET instruction }
  6874. ConvertJumpToRET(p, hp1);
  6875. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6876. if not Assigned(first_assignment) then
  6877. InternalError(2021040811)
  6878. else
  6879. p := first_assignment;
  6880. Exit;
  6881. end;
  6882. else
  6883. begin
  6884. { Duplicate the MOV instruction }
  6885. hp3:=tai(hp1.getcopy);
  6886. if first_assignment = nil then
  6887. first_assignment := hp3;
  6888. asml.InsertBefore(hp3, p);
  6889. { Make sure the compiler knows about any final registers written here }
  6890. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6891. with taicpu(hp3).oper[OperIdx]^ do
  6892. begin
  6893. case typ of
  6894. top_ref:
  6895. begin
  6896. if (ref^.base <> NR_NO) and
  6897. (getsupreg(ref^.base) <> RS_ESP) and
  6898. (getsupreg(ref^.base) <> RS_EBP)
  6899. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6900. then
  6901. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6902. if (ref^.index <> NR_NO) and
  6903. (getsupreg(ref^.index) <> RS_ESP) and
  6904. (getsupreg(ref^.index) <> RS_EBP)
  6905. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6906. (ref^.index <> ref^.base) then
  6907. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6908. end;
  6909. top_reg:
  6910. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6911. else
  6912. ;
  6913. end;
  6914. end;
  6915. end;
  6916. end;
  6917. if not GetNextInstruction(hp1, hp1) then
  6918. { Should have dropped out earlier }
  6919. InternalError(2021040710);
  6920. end;
  6921. end;
  6922. end;
  6923. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6924. var
  6925. hp2: tai;
  6926. X: Integer;
  6927. const
  6928. WriteOp: array[0..3] of set of TInsChange = (
  6929. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6930. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6931. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6932. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6933. RegWriteFlags: array[0..7] of set of TInsChange = (
  6934. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6935. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6936. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6937. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6938. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6939. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6940. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6941. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6942. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6943. begin
  6944. { If we have something like:
  6945. cmp ###,%reg1
  6946. mov 0,%reg2
  6947. And no modified registers are shared, move the instruction to before
  6948. the comparison as this means it can be optimised without worrying
  6949. about the FLAGS register. (CMP/MOV is generated by
  6950. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6951. As long as the second instruction doesn't use the flags or one of the
  6952. registers used by CMP or TEST (also check any references that use the
  6953. registers), then it can be moved prior to the comparison.
  6954. }
  6955. Result := False;
  6956. if (hp1.typ <> ait_instruction) or
  6957. taicpu(hp1).is_jmp or
  6958. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6959. Exit;
  6960. { NOP is a pipeline fence, likely marking the beginning of the function
  6961. epilogue, so drop out. Similarly, drop out if POP or RET are
  6962. encountered }
  6963. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6964. Exit;
  6965. if (taicpu(hp1).opcode = A_MOVSS) and
  6966. (taicpu(hp1).ops = 0) then
  6967. { Wrong MOVSS }
  6968. Exit;
  6969. { Check for writes to specific registers first }
  6970. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6971. for X := 0 to 7 do
  6972. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6973. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6974. Exit;
  6975. for X := 0 to taicpu(hp1).ops - 1 do
  6976. begin
  6977. { Check to see if this operand writes to something }
  6978. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6979. { And matches something in the CMP/TEST instruction }
  6980. (
  6981. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6982. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6983. (
  6984. { If it's a register, make sure the register written to doesn't
  6985. appear in the cmp instruction as part of a reference }
  6986. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6987. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6988. )
  6989. ) then
  6990. Exit;
  6991. end;
  6992. { The instruction can be safely moved }
  6993. asml.Remove(hp1);
  6994. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6995. if not GetLastInstruction(p, hp2) then
  6996. asml.InsertBefore(hp1, p)
  6997. else
  6998. asml.InsertAfter(hp1, hp2);
  6999. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7000. for X := 0 to taicpu(hp1).ops - 1 do
  7001. case taicpu(hp1).oper[X]^.typ of
  7002. top_reg:
  7003. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7004. top_ref:
  7005. begin
  7006. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7007. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7008. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7009. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7010. end;
  7011. else
  7012. ;
  7013. end;
  7014. if taicpu(hp1).opcode = A_LEA then
  7015. { The flags will be overwritten by the CMP/TEST instruction }
  7016. ConvertLEA(taicpu(hp1));
  7017. Result := True;
  7018. end;
  7019. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7020. function IsXCHGAcceptable: Boolean; inline;
  7021. begin
  7022. { Always accept if optimising for size }
  7023. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7024. (
  7025. {$ifdef x86_64}
  7026. { XCHG takes 3 cycles on AMD Athlon64 }
  7027. (current_settings.optimizecputype >= cpu_core_i)
  7028. {$else x86_64}
  7029. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7030. than 3, so it becomes a saving compared to three MOVs with two of
  7031. them able to execute simultaneously. [Kit] }
  7032. (current_settings.optimizecputype >= cpu_PentiumM)
  7033. {$endif x86_64}
  7034. );
  7035. end;
  7036. var
  7037. NewRef: TReference;
  7038. hp1, hp2, hp3, hp4: Tai;
  7039. {$ifndef x86_64}
  7040. OperIdx: Integer;
  7041. {$endif x86_64}
  7042. NewInstr : Taicpu;
  7043. NewAligh : Tai_align;
  7044. DestLabel: TAsmLabel;
  7045. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7046. var
  7047. NextInstr: tai;
  7048. begin
  7049. Result := False;
  7050. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7051. if not GetNextInstruction(InputInstr, NextInstr) or
  7052. (
  7053. { The FLAGS register isn't always tracked properly, so do not
  7054. perform this optimisation if a conditional statement follows }
  7055. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7056. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7057. ) then
  7058. begin
  7059. reference_reset(NewRef, 1, []);
  7060. NewRef.base := taicpu(p).oper[0]^.reg;
  7061. NewRef.scalefactor := 1;
  7062. if taicpu(InputInstr).opcode = A_ADD then
  7063. begin
  7064. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7065. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7066. end
  7067. else
  7068. begin
  7069. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7070. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7071. end;
  7072. taicpu(p).opcode := A_LEA;
  7073. taicpu(p).loadref(0, NewRef);
  7074. RemoveInstruction(InputInstr);
  7075. Result := True;
  7076. end;
  7077. end;
  7078. begin
  7079. Result:=false;
  7080. { This optimisation adds an instruction, so only do it for speed }
  7081. if not (cs_opt_size in current_settings.optimizerswitches) and
  7082. MatchOpType(taicpu(p), top_const, top_reg) and
  7083. (taicpu(p).oper[0]^.val = 0) then
  7084. begin
  7085. { To avoid compiler warning }
  7086. DestLabel := nil;
  7087. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7088. InternalError(2021040750);
  7089. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7090. Exit;
  7091. case hp1.typ of
  7092. ait_label:
  7093. begin
  7094. { Change:
  7095. mov $0,%reg mov $0,%reg
  7096. @Lbl1: @Lbl1:
  7097. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7098. je @Lbl2 jne @Lbl2
  7099. To: To:
  7100. mov $0,%reg mov $0,%reg
  7101. jmp @Lbl2 jmp @Lbl3
  7102. (align) (align)
  7103. @Lbl1: @Lbl1:
  7104. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7105. je @Lbl2 je @Lbl2
  7106. @Lbl3: <-- Only if label exists
  7107. (Not if it's optimised for size)
  7108. }
  7109. if not GetNextInstruction(hp1, hp2) then
  7110. Exit;
  7111. if not (cs_opt_size in current_settings.optimizerswitches) and
  7112. (hp2.typ = ait_instruction) and
  7113. (
  7114. { Register sizes must exactly match }
  7115. (
  7116. (taicpu(hp2).opcode = A_CMP) and
  7117. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7118. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7119. ) or (
  7120. (taicpu(hp2).opcode = A_TEST) and
  7121. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7122. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7123. )
  7124. ) and GetNextInstruction(hp2, hp3) and
  7125. (hp3.typ = ait_instruction) and
  7126. (taicpu(hp3).opcode = A_JCC) and
  7127. (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
  7128. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7129. begin
  7130. { Check condition of jump }
  7131. { Always true? }
  7132. if condition_in(C_E, taicpu(hp3).condition) then
  7133. begin
  7134. { Copy label symbol and obtain matching label entry for the
  7135. conditional jump, as this will be our destination}
  7136. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7137. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7138. Result := True;
  7139. end
  7140. { Always false? }
  7141. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7142. begin
  7143. { This is only worth it if there's a jump to take }
  7144. case hp2.typ of
  7145. ait_instruction:
  7146. begin
  7147. if taicpu(hp2).opcode = A_JMP then
  7148. begin
  7149. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7150. { An unconditional jump follows the conditional jump which will always be false,
  7151. so use this jump's destination for the new jump }
  7152. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7153. Result := True;
  7154. end
  7155. else if taicpu(hp2).opcode = A_JCC then
  7156. begin
  7157. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7158. if condition_in(C_E, taicpu(hp2).condition) then
  7159. begin
  7160. { A second conditional jump follows the conditional jump which will always be false,
  7161. while the second jump is always True, so use this jump's destination for the new jump }
  7162. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7163. Result := True;
  7164. end;
  7165. { Don't risk it if the jump isn't always true (Result remains False) }
  7166. end;
  7167. end;
  7168. else
  7169. { If anything else don't optimise };
  7170. end;
  7171. end;
  7172. if Result then
  7173. begin
  7174. { Just so we have something to insert as a paremeter}
  7175. reference_reset(NewRef, 1, []);
  7176. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7177. { Now actually load the correct parameter }
  7178. NewInstr.loadsymbol(0, DestLabel, 0);
  7179. { Get instruction before original label (may not be p under -O3) }
  7180. if not GetLastInstruction(hp1, hp2) then
  7181. { Shouldn't fail here }
  7182. InternalError(2021040701);
  7183. DestLabel.increfs;
  7184. AsmL.InsertAfter(NewInstr, hp2);
  7185. { Add new alignment field }
  7186. (* AsmL.InsertAfter(
  7187. cai_align.create_max(
  7188. current_settings.alignment.jumpalign,
  7189. current_settings.alignment.jumpalignskipmax
  7190. ),
  7191. NewInstr
  7192. ); *)
  7193. end;
  7194. Exit;
  7195. end;
  7196. end;
  7197. else
  7198. ;
  7199. end;
  7200. end;
  7201. if not GetNextInstruction(p, hp1) then
  7202. Exit;
  7203. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7204. and DoMovCmpMemOpt(p, hp1, True) then
  7205. begin
  7206. Result := True;
  7207. Exit;
  7208. end
  7209. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7210. begin
  7211. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7212. further, but we can't just put this jump optimisation in pass 1
  7213. because it tends to perform worse when conditional jumps are
  7214. nearby (e.g. when converting CMOV instructions). [Kit] }
  7215. if OptPass2JMP(hp1) then
  7216. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7217. Result := OptPass1MOV(p)
  7218. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7219. returned True and the instruction is still a MOV, thus checking
  7220. the optimisations below }
  7221. { If OptPass2JMP returned False, no optimisations were done to
  7222. the jump and there are no further optimisations that can be done
  7223. to the MOV instruction on this pass }
  7224. end
  7225. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7226. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7227. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7228. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7229. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7230. begin
  7231. { Change:
  7232. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7233. addl/q $x,%reg2 subl/q $x,%reg2
  7234. To:
  7235. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7236. }
  7237. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7238. { be lazy, checking separately for sub would be slightly better }
  7239. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7240. begin
  7241. TransferUsedRegs(TmpUsedRegs);
  7242. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7243. if TryMovArith2Lea(hp1) then
  7244. begin
  7245. Result := True;
  7246. Exit;
  7247. end
  7248. end
  7249. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7250. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7251. { Same as above, but also adds or subtracts to %reg2 in between.
  7252. It's still valid as long as the flags aren't in use }
  7253. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7254. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7255. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7256. { be lazy, checking separately for sub would be slightly better }
  7257. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7258. begin
  7259. TransferUsedRegs(TmpUsedRegs);
  7260. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7262. if TryMovArith2Lea(hp2) then
  7263. begin
  7264. Result := True;
  7265. Exit;
  7266. end;
  7267. end;
  7268. end
  7269. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7270. {$ifdef x86_64}
  7271. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7272. {$else x86_64}
  7273. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7274. {$endif x86_64}
  7275. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7276. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7277. { mov reg1, reg2 mov reg1, reg2
  7278. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7279. begin
  7280. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7281. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7282. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7283. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7284. TransferUsedRegs(TmpUsedRegs);
  7285. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7286. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7287. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7288. then
  7289. begin
  7290. RemoveCurrentP(p, hp1);
  7291. Result:=true;
  7292. end;
  7293. exit;
  7294. end
  7295. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7296. IsXCHGAcceptable and
  7297. { XCHG doesn't support 8-byte registers }
  7298. (taicpu(p).opsize <> S_B) and
  7299. MatchInstruction(hp1, A_MOV, []) and
  7300. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7301. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7302. GetNextInstruction(hp1, hp2) and
  7303. MatchInstruction(hp2, A_MOV, []) and
  7304. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7305. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7306. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7307. begin
  7308. { mov %reg1,%reg2
  7309. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7310. mov %reg2,%reg3
  7311. (%reg2 not used afterwards)
  7312. Note that xchg takes 3 cycles to execute, and generally mov's take
  7313. only one cycle apiece, but the first two mov's can be executed in
  7314. parallel, only taking 2 cycles overall. Older processors should
  7315. therefore only optimise for size. [Kit]
  7316. }
  7317. TransferUsedRegs(TmpUsedRegs);
  7318. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7319. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7320. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7321. begin
  7322. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7323. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7324. taicpu(hp1).opcode := A_XCHG;
  7325. RemoveCurrentP(p, hp1);
  7326. RemoveInstruction(hp2);
  7327. Result := True;
  7328. Exit;
  7329. end;
  7330. end
  7331. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7332. MatchInstruction(hp1, A_SAR, []) then
  7333. begin
  7334. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7335. begin
  7336. { the use of %edx also covers the opsize being S_L }
  7337. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7338. begin
  7339. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7340. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7341. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7342. begin
  7343. { Change:
  7344. movl %eax,%edx
  7345. sarl $31,%edx
  7346. To:
  7347. cltd
  7348. }
  7349. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7350. RemoveInstruction(hp1);
  7351. taicpu(p).opcode := A_CDQ;
  7352. taicpu(p).opsize := S_NO;
  7353. taicpu(p).clearop(1);
  7354. taicpu(p).clearop(0);
  7355. taicpu(p).ops:=0;
  7356. Result := True;
  7357. end
  7358. else if (cs_opt_size in current_settings.optimizerswitches) and
  7359. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7360. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7361. begin
  7362. { Change:
  7363. movl %edx,%eax
  7364. sarl $31,%edx
  7365. To:
  7366. movl %edx,%eax
  7367. cltd
  7368. Note that this creates a dependency between the two instructions,
  7369. so only perform if optimising for size.
  7370. }
  7371. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7372. taicpu(hp1).opcode := A_CDQ;
  7373. taicpu(hp1).opsize := S_NO;
  7374. taicpu(hp1).clearop(1);
  7375. taicpu(hp1).clearop(0);
  7376. taicpu(hp1).ops:=0;
  7377. end;
  7378. {$ifndef x86_64}
  7379. end
  7380. { Don't bother if CMOV is supported, because a more optimal
  7381. sequence would have been generated for the Abs() intrinsic }
  7382. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7383. { the use of %eax also covers the opsize being S_L }
  7384. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7385. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7386. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7387. GetNextInstruction(hp1, hp2) and
  7388. MatchInstruction(hp2, A_XOR, [S_L]) and
  7389. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7390. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7391. GetNextInstruction(hp2, hp3) and
  7392. MatchInstruction(hp3, A_SUB, [S_L]) and
  7393. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7394. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7395. begin
  7396. { Change:
  7397. movl %eax,%edx
  7398. sarl $31,%eax
  7399. xorl %eax,%edx
  7400. subl %eax,%edx
  7401. (Instruction that uses %edx)
  7402. (%eax deallocated)
  7403. (%edx deallocated)
  7404. To:
  7405. cltd
  7406. xorl %edx,%eax <-- Note the registers have swapped
  7407. subl %edx,%eax
  7408. (Instruction that uses %eax) <-- %eax rather than %edx
  7409. }
  7410. TransferUsedRegs(TmpUsedRegs);
  7411. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7412. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7413. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7414. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7415. begin
  7416. if GetNextInstruction(hp3, hp4) and
  7417. not RegModifiedByInstruction(NR_EDX, hp4) and
  7418. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7419. begin
  7420. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7421. taicpu(p).opcode := A_CDQ;
  7422. taicpu(p).clearop(1);
  7423. taicpu(p).clearop(0);
  7424. taicpu(p).ops:=0;
  7425. RemoveInstruction(hp1);
  7426. taicpu(hp2).loadreg(0, NR_EDX);
  7427. taicpu(hp2).loadreg(1, NR_EAX);
  7428. taicpu(hp3).loadreg(0, NR_EDX);
  7429. taicpu(hp3).loadreg(1, NR_EAX);
  7430. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7431. { Convert references in the following instruction (hp4) from %edx to %eax }
  7432. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7433. with taicpu(hp4).oper[OperIdx]^ do
  7434. case typ of
  7435. top_reg:
  7436. if getsupreg(reg) = RS_EDX then
  7437. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7438. top_ref:
  7439. begin
  7440. if getsupreg(reg) = RS_EDX then
  7441. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7442. if getsupreg(reg) = RS_EDX then
  7443. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7444. end;
  7445. else
  7446. ;
  7447. end;
  7448. end;
  7449. end;
  7450. {$else x86_64}
  7451. end;
  7452. end
  7453. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7454. { the use of %rdx also covers the opsize being S_Q }
  7455. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7456. begin
  7457. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7458. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7459. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7460. begin
  7461. { Change:
  7462. movq %rax,%rdx
  7463. sarq $63,%rdx
  7464. To:
  7465. cqto
  7466. }
  7467. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7468. RemoveInstruction(hp1);
  7469. taicpu(p).opcode := A_CQO;
  7470. taicpu(p).opsize := S_NO;
  7471. taicpu(p).clearop(1);
  7472. taicpu(p).clearop(0);
  7473. taicpu(p).ops:=0;
  7474. Result := True;
  7475. end
  7476. else if (cs_opt_size in current_settings.optimizerswitches) and
  7477. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7478. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7479. begin
  7480. { Change:
  7481. movq %rdx,%rax
  7482. sarq $63,%rdx
  7483. To:
  7484. movq %rdx,%rax
  7485. cqto
  7486. Note that this creates a dependency between the two instructions,
  7487. so only perform if optimising for size.
  7488. }
  7489. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7490. taicpu(hp1).opcode := A_CQO;
  7491. taicpu(hp1).opsize := S_NO;
  7492. taicpu(hp1).clearop(1);
  7493. taicpu(hp1).clearop(0);
  7494. taicpu(hp1).ops:=0;
  7495. {$endif x86_64}
  7496. end;
  7497. end;
  7498. end
  7499. else if MatchInstruction(hp1, A_MOV, []) and
  7500. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7501. { Though "GetNextInstruction" could be factored out, along with
  7502. the instructions that depend on hp2, it is an expensive call that
  7503. should be delayed for as long as possible, hence we do cheaper
  7504. checks first that are likely to be False. [Kit] }
  7505. begin
  7506. if (
  7507. (
  7508. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7509. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7510. (
  7511. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7512. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7513. )
  7514. ) or
  7515. (
  7516. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7517. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7518. (
  7519. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7520. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7521. )
  7522. )
  7523. ) and
  7524. GetNextInstruction(hp1, hp2) and
  7525. MatchInstruction(hp2, A_SAR, []) and
  7526. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7527. begin
  7528. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7529. begin
  7530. { Change:
  7531. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7532. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7533. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7534. To:
  7535. movl r/m,%eax <- Note the change in register
  7536. cltd
  7537. }
  7538. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7539. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7540. taicpu(p).loadreg(1, NR_EAX);
  7541. taicpu(hp1).opcode := A_CDQ;
  7542. taicpu(hp1).clearop(1);
  7543. taicpu(hp1).clearop(0);
  7544. taicpu(hp1).ops:=0;
  7545. RemoveInstruction(hp2);
  7546. (*
  7547. {$ifdef x86_64}
  7548. end
  7549. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7550. { This code sequence does not get generated - however it might become useful
  7551. if and when 128-bit signed integer types make an appearance, so the code
  7552. is kept here for when it is eventually needed. [Kit] }
  7553. (
  7554. (
  7555. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7556. (
  7557. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7558. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7559. )
  7560. ) or
  7561. (
  7562. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7563. (
  7564. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7565. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7566. )
  7567. )
  7568. ) and
  7569. GetNextInstruction(hp1, hp2) and
  7570. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7571. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7572. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7573. begin
  7574. { Change:
  7575. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7576. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7577. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7578. To:
  7579. movq r/m,%rax <- Note the change in register
  7580. cqto
  7581. }
  7582. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7583. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7584. taicpu(p).loadreg(1, NR_RAX);
  7585. taicpu(hp1).opcode := A_CQO;
  7586. taicpu(hp1).clearop(1);
  7587. taicpu(hp1).clearop(0);
  7588. taicpu(hp1).ops:=0;
  7589. RemoveInstruction(hp2);
  7590. {$endif x86_64}
  7591. *)
  7592. end;
  7593. end;
  7594. {$ifdef x86_64}
  7595. end
  7596. else if (taicpu(p).opsize = S_L) and
  7597. (taicpu(p).oper[1]^.typ = top_reg) and
  7598. (
  7599. MatchInstruction(hp1, A_MOV,[]) and
  7600. (taicpu(hp1).opsize = S_L) and
  7601. (taicpu(hp1).oper[1]^.typ = top_reg)
  7602. ) and (
  7603. GetNextInstruction(hp1, hp2) and
  7604. (tai(hp2).typ=ait_instruction) and
  7605. (taicpu(hp2).opsize = S_Q) and
  7606. (
  7607. (
  7608. MatchInstruction(hp2, A_ADD,[]) and
  7609. (taicpu(hp2).opsize = S_Q) and
  7610. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7611. (
  7612. (
  7613. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7614. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7615. ) or (
  7616. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7617. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7618. )
  7619. )
  7620. ) or (
  7621. MatchInstruction(hp2, A_LEA,[]) and
  7622. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7623. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7624. (
  7625. (
  7626. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7627. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7628. ) or (
  7629. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7630. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7631. )
  7632. ) and (
  7633. (
  7634. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7635. ) or (
  7636. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7637. )
  7638. )
  7639. )
  7640. )
  7641. ) and (
  7642. GetNextInstruction(hp2, hp3) and
  7643. MatchInstruction(hp3, A_SHR,[]) and
  7644. (taicpu(hp3).opsize = S_Q) and
  7645. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7646. (taicpu(hp3).oper[0]^.val = 1) and
  7647. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7648. ) then
  7649. begin
  7650. { Change movl x, reg1d movl x, reg1d
  7651. movl y, reg2d movl y, reg2d
  7652. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7653. shrq $1, reg1q shrq $1, reg1q
  7654. ( reg1d and reg2d can be switched around in the first two instructions )
  7655. To movl x, reg1d
  7656. addl y, reg1d
  7657. rcrl $1, reg1d
  7658. This corresponds to the common expression (x + y) shr 1, where
  7659. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7660. smaller code, but won't account for x + y causing an overflow). [Kit]
  7661. }
  7662. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7663. { Change first MOV command to have the same register as the final output }
  7664. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7665. else
  7666. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7667. { Change second MOV command to an ADD command. This is easier than
  7668. converting the existing command because it means we don't have to
  7669. touch 'y', which might be a complicated reference, and also the
  7670. fact that the third command might either be ADD or LEA. [Kit] }
  7671. taicpu(hp1).opcode := A_ADD;
  7672. { Delete old ADD/LEA instruction }
  7673. RemoveInstruction(hp2);
  7674. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7675. taicpu(hp3).opcode := A_RCR;
  7676. taicpu(hp3).changeopsize(S_L);
  7677. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7678. {$endif x86_64}
  7679. end;
  7680. end;
  7681. {$push}
  7682. {$q-}{$r-}
  7683. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7684. var
  7685. ThisReg: TRegister;
  7686. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7687. TargetSubReg: TSubRegister;
  7688. hp1, hp2: tai;
  7689. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7690. { Store list of found instructions so we don't have to call
  7691. GetNextInstructionUsingReg multiple times }
  7692. InstrList: array of taicpu;
  7693. InstrMax, Index: Integer;
  7694. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7695. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7696. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7697. WorkingValue: TCgInt;
  7698. PreMessage: string;
  7699. { Data flow analysis }
  7700. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7701. BitwiseOnly, OrXorUsed,
  7702. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7703. function CheckOverflowConditions: Boolean;
  7704. begin
  7705. Result := True;
  7706. if (TestValSignedMax > SignedUpperLimit) then
  7707. UpperSignedOverflow := True;
  7708. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7709. LowerSignedOverflow := True;
  7710. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7711. LowerUnsignedOverflow := True;
  7712. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7713. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7714. begin
  7715. { Absolute overflow }
  7716. Result := False;
  7717. Exit;
  7718. end;
  7719. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7720. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7721. ShiftDownOverflow := True;
  7722. if (TestValMin < 0) or (TestValMax < 0) then
  7723. begin
  7724. LowerUnsignedOverflow := True;
  7725. UpperUnsignedOverflow := True;
  7726. end;
  7727. end;
  7728. function AdjustInitialLoadAndSize: Boolean;
  7729. begin
  7730. Result := False;
  7731. if not p_removed then
  7732. begin
  7733. if TargetSize = MinSize then
  7734. begin
  7735. { Convert the input MOVZX to a MOV }
  7736. if (taicpu(p).oper[0]^.typ = top_reg) and
  7737. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7738. begin
  7739. { Or remove it completely! }
  7740. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7741. RemoveCurrentP(p);
  7742. p_removed := True;
  7743. end
  7744. else
  7745. begin
  7746. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7747. taicpu(p).opcode := A_MOV;
  7748. taicpu(p).oper[1]^.reg := ThisReg;
  7749. taicpu(p).opsize := TargetSize;
  7750. end;
  7751. Result := True;
  7752. end
  7753. else if TargetSize <> MaxSize then
  7754. begin
  7755. case MaxSize of
  7756. S_L:
  7757. if TargetSize = S_W then
  7758. begin
  7759. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7760. taicpu(p).opsize := S_BW;
  7761. taicpu(p).oper[1]^.reg := ThisReg;
  7762. Result := True;
  7763. end
  7764. else
  7765. InternalError(2020112341);
  7766. S_W:
  7767. if TargetSize = S_L then
  7768. begin
  7769. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7770. taicpu(p).opsize := S_BL;
  7771. taicpu(p).oper[1]^.reg := ThisReg;
  7772. Result := True;
  7773. end
  7774. else
  7775. InternalError(2020112342);
  7776. else
  7777. ;
  7778. end;
  7779. end
  7780. else if not hp1_removed and not RegInUse then
  7781. begin
  7782. { If we have something like:
  7783. movzbl (oper),%regd
  7784. add x, %regd
  7785. movzbl %regb, %regd
  7786. We can reduce the register size to the input of the final
  7787. movzbl instruction. Overflows won't have any effect.
  7788. }
  7789. if (taicpu(p).opsize in [S_BW, S_BL]) and
  7790. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7791. begin
  7792. TargetSize := S_B;
  7793. setsubreg(ThisReg, R_SUBL);
  7794. Result := True;
  7795. end
  7796. else if (taicpu(p).opsize = S_WL) and
  7797. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7798. begin
  7799. TargetSize := S_W;
  7800. setsubreg(ThisReg, R_SUBW);
  7801. Result := True;
  7802. end;
  7803. if Result then
  7804. begin
  7805. { Convert the input MOVZX to a MOV }
  7806. if (taicpu(p).oper[0]^.typ = top_reg) and
  7807. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7808. begin
  7809. { Or remove it completely! }
  7810. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7811. RemoveCurrentP(p);
  7812. p_removed := True;
  7813. end
  7814. else
  7815. begin
  7816. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7817. taicpu(p).opcode := A_MOV;
  7818. taicpu(p).oper[1]^.reg := ThisReg;
  7819. taicpu(p).opsize := TargetSize;
  7820. end;
  7821. end;
  7822. end;
  7823. end;
  7824. end;
  7825. procedure AdjustFinalLoad;
  7826. begin
  7827. if not LowerUnsignedOverflow then
  7828. begin
  7829. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7830. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7831. begin
  7832. { Convert the output MOVZX to a MOV }
  7833. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7834. begin
  7835. { Or remove it completely! }
  7836. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7837. { Be careful; if p = hp1 and p was also removed, p
  7838. will become a dangling pointer }
  7839. if p = hp1 then
  7840. begin
  7841. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7842. p_removed := True;
  7843. end
  7844. else
  7845. RemoveInstruction(hp1);
  7846. hp1_removed := True;
  7847. end
  7848. else
  7849. begin
  7850. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7851. taicpu(hp1).opcode := A_MOV;
  7852. taicpu(hp1).oper[0]^.reg := ThisReg;
  7853. taicpu(hp1).opsize := TargetSize;
  7854. end;
  7855. end
  7856. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7857. begin
  7858. { Need to change the size of the output }
  7859. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7860. taicpu(hp1).oper[0]^.reg := ThisReg;
  7861. taicpu(hp1).opsize := S_BL;
  7862. end;
  7863. end;
  7864. end;
  7865. function CompressInstructions: Boolean;
  7866. var
  7867. LocalIndex: Integer;
  7868. begin
  7869. Result := False;
  7870. { The objective here is to try to find a combination that
  7871. removes one of the MOV/Z instructions. }
  7872. if (
  7873. (taicpu(p).oper[0]^.typ <> top_reg) or
  7874. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7875. ) and
  7876. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7877. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7878. begin
  7879. { Make a preference to remove the second MOVZX instruction }
  7880. case taicpu(hp1).opsize of
  7881. S_BL, S_WL:
  7882. begin
  7883. TargetSize := S_L;
  7884. TargetSubReg := R_SUBD;
  7885. end;
  7886. S_BW:
  7887. begin
  7888. TargetSize := S_W;
  7889. TargetSubReg := R_SUBW;
  7890. end;
  7891. else
  7892. InternalError(2020112302);
  7893. end;
  7894. end
  7895. else
  7896. begin
  7897. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7898. begin
  7899. { Exceeded lower bound but not upper bound }
  7900. TargetSize := MaxSize;
  7901. end
  7902. else if not LowerUnsignedOverflow then
  7903. begin
  7904. { Size didn't exceed lower bound }
  7905. TargetSize := MinSize;
  7906. end
  7907. else
  7908. Exit;
  7909. end;
  7910. case TargetSize of
  7911. S_B:
  7912. TargetSubReg := R_SUBL;
  7913. S_W:
  7914. TargetSubReg := R_SUBW;
  7915. S_L:
  7916. TargetSubReg := R_SUBD;
  7917. else
  7918. InternalError(2020112350);
  7919. end;
  7920. { Update the register to its new size }
  7921. setsubreg(ThisReg, TargetSubReg);
  7922. RegInUse := False;
  7923. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7924. begin
  7925. { Check to see if the active register is used afterwards;
  7926. if not, we can change it and make a saving. }
  7927. TransferUsedRegs(TmpUsedRegs);
  7928. { The target register may be marked as in use to cross
  7929. a jump to a distant label, so exclude it }
  7930. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7931. hp2 := p;
  7932. repeat
  7933. { Explicitly check for the excluded register (don't include the first
  7934. instruction as it may be reading from here }
  7935. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7936. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7937. begin
  7938. RegInUse := True;
  7939. Break;
  7940. end;
  7941. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7942. if not GetNextInstruction(hp2, hp2) then
  7943. InternalError(2020112340);
  7944. until (hp2 = hp1);
  7945. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7946. { We might still be able to get away with this }
  7947. RegInUse := not
  7948. (
  7949. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7950. (hp2.typ = ait_instruction) and
  7951. (
  7952. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7953. instruction that doesn't actually contain ThisReg }
  7954. (cs_opt_level3 in current_settings.optimizerswitches) or
  7955. RegInInstruction(ThisReg, hp2)
  7956. ) and
  7957. RegLoadedWithNewValue(ThisReg, hp2)
  7958. );
  7959. if not RegInUse then
  7960. begin
  7961. { Force the register size to the same as this instruction so it can be removed}
  7962. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7963. begin
  7964. TargetSize := S_L;
  7965. TargetSubReg := R_SUBD;
  7966. end
  7967. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7968. begin
  7969. TargetSize := S_W;
  7970. TargetSubReg := R_SUBW;
  7971. end;
  7972. ThisReg := taicpu(hp1).oper[1]^.reg;
  7973. setsubreg(ThisReg, TargetSubReg);
  7974. RegChanged := True;
  7975. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7976. TransferUsedRegs(TmpUsedRegs);
  7977. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7978. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7979. if p = hp1 then
  7980. begin
  7981. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7982. p_removed := True;
  7983. end
  7984. else
  7985. RemoveInstruction(hp1);
  7986. hp1_removed := True;
  7987. { Instruction will become "mov %reg,%reg" }
  7988. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7989. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7990. begin
  7991. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7992. RemoveCurrentP(p);
  7993. p_removed := True;
  7994. end
  7995. else
  7996. taicpu(p).oper[1]^.reg := ThisReg;
  7997. Result := True;
  7998. end
  7999. else
  8000. begin
  8001. if TargetSize <> MaxSize then
  8002. begin
  8003. { Since the register is in use, we have to force it to
  8004. MaxSize otherwise part of it may become undefined later on }
  8005. TargetSize := MaxSize;
  8006. case TargetSize of
  8007. S_B:
  8008. TargetSubReg := R_SUBL;
  8009. S_W:
  8010. TargetSubReg := R_SUBW;
  8011. S_L:
  8012. TargetSubReg := R_SUBD;
  8013. else
  8014. InternalError(2020112351);
  8015. end;
  8016. setsubreg(ThisReg, TargetSubReg);
  8017. end;
  8018. AdjustFinalLoad;
  8019. end;
  8020. end
  8021. else
  8022. AdjustFinalLoad;
  8023. Result := AdjustInitialLoadAndSize or Result;
  8024. { Now go through every instruction we found and change the
  8025. size. If TargetSize = MaxSize, then almost no changes are
  8026. needed and Result can remain False if it hasn't been set
  8027. yet.
  8028. If RegChanged is True, then the register requires changing
  8029. and so the point about TargetSize = MaxSize doesn't apply. }
  8030. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8031. begin
  8032. for LocalIndex := 0 to InstrMax do
  8033. begin
  8034. { If p_removed is true, then the original MOV/Z was removed
  8035. and removing the AND instruction may not be safe if it
  8036. appears first }
  8037. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8038. InternalError(2020112310);
  8039. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8040. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8041. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8042. InstrList[LocalIndex].opsize := TargetSize;
  8043. end;
  8044. Result := True;
  8045. end;
  8046. end;
  8047. begin
  8048. Result := False;
  8049. p_removed := False;
  8050. hp1_removed := False;
  8051. ThisReg := taicpu(p).oper[1]^.reg;
  8052. { Check for:
  8053. movs/z ###,%ecx (or %cx or %rcx)
  8054. ...
  8055. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8056. (dealloc %ecx)
  8057. Change to:
  8058. mov ###,%cl (if ### = %cl, then remove completely)
  8059. ...
  8060. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8061. }
  8062. if (getsupreg(ThisReg) = RS_ECX) and
  8063. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8064. (hp1.typ = ait_instruction) and
  8065. (
  8066. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8067. instruction that doesn't actually contain ECX }
  8068. (cs_opt_level3 in current_settings.optimizerswitches) or
  8069. RegInInstruction(NR_ECX, hp1) or
  8070. (
  8071. { It's common for the shift/rotate's read/write register to be
  8072. initialised in between, so under -O2 and under, search ahead
  8073. one more instruction
  8074. }
  8075. GetNextInstruction(hp1, hp1) and
  8076. (hp1.typ = ait_instruction) and
  8077. RegInInstruction(NR_ECX, hp1)
  8078. )
  8079. ) and
  8080. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8081. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8082. begin
  8083. TransferUsedRegs(TmpUsedRegs);
  8084. hp2 := p;
  8085. repeat
  8086. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8087. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8088. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8089. begin
  8090. case taicpu(p).opsize of
  8091. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8092. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8093. begin
  8094. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8095. RemoveCurrentP(p);
  8096. end
  8097. else
  8098. begin
  8099. taicpu(p).opcode := A_MOV;
  8100. taicpu(p).opsize := S_B;
  8101. taicpu(p).oper[1]^.reg := NR_CL;
  8102. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8103. end;
  8104. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8105. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8106. begin
  8107. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8108. RemoveCurrentP(p);
  8109. end
  8110. else
  8111. begin
  8112. taicpu(p).opcode := A_MOV;
  8113. taicpu(p).opsize := S_W;
  8114. taicpu(p).oper[1]^.reg := NR_CX;
  8115. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8116. end;
  8117. {$ifdef x86_64}
  8118. S_LQ:
  8119. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8120. begin
  8121. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8122. RemoveCurrentP(p);
  8123. end
  8124. else
  8125. begin
  8126. taicpu(p).opcode := A_MOV;
  8127. taicpu(p).opsize := S_L;
  8128. taicpu(p).oper[1]^.reg := NR_ECX;
  8129. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8130. end;
  8131. {$endif x86_64}
  8132. else
  8133. InternalError(2021120401);
  8134. end;
  8135. Result := True;
  8136. Exit;
  8137. end;
  8138. end;
  8139. { This is anything but quick! }
  8140. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8141. Exit;
  8142. SetLength(InstrList, 0);
  8143. InstrMax := -1;
  8144. case taicpu(p).opsize of
  8145. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8146. begin
  8147. {$if defined(i386) or defined(i8086)}
  8148. { If the target size is 8-bit, make sure we can actually encode it }
  8149. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8150. Exit;
  8151. {$endif i386 or i8086}
  8152. LowerLimit := $FF;
  8153. SignedLowerLimit := $7F;
  8154. SignedLowerLimitBottom := -128;
  8155. MinSize := S_B;
  8156. if taicpu(p).opsize = S_BW then
  8157. begin
  8158. MaxSize := S_W;
  8159. UpperLimit := $FFFF;
  8160. SignedUpperLimit := $7FFF;
  8161. SignedUpperLimitBottom := -32768;
  8162. end
  8163. else
  8164. begin
  8165. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8166. MaxSize := S_L;
  8167. UpperLimit := $FFFFFFFF;
  8168. SignedUpperLimit := $7FFFFFFF;
  8169. SignedUpperLimitBottom := -2147483648;
  8170. end;
  8171. end;
  8172. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8173. begin
  8174. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8175. LowerLimit := $FFFF;
  8176. SignedLowerLimit := $7FFF;
  8177. SignedLowerLimitBottom := -32768;
  8178. UpperLimit := $FFFFFFFF;
  8179. SignedUpperLimit := $7FFFFFFF;
  8180. SignedUpperLimitBottom := -2147483648;
  8181. MinSize := S_W;
  8182. MaxSize := S_L;
  8183. end;
  8184. {$ifdef x86_64}
  8185. S_LQ:
  8186. begin
  8187. { Both the lower and upper limits are set to 32-bit. If a limit
  8188. is breached, then optimisation is impossible }
  8189. LowerLimit := $FFFFFFFF;
  8190. SignedLowerLimit := $7FFFFFFF;
  8191. SignedLowerLimitBottom := -2147483648;
  8192. UpperLimit := $FFFFFFFF;
  8193. SignedUpperLimit := $7FFFFFFF;
  8194. SignedUpperLimitBottom := -2147483648;
  8195. MinSize := S_L;
  8196. MaxSize := S_L;
  8197. end;
  8198. {$endif x86_64}
  8199. else
  8200. InternalError(2020112301);
  8201. end;
  8202. TestValMin := 0;
  8203. TestValMax := LowerLimit;
  8204. TestValSignedMax := SignedLowerLimit;
  8205. TryShiftDownLimit := LowerLimit;
  8206. TryShiftDown := S_NO;
  8207. ShiftDownOverflow := False;
  8208. RegChanged := False;
  8209. BitwiseOnly := True;
  8210. OrXorUsed := False;
  8211. UpperSignedOverflow := False;
  8212. LowerSignedOverflow := False;
  8213. UpperUnsignedOverflow := False;
  8214. LowerUnsignedOverflow := False;
  8215. hp1 := p;
  8216. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8217. (hp1.typ = ait_instruction) and
  8218. (
  8219. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8220. instruction that doesn't actually contain ThisReg }
  8221. (cs_opt_level3 in current_settings.optimizerswitches) or
  8222. { This allows this Movx optimisation to work through the SETcc instructions
  8223. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8224. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8225. skip over these SETcc instructions). }
  8226. (taicpu(hp1).opcode = A_SETcc) or
  8227. RegInInstruction(ThisReg, hp1)
  8228. ) do
  8229. begin
  8230. case taicpu(hp1).opcode of
  8231. A_INC,A_DEC:
  8232. begin
  8233. { Has to be an exact match on the register }
  8234. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8235. Break;
  8236. if taicpu(hp1).opcode = A_INC then
  8237. begin
  8238. Inc(TestValMin);
  8239. Inc(TestValMax);
  8240. Inc(TestValSignedMax);
  8241. end
  8242. else
  8243. begin
  8244. Dec(TestValMin);
  8245. Dec(TestValMax);
  8246. Dec(TestValSignedMax);
  8247. end;
  8248. end;
  8249. A_TEST, A_CMP:
  8250. begin
  8251. if (
  8252. { Too high a risk of non-linear behaviour that breaks DFA
  8253. here, unless it's cmp $0,%reg, which is equivalent to
  8254. test %reg,%reg }
  8255. OrXorUsed and
  8256. (taicpu(hp1).opcode = A_CMP) and
  8257. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8258. ) or
  8259. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8260. { Has to be an exact match on the register }
  8261. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8262. (
  8263. { Permit "test %reg,%reg" }
  8264. (taicpu(hp1).opcode = A_TEST) and
  8265. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8266. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8267. ) or
  8268. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8269. { Make sure the comparison value is not smaller than the
  8270. smallest allowed signed value for the minimum size (e.g.
  8271. -128 for 8-bit) }
  8272. not (
  8273. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8274. { Is it in the negative range? }
  8275. (
  8276. (taicpu(hp1).oper[0]^.val < 0) and
  8277. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8278. )
  8279. ) then
  8280. Break;
  8281. { Check to see if the active register is used afterwards }
  8282. TransferUsedRegs(TmpUsedRegs);
  8283. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8284. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8285. begin
  8286. { Make sure the comparison or any previous instructions
  8287. hasn't pushed the test values outside of the range of
  8288. MinSize }
  8289. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8290. begin
  8291. { Exceeded lower bound but not upper bound }
  8292. Exit;
  8293. end
  8294. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8295. begin
  8296. { Size didn't exceed lower bound }
  8297. TargetSize := MinSize;
  8298. end
  8299. else
  8300. Break;
  8301. case TargetSize of
  8302. S_B:
  8303. TargetSubReg := R_SUBL;
  8304. S_W:
  8305. TargetSubReg := R_SUBW;
  8306. S_L:
  8307. TargetSubReg := R_SUBD;
  8308. else
  8309. InternalError(2021051002);
  8310. end;
  8311. if TargetSize <> MaxSize then
  8312. begin
  8313. { Update the register to its new size }
  8314. setsubreg(ThisReg, TargetSubReg);
  8315. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8316. taicpu(hp1).oper[1]^.reg := ThisReg;
  8317. taicpu(hp1).opsize := TargetSize;
  8318. { Convert the input MOVZX to a MOV if necessary }
  8319. AdjustInitialLoadAndSize;
  8320. if (InstrMax >= 0) then
  8321. begin
  8322. for Index := 0 to InstrMax do
  8323. begin
  8324. { If p_removed is true, then the original MOV/Z was removed
  8325. and removing the AND instruction may not be safe if it
  8326. appears first }
  8327. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8328. InternalError(2020112311);
  8329. if InstrList[Index].oper[0]^.typ = top_reg then
  8330. InstrList[Index].oper[0]^.reg := ThisReg;
  8331. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8332. InstrList[Index].opsize := MinSize;
  8333. end;
  8334. end;
  8335. Result := True;
  8336. end;
  8337. Exit;
  8338. end;
  8339. end;
  8340. A_SETcc:
  8341. begin
  8342. { This allows this Movx optimisation to work through the SETcc instructions
  8343. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8344. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8345. skip over these SETcc instructions). }
  8346. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8347. { Of course, break out if the current register is used }
  8348. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8349. Break
  8350. else
  8351. { We must use Continue so the instruction doesn't get added
  8352. to InstrList }
  8353. Continue;
  8354. end;
  8355. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8356. begin
  8357. if
  8358. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8359. { Has to be an exact match on the register }
  8360. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8361. (
  8362. (
  8363. (taicpu(hp1).oper[0]^.typ = top_const) and
  8364. (
  8365. (
  8366. (taicpu(hp1).opcode = A_SHL) and
  8367. (
  8368. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8369. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8370. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8371. )
  8372. ) or (
  8373. (taicpu(hp1).opcode <> A_SHL) and
  8374. (
  8375. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8376. { Is it in the negative range? }
  8377. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8378. )
  8379. )
  8380. )
  8381. ) or (
  8382. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8383. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8384. )
  8385. ) then
  8386. Break;
  8387. { Only process OR and XOR if there are only bitwise operations,
  8388. since otherwise they can too easily fool the data flow
  8389. analysis (they can cause non-linear behaviour) }
  8390. case taicpu(hp1).opcode of
  8391. A_ADD:
  8392. begin
  8393. if OrXorUsed then
  8394. { Too high a risk of non-linear behaviour that breaks DFA here }
  8395. Break
  8396. else
  8397. BitwiseOnly := False;
  8398. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8399. begin
  8400. TestValMin := TestValMin * 2;
  8401. TestValMax := TestValMax * 2;
  8402. TestValSignedMax := TestValSignedMax * 2;
  8403. end
  8404. else
  8405. begin
  8406. WorkingValue := taicpu(hp1).oper[0]^.val;
  8407. TestValMin := TestValMin + WorkingValue;
  8408. TestValMax := TestValMax + WorkingValue;
  8409. TestValSignedMax := TestValSignedMax + WorkingValue;
  8410. end;
  8411. end;
  8412. A_SUB:
  8413. begin
  8414. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8415. begin
  8416. TestValMin := 0;
  8417. TestValMax := 0;
  8418. TestValSignedMax := 0;
  8419. end
  8420. else
  8421. begin
  8422. if OrXorUsed then
  8423. { Too high a risk of non-linear behaviour that breaks DFA here }
  8424. Break
  8425. else
  8426. BitwiseOnly := False;
  8427. WorkingValue := taicpu(hp1).oper[0]^.val;
  8428. TestValMin := TestValMin - WorkingValue;
  8429. TestValMax := TestValMax - WorkingValue;
  8430. TestValSignedMax := TestValSignedMax - WorkingValue;
  8431. end;
  8432. end;
  8433. A_AND:
  8434. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8435. begin
  8436. { we might be able to go smaller if AND appears first }
  8437. if InstrMax = -1 then
  8438. case MinSize of
  8439. S_B:
  8440. ;
  8441. S_W:
  8442. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8443. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8444. begin
  8445. TryShiftDown := S_B;
  8446. TryShiftDownLimit := $FF;
  8447. end;
  8448. S_L:
  8449. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8450. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8451. begin
  8452. TryShiftDown := S_B;
  8453. TryShiftDownLimit := $FF;
  8454. end
  8455. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8456. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8457. begin
  8458. TryShiftDown := S_W;
  8459. TryShiftDownLimit := $FFFF;
  8460. end;
  8461. else
  8462. InternalError(2020112320);
  8463. end;
  8464. WorkingValue := taicpu(hp1).oper[0]^.val;
  8465. TestValMin := TestValMin and WorkingValue;
  8466. TestValMax := TestValMax and WorkingValue;
  8467. TestValSignedMax := TestValSignedMax and WorkingValue;
  8468. end;
  8469. A_OR:
  8470. begin
  8471. if not BitwiseOnly then
  8472. Break;
  8473. OrXorUsed := True;
  8474. WorkingValue := taicpu(hp1).oper[0]^.val;
  8475. TestValMin := TestValMin or WorkingValue;
  8476. TestValMax := TestValMax or WorkingValue;
  8477. TestValSignedMax := TestValSignedMax or WorkingValue;
  8478. end;
  8479. A_XOR:
  8480. begin
  8481. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8482. begin
  8483. TestValMin := 0;
  8484. TestValMax := 0;
  8485. TestValSignedMax := 0;
  8486. end
  8487. else
  8488. begin
  8489. if not BitwiseOnly then
  8490. Break;
  8491. OrXorUsed := True;
  8492. WorkingValue := taicpu(hp1).oper[0]^.val;
  8493. TestValMin := TestValMin xor WorkingValue;
  8494. TestValMax := TestValMax xor WorkingValue;
  8495. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8496. end;
  8497. end;
  8498. A_SHL:
  8499. begin
  8500. BitwiseOnly := False;
  8501. WorkingValue := taicpu(hp1).oper[0]^.val;
  8502. TestValMin := TestValMin shl WorkingValue;
  8503. TestValMax := TestValMax shl WorkingValue;
  8504. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8505. end;
  8506. A_SHR,
  8507. { The first instruction was MOVZX, so the value won't be negative }
  8508. A_SAR:
  8509. begin
  8510. if InstrMax <> -1 then
  8511. BitwiseOnly := False
  8512. else
  8513. { we might be able to go smaller if SHR appears first }
  8514. case MinSize of
  8515. S_B:
  8516. ;
  8517. S_W:
  8518. if (taicpu(hp1).oper[0]^.val >= 8) then
  8519. begin
  8520. TryShiftDown := S_B;
  8521. TryShiftDownLimit := $FF;
  8522. TryShiftDownSignedLimit := $7F;
  8523. TryShiftDownSignedLimitLower := -128;
  8524. end;
  8525. S_L:
  8526. if (taicpu(hp1).oper[0]^.val >= 24) then
  8527. begin
  8528. TryShiftDown := S_B;
  8529. TryShiftDownLimit := $FF;
  8530. TryShiftDownSignedLimit := $7F;
  8531. TryShiftDownSignedLimitLower := -128;
  8532. end
  8533. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8534. begin
  8535. TryShiftDown := S_W;
  8536. TryShiftDownLimit := $FFFF;
  8537. TryShiftDownSignedLimit := $7FFF;
  8538. TryShiftDownSignedLimitLower := -32768;
  8539. end;
  8540. else
  8541. InternalError(2020112321);
  8542. end;
  8543. WorkingValue := taicpu(hp1).oper[0]^.val;
  8544. if taicpu(hp1).opcode = A_SAR then
  8545. begin
  8546. TestValMin := SarInt64(TestValMin, WorkingValue);
  8547. TestValMax := SarInt64(TestValMax, WorkingValue);
  8548. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8549. end
  8550. else
  8551. begin
  8552. TestValMin := TestValMin shr WorkingValue;
  8553. TestValMax := TestValMax shr WorkingValue;
  8554. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8555. end;
  8556. end;
  8557. else
  8558. InternalError(2020112303);
  8559. end;
  8560. end;
  8561. (*
  8562. A_IMUL:
  8563. case taicpu(hp1).ops of
  8564. 2:
  8565. begin
  8566. if not MatchOpType(hp1, top_reg, top_reg) or
  8567. { Has to be an exact match on the register }
  8568. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8569. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8570. Break;
  8571. TestValMin := TestValMin * TestValMin;
  8572. TestValMax := TestValMax * TestValMax;
  8573. TestValSignedMax := TestValSignedMax * TestValMax;
  8574. end;
  8575. 3:
  8576. begin
  8577. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8578. { Has to be an exact match on the register }
  8579. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8580. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8581. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8582. { Is it in the negative range? }
  8583. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8584. Break;
  8585. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8586. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8587. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8588. end;
  8589. else
  8590. Break;
  8591. end;
  8592. A_IDIV:
  8593. case taicpu(hp1).ops of
  8594. 3:
  8595. begin
  8596. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8597. { Has to be an exact match on the register }
  8598. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8599. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8600. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8601. { Is it in the negative range? }
  8602. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8603. Break;
  8604. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8605. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8606. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8607. end;
  8608. else
  8609. Break;
  8610. end;
  8611. *)
  8612. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8613. begin
  8614. { If there are no instructions in between, then we might be able to make a saving }
  8615. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8616. Break;
  8617. { We have something like:
  8618. movzbw %dl,%dx
  8619. ...
  8620. movswl %dx,%edx
  8621. Change the latter to a zero-extension then enter the
  8622. A_MOVZX case branch.
  8623. }
  8624. {$ifdef x86_64}
  8625. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8626. begin
  8627. { this becomes a zero extension from 32-bit to 64-bit, but
  8628. the upper 32 bits are already zero, so just delete the
  8629. instruction }
  8630. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8631. RemoveInstruction(hp1);
  8632. Result := True;
  8633. Exit;
  8634. end
  8635. else
  8636. {$endif x86_64}
  8637. begin
  8638. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8639. taicpu(hp1).opcode := A_MOVZX;
  8640. {$ifdef x86_64}
  8641. case taicpu(hp1).opsize of
  8642. S_BQ:
  8643. begin
  8644. taicpu(hp1).opsize := S_BL;
  8645. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8646. end;
  8647. S_WQ:
  8648. begin
  8649. taicpu(hp1).opsize := S_WL;
  8650. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8651. end;
  8652. S_LQ:
  8653. begin
  8654. taicpu(hp1).opcode := A_MOV;
  8655. taicpu(hp1).opsize := S_L;
  8656. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8657. { In this instance, we need to break out because the
  8658. instruction is no longer MOVZX or MOVSXD }
  8659. Result := True;
  8660. Exit;
  8661. end;
  8662. else
  8663. ;
  8664. end;
  8665. {$endif x86_64}
  8666. Result := CompressInstructions;
  8667. Exit;
  8668. end;
  8669. end;
  8670. A_MOVZX:
  8671. begin
  8672. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8673. Break;
  8674. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8675. begin
  8676. if (InstrMax = -1) and
  8677. { Will return false if the second parameter isn't ThisReg
  8678. (can happen on -O2 and under) }
  8679. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8680. begin
  8681. { The two MOVZX instructions are adjacent, so remove the first one }
  8682. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8683. RemoveCurrentP(p);
  8684. Result := True;
  8685. Exit;
  8686. end;
  8687. Break;
  8688. end;
  8689. Result := CompressInstructions;
  8690. Exit;
  8691. end;
  8692. else
  8693. { This includes ADC, SBB and IDIV }
  8694. Break;
  8695. end;
  8696. if not CheckOverflowConditions then
  8697. Break;
  8698. { Contains highest index (so instruction count - 1) }
  8699. Inc(InstrMax);
  8700. if InstrMax > High(InstrList) then
  8701. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8702. InstrList[InstrMax] := taicpu(hp1);
  8703. end;
  8704. end;
  8705. {$pop}
  8706. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8707. var
  8708. hp1 : tai;
  8709. begin
  8710. Result:=false;
  8711. if (taicpu(p).ops >= 2) and
  8712. ((taicpu(p).oper[0]^.typ = top_const) or
  8713. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8714. (taicpu(p).oper[1]^.typ = top_reg) and
  8715. ((taicpu(p).ops = 2) or
  8716. ((taicpu(p).oper[2]^.typ = top_reg) and
  8717. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8718. GetLastInstruction(p,hp1) and
  8719. MatchInstruction(hp1,A_MOV,[]) and
  8720. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8721. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8722. begin
  8723. TransferUsedRegs(TmpUsedRegs);
  8724. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8725. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8726. { change
  8727. mov reg1,reg2
  8728. imul y,reg2 to imul y,reg1,reg2 }
  8729. begin
  8730. taicpu(p).ops := 3;
  8731. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8732. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8733. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8734. RemoveInstruction(hp1);
  8735. result:=true;
  8736. end;
  8737. end;
  8738. end;
  8739. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8740. var
  8741. ThisLabel: TAsmLabel;
  8742. begin
  8743. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8744. ThisLabel.decrefs;
  8745. taicpu(p).opcode := A_RET;
  8746. taicpu(p).is_jmp := false;
  8747. taicpu(p).ops := taicpu(ret_p).ops;
  8748. case taicpu(ret_p).ops of
  8749. 0:
  8750. taicpu(p).clearop(0);
  8751. 1:
  8752. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8753. else
  8754. internalerror(2016041301);
  8755. end;
  8756. { If the original label is now dead, it might turn out that the label
  8757. immediately follows p. As a result, everything beyond it, which will
  8758. be just some final register configuration and a RET instruction, is
  8759. now dead code. [Kit] }
  8760. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8761. running RemoveDeadCodeAfterJump for each RET instruction, because
  8762. this optimisation rarely happens and most RETs appear at the end of
  8763. routines where there is nothing that can be stripped. [Kit] }
  8764. if not ThisLabel.is_used then
  8765. RemoveDeadCodeAfterJump(p);
  8766. end;
  8767. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8768. var
  8769. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8770. Unconditional, PotentialModified: Boolean;
  8771. OperPtr: POper;
  8772. NewRef: TReference;
  8773. InstrList: array of taicpu;
  8774. InstrMax, Index: Integer;
  8775. const
  8776. {$ifdef DEBUG_AOPTCPU}
  8777. SNoFlags: shortstring = ' so the flags aren''t modified';
  8778. {$else DEBUG_AOPTCPU}
  8779. SNoFlags = '';
  8780. {$endif DEBUG_AOPTCPU}
  8781. begin
  8782. Result:=false;
  8783. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8784. begin
  8785. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8786. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8787. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8788. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8789. GetNextInstruction(hp1, hp2) and
  8790. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8791. { Change from: To:
  8792. set(C) %reg j(~C) label
  8793. test %reg,%reg/cmp $0,%reg
  8794. je label
  8795. set(C) %reg j(C) label
  8796. test %reg,%reg/cmp $0,%reg
  8797. jne label
  8798. (Also do something similar with sete/setne instead of je/jne)
  8799. }
  8800. begin
  8801. { Before we do anything else, we need to check the instructions
  8802. in between SETcc and TEST to make sure they don't modify the
  8803. FLAGS register - if -O2 or under, there won't be any
  8804. instructions between SET and TEST }
  8805. TransferUsedRegs(TmpUsedRegs);
  8806. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8807. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8808. begin
  8809. next := p;
  8810. SetLength(InstrList, 0);
  8811. InstrMax := -1;
  8812. PotentialModified := False;
  8813. { Make a note of every instruction that modifies the FLAGS
  8814. register }
  8815. while GetNextInstruction(next, next) and (next <> hp1) do
  8816. begin
  8817. if next.typ <> ait_instruction then
  8818. { GetNextInstructionUsingReg should have returned False }
  8819. InternalError(2021051701);
  8820. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8821. begin
  8822. case taicpu(next).opcode of
  8823. A_SETcc,
  8824. A_CMOVcc,
  8825. A_Jcc:
  8826. begin
  8827. if PotentialModified then
  8828. { Not safe because the flags were modified earlier }
  8829. Exit
  8830. else
  8831. { Condition is the same as the initial SETcc, so this is safe
  8832. (don't add to instruction list though) }
  8833. Continue;
  8834. end;
  8835. A_ADD:
  8836. begin
  8837. if (taicpu(next).opsize = S_B) or
  8838. { LEA doesn't support 8-bit operands }
  8839. (taicpu(next).oper[1]^.typ <> top_reg) or
  8840. { Must write to a register }
  8841. (taicpu(next).oper[0]^.typ = top_ref) then
  8842. { Require a constant or a register }
  8843. Exit;
  8844. PotentialModified := True;
  8845. end;
  8846. A_SUB:
  8847. begin
  8848. if (taicpu(next).opsize = S_B) or
  8849. { LEA doesn't support 8-bit operands }
  8850. (taicpu(next).oper[1]^.typ <> top_reg) or
  8851. { Must write to a register }
  8852. (taicpu(next).oper[0]^.typ <> top_const) or
  8853. (taicpu(next).oper[0]^.val = $80000000) then
  8854. { Can't subtract a register with LEA - also
  8855. check that the value isn't -2^31, as this
  8856. can't be negated }
  8857. Exit;
  8858. PotentialModified := True;
  8859. end;
  8860. A_SAL,
  8861. A_SHL:
  8862. begin
  8863. if (taicpu(next).opsize = S_B) or
  8864. { LEA doesn't support 8-bit operands }
  8865. (taicpu(next).oper[1]^.typ <> top_reg) or
  8866. { Must write to a register }
  8867. (taicpu(next).oper[0]^.typ <> top_const) or
  8868. (taicpu(next).oper[0]^.val < 0) or
  8869. (taicpu(next).oper[0]^.val > 3) then
  8870. Exit;
  8871. PotentialModified := True;
  8872. end;
  8873. A_IMUL:
  8874. begin
  8875. if (taicpu(next).ops <> 3) or
  8876. (taicpu(next).oper[1]^.typ <> top_reg) or
  8877. { Must write to a register }
  8878. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8879. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8880. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8881. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8882. Exit
  8883. else
  8884. PotentialModified := True;
  8885. end;
  8886. else
  8887. { Don't know how to change this, so abort }
  8888. Exit;
  8889. end;
  8890. { Contains highest index (so instruction count - 1) }
  8891. Inc(InstrMax);
  8892. if InstrMax > High(InstrList) then
  8893. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8894. InstrList[InstrMax] := taicpu(next);
  8895. end;
  8896. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8897. end;
  8898. if not Assigned(next) or (next <> hp1) then
  8899. { It should be equal to hp1 }
  8900. InternalError(2021051702);
  8901. { Cycle through each instruction and check to see if we can
  8902. change them to versions that don't modify the flags }
  8903. if (InstrMax >= 0) then
  8904. begin
  8905. for Index := 0 to InstrMax do
  8906. case InstrList[Index].opcode of
  8907. A_ADD:
  8908. begin
  8909. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8910. InstrList[Index].opcode := A_LEA;
  8911. reference_reset(NewRef, 1, []);
  8912. NewRef.base := InstrList[Index].oper[1]^.reg;
  8913. if InstrList[Index].oper[0]^.typ = top_reg then
  8914. begin
  8915. NewRef.index := InstrList[Index].oper[0]^.reg;
  8916. NewRef.scalefactor := 1;
  8917. end
  8918. else
  8919. NewRef.offset := InstrList[Index].oper[0]^.val;
  8920. InstrList[Index].loadref(0, NewRef);
  8921. end;
  8922. A_SUB:
  8923. begin
  8924. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8925. InstrList[Index].opcode := A_LEA;
  8926. reference_reset(NewRef, 1, []);
  8927. NewRef.base := InstrList[Index].oper[1]^.reg;
  8928. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8929. InstrList[Index].loadref(0, NewRef);
  8930. end;
  8931. A_SHL,
  8932. A_SAL:
  8933. begin
  8934. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8935. InstrList[Index].opcode := A_LEA;
  8936. reference_reset(NewRef, 1, []);
  8937. NewRef.index := InstrList[Index].oper[1]^.reg;
  8938. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8939. InstrList[Index].loadref(0, NewRef);
  8940. end;
  8941. A_IMUL:
  8942. begin
  8943. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8944. InstrList[Index].opcode := A_LEA;
  8945. reference_reset(NewRef, 1, []);
  8946. NewRef.index := InstrList[Index].oper[1]^.reg;
  8947. case InstrList[Index].oper[0]^.val of
  8948. 2, 4, 8:
  8949. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8950. else {3, 5 and 9}
  8951. begin
  8952. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8953. NewRef.base := InstrList[Index].oper[1]^.reg;
  8954. end;
  8955. end;
  8956. InstrList[Index].loadref(0, NewRef);
  8957. end;
  8958. else
  8959. InternalError(2021051710);
  8960. end;
  8961. end;
  8962. { Mark the FLAGS register as used across this whole block }
  8963. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8964. end;
  8965. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8966. JumpC := taicpu(hp2).condition;
  8967. Unconditional := False;
  8968. if conditions_equal(JumpC, C_E) then
  8969. SetC := inverse_cond(taicpu(p).condition)
  8970. else if conditions_equal(JumpC, C_NE) then
  8971. SetC := taicpu(p).condition
  8972. else
  8973. { We've got something weird here (and inefficent) }
  8974. begin
  8975. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8976. SetC := C_NONE;
  8977. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8978. if condition_in(C_AE, JumpC) then
  8979. Unconditional := True
  8980. else
  8981. { Not sure what to do with this jump - drop out }
  8982. Exit;
  8983. end;
  8984. RemoveInstruction(hp1);
  8985. if Unconditional then
  8986. MakeUnconditional(taicpu(hp2))
  8987. else
  8988. begin
  8989. if SetC = C_NONE then
  8990. InternalError(2018061402);
  8991. taicpu(hp2).SetCondition(SetC);
  8992. end;
  8993. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8994. TmpUsedRegs }
  8995. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8996. begin
  8997. RemoveCurrentp(p, hp2);
  8998. if taicpu(hp2).opcode = A_SETcc then
  8999. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9000. else
  9001. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9002. end
  9003. else
  9004. if taicpu(hp2).opcode = A_SETcc then
  9005. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9006. else
  9007. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9008. Result := True;
  9009. end
  9010. else if
  9011. { Make sure the instructions are adjacent }
  9012. (
  9013. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9014. GetNextInstruction(p, hp1)
  9015. ) and
  9016. MatchInstruction(hp1, A_MOV, [S_B]) and
  9017. { Writing to memory is allowed }
  9018. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9019. begin
  9020. {
  9021. Watch out for sequences such as:
  9022. set(c)b %regb
  9023. movb %regb,(ref)
  9024. movb $0,1(ref)
  9025. movb $0,2(ref)
  9026. movb $0,3(ref)
  9027. Much more efficient to turn it into:
  9028. movl $0,%regl
  9029. set(c)b %regb
  9030. movl %regl,(ref)
  9031. Or:
  9032. set(c)b %regb
  9033. movzbl %regb,%regl
  9034. movl %regl,(ref)
  9035. }
  9036. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9037. GetNextInstruction(hp1, hp2) and
  9038. MatchInstruction(hp2, A_MOV, [S_B]) and
  9039. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9040. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9041. begin
  9042. { Don't do anything else except set Result to True }
  9043. end
  9044. else
  9045. begin
  9046. if taicpu(p).oper[0]^.typ = top_reg then
  9047. begin
  9048. TransferUsedRegs(TmpUsedRegs);
  9049. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9050. end;
  9051. { If it's not a register, it's a memory address }
  9052. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9053. begin
  9054. { Even if the register is still in use, we can minimise the
  9055. pipeline stall by changing the MOV into another SETcc. }
  9056. taicpu(hp1).opcode := A_SETcc;
  9057. taicpu(hp1).condition := taicpu(p).condition;
  9058. if taicpu(hp1).oper[1]^.typ = top_ref then
  9059. begin
  9060. { Swapping the operand pointers like this is probably a
  9061. bit naughty, but it is far faster than using loadoper
  9062. to transfer the reference from oper[1] to oper[0] if
  9063. you take into account the extra procedure calls and
  9064. the memory allocation and deallocation required }
  9065. OperPtr := taicpu(hp1).oper[1];
  9066. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9067. taicpu(hp1).oper[0] := OperPtr;
  9068. end
  9069. else
  9070. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9071. taicpu(hp1).clearop(1);
  9072. taicpu(hp1).ops := 1;
  9073. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9074. end
  9075. else
  9076. begin
  9077. if taicpu(hp1).oper[1]^.typ = top_reg then
  9078. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9079. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9080. RemoveInstruction(hp1);
  9081. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9082. end
  9083. end;
  9084. Result := True;
  9085. end;
  9086. end;
  9087. end;
  9088. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9089. var
  9090. hp1: tai;
  9091. Count: Integer;
  9092. OrigLabel: TAsmLabel;
  9093. begin
  9094. result := False;
  9095. { Sometimes, the optimisations below can permit this }
  9096. RemoveDeadCodeAfterJump(p);
  9097. 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
  9098. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9099. begin
  9100. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9101. { Also a side-effect of optimisations }
  9102. if CollapseZeroDistJump(p, OrigLabel) then
  9103. begin
  9104. Result := True;
  9105. Exit;
  9106. end;
  9107. hp1 := GetLabelWithSym(OrigLabel);
  9108. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9109. begin
  9110. case taicpu(hp1).opcode of
  9111. A_RET:
  9112. {
  9113. change
  9114. jmp .L1
  9115. ...
  9116. .L1:
  9117. ret
  9118. into
  9119. ret
  9120. }
  9121. begin
  9122. ConvertJumpToRET(p, hp1);
  9123. result:=true;
  9124. end;
  9125. { Check any kind of direct assignment instruction }
  9126. A_MOV,
  9127. A_MOVD,
  9128. A_MOVQ,
  9129. A_MOVSX,
  9130. {$ifdef x86_64}
  9131. A_MOVSXD,
  9132. {$endif x86_64}
  9133. A_MOVZX,
  9134. A_MOVAPS,
  9135. A_MOVUPS,
  9136. A_MOVSD,
  9137. A_MOVAPD,
  9138. A_MOVUPD,
  9139. A_MOVDQA,
  9140. A_MOVDQU,
  9141. A_VMOVSS,
  9142. A_VMOVAPS,
  9143. A_VMOVUPS,
  9144. A_VMOVSD,
  9145. A_VMOVAPD,
  9146. A_VMOVUPD,
  9147. A_VMOVDQA,
  9148. A_VMOVDQU:
  9149. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9150. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9151. begin
  9152. Result := True;
  9153. Exit;
  9154. end;
  9155. else
  9156. ;
  9157. end;
  9158. end;
  9159. end;
  9160. end;
  9161. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9162. begin
  9163. CanBeCMOV:=assigned(p) and
  9164. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9165. { we can't use cmov ref,reg because
  9166. ref could be nil and cmov still throws an exception
  9167. if ref=nil but the mov isn't done (FK)
  9168. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9169. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9170. }
  9171. (taicpu(p).oper[1]^.typ = top_reg) and
  9172. (
  9173. (taicpu(p).oper[0]^.typ = top_reg) or
  9174. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9175. it is not expected that this can cause a seg. violation }
  9176. (
  9177. (taicpu(p).oper[0]^.typ = top_ref) and
  9178. IsRefSafe(taicpu(p).oper[0]^.ref)
  9179. )
  9180. );
  9181. end;
  9182. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9183. var
  9184. hp1,hp2: tai;
  9185. {$ifndef i8086}
  9186. hp3,hp4,hpmov2, hp5: tai;
  9187. l : Longint;
  9188. condition : TAsmCond;
  9189. {$endif i8086}
  9190. carryadd_opcode : TAsmOp;
  9191. symbol: TAsmSymbol;
  9192. increg, tmpreg: TRegister;
  9193. begin
  9194. result:=false;
  9195. if GetNextInstruction(p,hp1) then
  9196. begin
  9197. if (hp1.typ=ait_label) then
  9198. begin
  9199. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9200. Exit;
  9201. end
  9202. else if (hp1.typ<>ait_instruction) then
  9203. Exit;
  9204. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9205. if (
  9206. (
  9207. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9208. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9209. (Taicpu(hp1).oper[0]^.val=1)
  9210. ) or
  9211. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9212. ) and
  9213. GetNextInstruction(hp1,hp2) and
  9214. SkipAligns(hp2, hp2) and
  9215. (hp2.typ = ait_label) and
  9216. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9217. { jb @@1 cmc
  9218. inc/dec operand --> adc/sbb operand,0
  9219. @@1:
  9220. ... and ...
  9221. jnb @@1
  9222. inc/dec operand --> adc/sbb operand,0
  9223. @@1: }
  9224. begin
  9225. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9226. begin
  9227. case taicpu(hp1).opcode of
  9228. A_INC,
  9229. A_ADD:
  9230. carryadd_opcode:=A_ADC;
  9231. A_DEC,
  9232. A_SUB:
  9233. carryadd_opcode:=A_SBB;
  9234. else
  9235. InternalError(2021011001);
  9236. end;
  9237. Taicpu(p).clearop(0);
  9238. Taicpu(p).ops:=0;
  9239. Taicpu(p).is_jmp:=false;
  9240. Taicpu(p).opcode:=A_CMC;
  9241. Taicpu(p).condition:=C_NONE;
  9242. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9243. Taicpu(hp1).ops:=2;
  9244. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9245. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9246. else
  9247. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9248. Taicpu(hp1).loadconst(0,0);
  9249. Taicpu(hp1).opcode:=carryadd_opcode;
  9250. result:=true;
  9251. exit;
  9252. end
  9253. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9254. begin
  9255. case taicpu(hp1).opcode of
  9256. A_INC,
  9257. A_ADD:
  9258. carryadd_opcode:=A_ADC;
  9259. A_DEC,
  9260. A_SUB:
  9261. carryadd_opcode:=A_SBB;
  9262. else
  9263. InternalError(2021011002);
  9264. end;
  9265. Taicpu(hp1).ops:=2;
  9266. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9267. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9268. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9269. else
  9270. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9271. Taicpu(hp1).loadconst(0,0);
  9272. Taicpu(hp1).opcode:=carryadd_opcode;
  9273. RemoveCurrentP(p, hp1);
  9274. result:=true;
  9275. exit;
  9276. end
  9277. {
  9278. jcc @@1 setcc tmpreg
  9279. inc/dec/add/sub operand -> (movzx tmpreg)
  9280. @@1: add/sub tmpreg,operand
  9281. While this increases code size slightly, it makes the code much faster if the
  9282. jump is unpredictable
  9283. }
  9284. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9285. begin
  9286. { search for an available register which is volatile }
  9287. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9288. if increg <> NR_NO then
  9289. begin
  9290. { We don't need to check if tmpreg is in hp1 or not, because
  9291. it will be marked as in use at p (if not, this is
  9292. indictive of a compiler bug). }
  9293. TAsmLabel(symbol).decrefs;
  9294. Taicpu(p).clearop(0);
  9295. Taicpu(p).ops:=1;
  9296. Taicpu(p).is_jmp:=false;
  9297. Taicpu(p).opcode:=A_SETcc;
  9298. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9299. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9300. Taicpu(p).loadreg(0,increg);
  9301. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9302. begin
  9303. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9304. R_SUBW:
  9305. begin
  9306. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9307. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9308. end;
  9309. R_SUBD:
  9310. begin
  9311. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9312. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9313. end;
  9314. {$ifdef x86_64}
  9315. R_SUBQ:
  9316. begin
  9317. { MOVZX doesn't have a 64-bit variant, because
  9318. the 32-bit version implicitly zeroes the
  9319. upper 32-bits of the destination register }
  9320. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9321. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9322. setsubreg(tmpreg, R_SUBQ);
  9323. end;
  9324. {$endif x86_64}
  9325. else
  9326. Internalerror(2020030601);
  9327. end;
  9328. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9329. asml.InsertAfter(hp2,p);
  9330. end
  9331. else
  9332. tmpreg := increg;
  9333. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9334. begin
  9335. Taicpu(hp1).ops:=2;
  9336. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9337. end;
  9338. Taicpu(hp1).loadreg(0,tmpreg);
  9339. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9340. Result := True;
  9341. { p is no longer a Jcc instruction, so exit }
  9342. Exit;
  9343. end;
  9344. end;
  9345. end;
  9346. { Detect the following:
  9347. jmp<cond> @Lbl1
  9348. jmp @Lbl2
  9349. ...
  9350. @Lbl1:
  9351. ret
  9352. Change to:
  9353. jmp<inv_cond> @Lbl2
  9354. ret
  9355. }
  9356. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9357. begin
  9358. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9359. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9360. MatchInstruction(hp2,A_RET,[S_NO]) then
  9361. begin
  9362. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9363. { Change label address to that of the unconditional jump }
  9364. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9365. TAsmLabel(symbol).DecRefs;
  9366. taicpu(hp1).opcode := A_RET;
  9367. taicpu(hp1).is_jmp := false;
  9368. taicpu(hp1).ops := taicpu(hp2).ops;
  9369. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9370. case taicpu(hp2).ops of
  9371. 0:
  9372. taicpu(hp1).clearop(0);
  9373. 1:
  9374. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9375. else
  9376. internalerror(2016041302);
  9377. end;
  9378. end;
  9379. {$ifndef i8086}
  9380. end
  9381. {
  9382. convert
  9383. j<c> .L1
  9384. mov 1,reg
  9385. jmp .L2
  9386. .L1
  9387. mov 0,reg
  9388. .L2
  9389. into
  9390. mov 0,reg
  9391. set<not(c)> reg
  9392. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9393. would destroy the flag contents
  9394. }
  9395. else if MatchInstruction(hp1,A_MOV,[]) and
  9396. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9397. {$ifdef i386}
  9398. (
  9399. { Under i386, ESI, EDI, EBP and ESP
  9400. don't have an 8-bit representation }
  9401. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9402. ) and
  9403. {$endif i386}
  9404. (taicpu(hp1).oper[0]^.val=1) and
  9405. GetNextInstruction(hp1,hp2) and
  9406. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9407. GetNextInstruction(hp2,hp3) and
  9408. { skip align }
  9409. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9410. (hp3.typ=ait_label) and
  9411. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9412. (tai_label(hp3).labsym.getrefs=1) and
  9413. GetNextInstruction(hp3,hp4) and
  9414. MatchInstruction(hp4,A_MOV,[]) and
  9415. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9416. (taicpu(hp4).oper[0]^.val=0) and
  9417. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9418. GetNextInstruction(hp4,hp5) and
  9419. (hp5.typ=ait_label) and
  9420. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9421. (tai_label(hp5).labsym.getrefs=1) then
  9422. begin
  9423. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9424. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9425. { remove last label }
  9426. RemoveInstruction(hp5);
  9427. { remove second label }
  9428. RemoveInstruction(hp3);
  9429. { if align is present remove it }
  9430. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9431. RemoveInstruction(hp3);
  9432. { remove jmp }
  9433. RemoveInstruction(hp2);
  9434. if taicpu(hp1).opsize=S_B then
  9435. RemoveInstruction(hp1)
  9436. else
  9437. taicpu(hp1).loadconst(0,0);
  9438. taicpu(hp4).opcode:=A_SETcc;
  9439. taicpu(hp4).opsize:=S_B;
  9440. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9441. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9442. taicpu(hp4).opercnt:=1;
  9443. taicpu(hp4).ops:=1;
  9444. taicpu(hp4).freeop(1);
  9445. RemoveCurrentP(p);
  9446. Result:=true;
  9447. exit;
  9448. end
  9449. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9450. begin
  9451. { check for
  9452. jCC xxx
  9453. <several movs>
  9454. xxx:
  9455. Also spot:
  9456. Jcc xxx
  9457. <several movs>
  9458. jmp xxx
  9459. Change to:
  9460. <several cmovs with inverted condition>
  9461. jmp xxx
  9462. }
  9463. l:=0;
  9464. while assigned(hp1) and
  9465. CanBeCMOV(hp1) and
  9466. { stop on labels }
  9467. not(hp1.typ=ait_label) do
  9468. begin
  9469. inc(l);
  9470. hp5 := hp1;
  9471. GetNextInstruction(hp1,hp1);
  9472. end;
  9473. if assigned(hp1) then
  9474. begin
  9475. TransferUsedRegs(TmpUsedRegs);
  9476. if (
  9477. MatchInstruction(hp1, A_JMP, []) and
  9478. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9479. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9480. ) or
  9481. FindLabel(tasmlabel(symbol),hp1) then
  9482. begin
  9483. if (l<=4) and (l>0) then
  9484. begin
  9485. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9486. condition:=inverse_cond(taicpu(p).condition);
  9487. UpdateUsedRegs(tai(p.next));
  9488. GetNextInstruction(p,hp1);
  9489. repeat
  9490. if not Assigned(hp1) then
  9491. InternalError(2018062900);
  9492. taicpu(hp1).opcode:=A_CMOVcc;
  9493. taicpu(hp1).condition:=condition;
  9494. UpdateUsedRegs(tai(hp1.next));
  9495. GetNextInstruction(hp1,hp1);
  9496. until not(CanBeCMOV(hp1));
  9497. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9498. hp2 := hp1;
  9499. repeat
  9500. if not Assigned(hp2) then
  9501. InternalError(2018062910);
  9502. case hp2.typ of
  9503. ait_label:
  9504. { What we expected - break out of the loop (it won't be a dead label at the top of
  9505. a cluster because that was optimised at an earlier stage) }
  9506. Break;
  9507. ait_align:
  9508. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9509. begin
  9510. hp2 := tai(hp2.Next);
  9511. Continue;
  9512. end;
  9513. ait_instruction:
  9514. begin
  9515. if taicpu(hp2).opcode<>A_JMP then
  9516. InternalError(2018062912);
  9517. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9518. Break;
  9519. end
  9520. else
  9521. begin
  9522. { Might be a comment or temporary allocation entry }
  9523. if not (hp2.typ in SkipInstr) then
  9524. InternalError(2018062911);
  9525. hp2 := tai(hp2.Next);
  9526. Continue;
  9527. end;
  9528. end;
  9529. until False;
  9530. { Now we can safely decrement the reference count }
  9531. tasmlabel(symbol).decrefs;
  9532. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9533. { Remove the original jump }
  9534. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9535. if hp2.typ=ait_instruction then
  9536. begin
  9537. p:=hp2;
  9538. Result:=True;
  9539. end
  9540. else
  9541. begin
  9542. UpdateUsedRegs(tai(hp2.next));
  9543. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9544. { Remove the label if this is its final reference }
  9545. if (tasmlabel(symbol).getrefs=0) then
  9546. StripLabelFast(hp1);
  9547. end;
  9548. exit;
  9549. end;
  9550. end
  9551. else
  9552. begin
  9553. { check further for
  9554. jCC xxx
  9555. <several movs 1>
  9556. jmp yyy
  9557. xxx:
  9558. <several movs 2>
  9559. yyy:
  9560. }
  9561. { hp2 points to jmp yyy }
  9562. hp2:=hp1;
  9563. { skip hp1 to xxx (or an align right before it) }
  9564. GetNextInstruction(hp1, hp1);
  9565. if assigned(hp2) and
  9566. assigned(hp1) and
  9567. (l<=3) and
  9568. (hp2.typ=ait_instruction) and
  9569. (taicpu(hp2).is_jmp) and
  9570. (taicpu(hp2).condition=C_None) and
  9571. { real label and jump, no further references to the
  9572. label are allowed }
  9573. (tasmlabel(symbol).getrefs=1) and
  9574. FindLabel(tasmlabel(symbol),hp1) then
  9575. begin
  9576. l:=0;
  9577. { skip hp1 to <several moves 2> }
  9578. if (hp1.typ = ait_align) then
  9579. GetNextInstruction(hp1, hp1);
  9580. GetNextInstruction(hp1, hpmov2);
  9581. hp1 := hpmov2;
  9582. while assigned(hp1) and
  9583. CanBeCMOV(hp1) do
  9584. begin
  9585. inc(l);
  9586. hp5 := hp1;
  9587. GetNextInstruction(hp1, hp1);
  9588. end;
  9589. { hp1 points to yyy (or an align right before it) }
  9590. hp3 := hp1;
  9591. if assigned(hp1) and
  9592. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9593. begin
  9594. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9595. condition:=inverse_cond(taicpu(p).condition);
  9596. UpdateUsedRegs(tai(p.next));
  9597. GetNextInstruction(p,hp1);
  9598. repeat
  9599. taicpu(hp1).opcode:=A_CMOVcc;
  9600. taicpu(hp1).condition:=condition;
  9601. UpdateUsedRegs(tai(hp1.next));
  9602. GetNextInstruction(hp1,hp1);
  9603. until not(assigned(hp1)) or
  9604. not(CanBeCMOV(hp1));
  9605. condition:=inverse_cond(condition);
  9606. if GetLastInstruction(hpmov2,hp1) then
  9607. UpdateUsedRegs(tai(hp1.next));
  9608. hp1 := hpmov2;
  9609. { hp1 is now at <several movs 2> }
  9610. while Assigned(hp1) and CanBeCMOV(hp1) do
  9611. begin
  9612. taicpu(hp1).opcode:=A_CMOVcc;
  9613. taicpu(hp1).condition:=condition;
  9614. UpdateUsedRegs(tai(hp1.next));
  9615. GetNextInstruction(hp1,hp1);
  9616. end;
  9617. hp1 := p;
  9618. { Get first instruction after label }
  9619. UpdateUsedRegs(tai(hp3.next));
  9620. GetNextInstruction(hp3, p);
  9621. if assigned(p) and (hp3.typ = ait_align) then
  9622. GetNextInstruction(p, p);
  9623. { Don't dereference yet, as doing so will cause
  9624. GetNextInstruction to skip the label and
  9625. optional align marker. [Kit] }
  9626. GetNextInstruction(hp2, hp4);
  9627. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9628. { remove jCC }
  9629. RemoveInstruction(hp1);
  9630. { Now we can safely decrement it }
  9631. tasmlabel(symbol).decrefs;
  9632. { Remove label xxx (it will have a ref of zero due to the initial check }
  9633. StripLabelFast(hp4);
  9634. { remove jmp }
  9635. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9636. RemoveInstruction(hp2);
  9637. { As before, now we can safely decrement it }
  9638. tasmlabel(symbol).decrefs;
  9639. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9640. if tasmlabel(symbol).getrefs = 0 then
  9641. StripLabelFast(hp3);
  9642. if Assigned(p) then
  9643. result:=true;
  9644. exit;
  9645. end;
  9646. end;
  9647. end;
  9648. end;
  9649. {$endif i8086}
  9650. end;
  9651. end;
  9652. end;
  9653. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9654. var
  9655. hp1,hp2,hp3: tai;
  9656. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9657. NewSize: TOpSize;
  9658. NewRegSize: TSubRegister;
  9659. Limit: TCgInt;
  9660. SwapOper: POper;
  9661. begin
  9662. result:=false;
  9663. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9664. GetNextInstruction(p,hp1) and
  9665. (hp1.typ = ait_instruction);
  9666. if reg_and_hp1_is_instr and
  9667. (
  9668. (taicpu(hp1).opcode <> A_LEA) or
  9669. { If the LEA instruction can be converted into an arithmetic instruction,
  9670. it may be possible to then fold it. }
  9671. (
  9672. { If the flags register is in use, don't change the instruction
  9673. to an ADD otherwise this will scramble the flags. [Kit] }
  9674. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9675. ConvertLEA(taicpu(hp1))
  9676. )
  9677. ) and
  9678. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9679. GetNextInstruction(hp1,hp2) and
  9680. MatchInstruction(hp2,A_MOV,[]) and
  9681. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9682. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9683. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9684. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9685. {$ifdef i386}
  9686. { not all registers have byte size sub registers on i386 }
  9687. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9688. {$endif i386}
  9689. (((taicpu(hp1).ops=2) and
  9690. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9691. ((taicpu(hp1).ops=1) and
  9692. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9693. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9694. begin
  9695. { change movsX/movzX reg/ref, reg2
  9696. add/sub/or/... reg3/$const, reg2
  9697. mov reg2 reg/ref
  9698. to add/sub/or/... reg3/$const, reg/ref }
  9699. { by example:
  9700. movswl %si,%eax movswl %si,%eax p
  9701. decl %eax addl %edx,%eax hp1
  9702. movw %ax,%si movw %ax,%si hp2
  9703. ->
  9704. movswl %si,%eax movswl %si,%eax p
  9705. decw %eax addw %edx,%eax hp1
  9706. movw %ax,%si movw %ax,%si hp2
  9707. }
  9708. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9709. {
  9710. ->
  9711. movswl %si,%eax movswl %si,%eax p
  9712. decw %si addw %dx,%si hp1
  9713. movw %ax,%si movw %ax,%si hp2
  9714. }
  9715. case taicpu(hp1).ops of
  9716. 1:
  9717. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9718. 2:
  9719. begin
  9720. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9721. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9722. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9723. end;
  9724. else
  9725. internalerror(2008042702);
  9726. end;
  9727. {
  9728. ->
  9729. decw %si addw %dx,%si p
  9730. }
  9731. DebugMsg(SPeepholeOptimization + 'var3',p);
  9732. RemoveCurrentP(p, hp1);
  9733. RemoveInstruction(hp2);
  9734. Result := True;
  9735. Exit;
  9736. end;
  9737. if reg_and_hp1_is_instr and
  9738. (taicpu(hp1).opcode = A_MOV) and
  9739. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9740. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9741. {$ifdef x86_64}
  9742. { check for implicit extension to 64 bit }
  9743. or
  9744. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9745. (taicpu(hp1).opsize=S_Q) and
  9746. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9747. )
  9748. {$endif x86_64}
  9749. )
  9750. then
  9751. begin
  9752. { change
  9753. movx %reg1,%reg2
  9754. mov %reg2,%reg3
  9755. dealloc %reg2
  9756. into
  9757. movx %reg,%reg3
  9758. }
  9759. TransferUsedRegs(TmpUsedRegs);
  9760. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9761. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9762. begin
  9763. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9764. {$ifdef x86_64}
  9765. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9766. (taicpu(hp1).opsize=S_Q) then
  9767. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9768. else
  9769. {$endif x86_64}
  9770. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9771. RemoveInstruction(hp1);
  9772. Result := True;
  9773. Exit;
  9774. end;
  9775. end;
  9776. if reg_and_hp1_is_instr and
  9777. ((taicpu(hp1).opcode=A_MOV) or
  9778. (taicpu(hp1).opcode=A_ADD) or
  9779. (taicpu(hp1).opcode=A_SUB) or
  9780. (taicpu(hp1).opcode=A_CMP) or
  9781. (taicpu(hp1).opcode=A_OR) or
  9782. (taicpu(hp1).opcode=A_XOR) or
  9783. (taicpu(hp1).opcode=A_AND)
  9784. ) and
  9785. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9786. begin
  9787. AndTest := (taicpu(hp1).opcode=A_AND) and
  9788. GetNextInstruction(hp1, hp2) and
  9789. (hp2.typ = ait_instruction) and
  9790. (
  9791. (
  9792. (taicpu(hp2).opcode=A_TEST) and
  9793. (
  9794. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9795. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9796. (
  9797. { If the AND and TEST instructions share a constant, this is also valid }
  9798. (taicpu(hp1).oper[0]^.typ = top_const) and
  9799. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9800. )
  9801. ) and
  9802. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9803. ) or
  9804. (
  9805. (taicpu(hp2).opcode=A_CMP) and
  9806. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9807. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9808. )
  9809. );
  9810. { change
  9811. movx (oper),%reg2
  9812. and $x,%reg2
  9813. test %reg2,%reg2
  9814. dealloc %reg2
  9815. into
  9816. op %reg1,%reg3
  9817. if the second op accesses only the bits stored in reg1
  9818. }
  9819. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9820. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9821. (taicpu(hp1).oper[0]^.typ = top_const) and
  9822. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9823. AndTest then
  9824. begin
  9825. { Check if the AND constant is in range }
  9826. case taicpu(p).opsize of
  9827. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9828. begin
  9829. NewSize := S_B;
  9830. Limit := $FF;
  9831. end;
  9832. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9833. begin
  9834. NewSize := S_W;
  9835. Limit := $FFFF;
  9836. end;
  9837. {$ifdef x86_64}
  9838. S_LQ:
  9839. begin
  9840. NewSize := S_L;
  9841. Limit := $FFFFFFFF;
  9842. end;
  9843. {$endif x86_64}
  9844. else
  9845. InternalError(2021120303);
  9846. end;
  9847. if (
  9848. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9849. { Check for negative operands }
  9850. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9851. ) and
  9852. GetNextInstruction(hp2,hp3) and
  9853. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9854. (taicpu(hp3).condition in [C_E,C_NE]) then
  9855. begin
  9856. TransferUsedRegs(TmpUsedRegs);
  9857. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9858. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9859. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9860. begin
  9861. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9862. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9863. taicpu(hp1).opcode := A_TEST;
  9864. taicpu(hp1).opsize := NewSize;
  9865. RemoveInstruction(hp2);
  9866. RemoveCurrentP(p, hp1);
  9867. Result:=true;
  9868. exit;
  9869. end;
  9870. end;
  9871. end;
  9872. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9873. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9874. (taicpu(hp1).opsize=S_B)) or
  9875. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9876. (taicpu(hp1).opsize=S_W))
  9877. {$ifdef x86_64}
  9878. or ((taicpu(p).opsize=S_LQ) and
  9879. (taicpu(hp1).opsize=S_L))
  9880. {$endif x86_64}
  9881. ) and
  9882. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9883. begin
  9884. { change
  9885. movx %reg1,%reg2
  9886. op %reg2,%reg3
  9887. dealloc %reg2
  9888. into
  9889. op %reg1,%reg3
  9890. if the second op accesses only the bits stored in reg1
  9891. }
  9892. TransferUsedRegs(TmpUsedRegs);
  9893. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9894. if AndTest then
  9895. begin
  9896. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9897. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9898. end
  9899. else
  9900. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9901. if not RegUsed then
  9902. begin
  9903. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9904. if taicpu(p).oper[0]^.typ=top_reg then
  9905. begin
  9906. case taicpu(hp1).opsize of
  9907. S_B:
  9908. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9909. S_W:
  9910. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9911. S_L:
  9912. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9913. else
  9914. Internalerror(2020102301);
  9915. end;
  9916. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9917. end
  9918. else
  9919. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9920. RemoveCurrentP(p);
  9921. if AndTest then
  9922. RemoveInstruction(hp2);
  9923. result:=true;
  9924. exit;
  9925. end;
  9926. end
  9927. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9928. (
  9929. { Bitwise operations only }
  9930. (taicpu(hp1).opcode=A_AND) or
  9931. (taicpu(hp1).opcode=A_TEST) or
  9932. (
  9933. (taicpu(hp1).oper[0]^.typ = top_const) and
  9934. (
  9935. (taicpu(hp1).opcode=A_OR) or
  9936. (taicpu(hp1).opcode=A_XOR)
  9937. )
  9938. )
  9939. ) and
  9940. (
  9941. (taicpu(hp1).oper[0]^.typ = top_const) or
  9942. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9943. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9944. ) then
  9945. begin
  9946. { change
  9947. movx %reg2,%reg2
  9948. op const,%reg2
  9949. into
  9950. op const,%reg2 (smaller version)
  9951. movx %reg2,%reg2
  9952. also change
  9953. movx %reg1,%reg2
  9954. and/test (oper),%reg2
  9955. dealloc %reg2
  9956. into
  9957. and/test (oper),%reg1
  9958. }
  9959. case taicpu(p).opsize of
  9960. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9961. begin
  9962. NewSize := S_B;
  9963. NewRegSize := R_SUBL;
  9964. Limit := $FF;
  9965. end;
  9966. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9967. begin
  9968. NewSize := S_W;
  9969. NewRegSize := R_SUBW;
  9970. Limit := $FFFF;
  9971. end;
  9972. {$ifdef x86_64}
  9973. S_LQ:
  9974. begin
  9975. NewSize := S_L;
  9976. NewRegSize := R_SUBD;
  9977. Limit := $FFFFFFFF;
  9978. end;
  9979. {$endif x86_64}
  9980. else
  9981. Internalerror(2021120302);
  9982. end;
  9983. TransferUsedRegs(TmpUsedRegs);
  9984. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9985. if AndTest then
  9986. begin
  9987. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9988. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9989. end
  9990. else
  9991. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9992. if
  9993. (
  9994. (taicpu(p).opcode = A_MOVZX) and
  9995. (
  9996. (taicpu(hp1).opcode=A_AND) or
  9997. (taicpu(hp1).opcode=A_TEST)
  9998. ) and
  9999. not (
  10000. { If both are references, then the final instruction will have
  10001. both operands as references, which is not allowed }
  10002. (taicpu(p).oper[0]^.typ = top_ref) and
  10003. (taicpu(hp1).oper[0]^.typ = top_ref)
  10004. ) and
  10005. not RegUsed
  10006. ) or
  10007. (
  10008. (
  10009. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10010. not RegUsed
  10011. ) and
  10012. (taicpu(p).oper[0]^.typ = top_reg) and
  10013. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10014. (taicpu(hp1).oper[0]^.typ = top_const) and
  10015. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10016. ) then
  10017. begin
  10018. {$if defined(i386) or defined(i8086)}
  10019. { If the target size is 8-bit, make sure we can actually encode it }
  10020. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10021. Exit;
  10022. {$endif i386 or i8086}
  10023. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10024. taicpu(hp1).opsize := NewSize;
  10025. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10026. if AndTest then
  10027. begin
  10028. RemoveInstruction(hp2);
  10029. if not RegUsed then
  10030. begin
  10031. taicpu(hp1).opcode := A_TEST;
  10032. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10033. begin
  10034. { Make sure the reference is the second operand }
  10035. SwapOper := taicpu(hp1).oper[0];
  10036. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10037. taicpu(hp1).oper[1] := SwapOper;
  10038. end;
  10039. end;
  10040. end;
  10041. case taicpu(hp1).oper[0]^.typ of
  10042. top_reg:
  10043. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10044. top_const:
  10045. { For the AND/TEST case }
  10046. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10047. else
  10048. ;
  10049. end;
  10050. if RegUsed then
  10051. begin
  10052. AsmL.Remove(p);
  10053. AsmL.InsertAfter(p, hp1);
  10054. p := hp1;
  10055. end
  10056. else
  10057. RemoveCurrentP(p, hp1);
  10058. result:=true;
  10059. exit;
  10060. end;
  10061. end;
  10062. end;
  10063. if reg_and_hp1_is_instr and
  10064. (taicpu(p).oper[0]^.typ = top_reg) and
  10065. (
  10066. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10067. ) and
  10068. (taicpu(hp1).oper[0]^.typ = top_const) and
  10069. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10070. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10071. { Minimum shift value allowed is the bit difference between the sizes }
  10072. (taicpu(hp1).oper[0]^.val >=
  10073. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10074. 8 * (
  10075. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10076. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10077. )
  10078. ) then
  10079. begin
  10080. { For:
  10081. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10082. shl/sal ##, %reg1
  10083. Remove the movsx/movzx instruction if the shift overwrites the
  10084. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10085. }
  10086. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10087. RemoveCurrentP(p, hp1);
  10088. Result := True;
  10089. Exit;
  10090. end
  10091. else if reg_and_hp1_is_instr and
  10092. (taicpu(p).oper[0]^.typ = top_reg) and
  10093. (
  10094. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10095. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10096. ) and
  10097. (taicpu(hp1).oper[0]^.typ = top_const) and
  10098. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10099. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10100. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10101. (taicpu(hp1).oper[0]^.val <
  10102. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10103. 8 * (
  10104. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10105. )
  10106. ) then
  10107. begin
  10108. { For:
  10109. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10110. sar ##, %reg1 shr ##, %reg1
  10111. Move the shift to before the movx instruction if the shift value
  10112. is not too large.
  10113. }
  10114. asml.Remove(hp1);
  10115. asml.InsertBefore(hp1, p);
  10116. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10117. case taicpu(p).opsize of
  10118. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10119. taicpu(hp1).opsize := S_B;
  10120. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10121. taicpu(hp1).opsize := S_W;
  10122. {$ifdef x86_64}
  10123. S_LQ:
  10124. taicpu(hp1).opsize := S_L;
  10125. {$endif}
  10126. else
  10127. InternalError(2020112401);
  10128. end;
  10129. if (taicpu(hp1).opcode = A_SHR) then
  10130. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10131. else
  10132. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10133. Result := True;
  10134. end;
  10135. if reg_and_hp1_is_instr and
  10136. (taicpu(p).oper[0]^.typ = top_reg) and
  10137. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10138. (
  10139. (taicpu(hp1).opcode = taicpu(p).opcode)
  10140. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10141. {$ifdef x86_64}
  10142. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10143. {$endif x86_64}
  10144. ) then
  10145. begin
  10146. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10147. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10148. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10149. begin
  10150. {
  10151. For example:
  10152. movzbw %al,%ax
  10153. movzwl %ax,%eax
  10154. Compress into:
  10155. movzbl %al,%eax
  10156. }
  10157. RegUsed := False;
  10158. case taicpu(p).opsize of
  10159. S_BW:
  10160. case taicpu(hp1).opsize of
  10161. S_WL:
  10162. begin
  10163. taicpu(p).opsize := S_BL;
  10164. RegUsed := True;
  10165. end;
  10166. {$ifdef x86_64}
  10167. S_WQ:
  10168. begin
  10169. if taicpu(p).opcode = A_MOVZX then
  10170. begin
  10171. taicpu(p).opsize := S_BL;
  10172. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10173. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10174. end
  10175. else
  10176. taicpu(p).opsize := S_BQ;
  10177. RegUsed := True;
  10178. end;
  10179. {$endif x86_64}
  10180. else
  10181. ;
  10182. end;
  10183. {$ifdef x86_64}
  10184. S_BL:
  10185. case taicpu(hp1).opsize of
  10186. S_LQ:
  10187. begin
  10188. if taicpu(p).opcode = A_MOVZX then
  10189. begin
  10190. taicpu(p).opsize := S_BL;
  10191. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10192. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10193. end
  10194. else
  10195. taicpu(p).opsize := S_BQ;
  10196. RegUsed := True;
  10197. end;
  10198. else
  10199. ;
  10200. end;
  10201. S_WL:
  10202. case taicpu(hp1).opsize of
  10203. S_LQ:
  10204. begin
  10205. if taicpu(p).opcode = A_MOVZX then
  10206. begin
  10207. taicpu(p).opsize := S_WL;
  10208. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10209. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10210. end
  10211. else
  10212. taicpu(p).opsize := S_WQ;
  10213. RegUsed := True;
  10214. end;
  10215. else
  10216. ;
  10217. end;
  10218. {$endif x86_64}
  10219. else
  10220. ;
  10221. end;
  10222. if RegUsed then
  10223. begin
  10224. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10225. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10226. RemoveInstruction(hp1);
  10227. Result := True;
  10228. Exit;
  10229. end;
  10230. end;
  10231. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10232. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10233. GetNextInstruction(hp1, hp2) and
  10234. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10235. (
  10236. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10237. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10238. {$ifdef x86_64}
  10239. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10240. {$endif x86_64}
  10241. ) and
  10242. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10243. (
  10244. (
  10245. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10246. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10247. ) or
  10248. (
  10249. { Only allow the operands in reverse order for TEST instructions }
  10250. (taicpu(hp2).opcode = A_TEST) and
  10251. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10252. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10253. )
  10254. ) then
  10255. begin
  10256. {
  10257. For example:
  10258. movzbl %al,%eax
  10259. movzbl (ref),%edx
  10260. andl %edx,%eax
  10261. (%edx deallocated)
  10262. Change to:
  10263. andb (ref),%al
  10264. movzbl %al,%eax
  10265. Rules are:
  10266. - First two instructions have the same opcode and opsize
  10267. - First instruction's operands are the same super-register
  10268. - Second instruction operates on a different register
  10269. - Third instruction is AND, OR, XOR or TEST
  10270. - Third instruction's operands are the destination registers of the first two instructions
  10271. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10272. - Second instruction's destination register is deallocated afterwards
  10273. }
  10274. TransferUsedRegs(TmpUsedRegs);
  10275. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10276. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10277. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10278. begin
  10279. case taicpu(p).opsize of
  10280. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10281. NewSize := S_B;
  10282. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10283. NewSize := S_W;
  10284. {$ifdef x86_64}
  10285. S_LQ:
  10286. NewSize := S_L;
  10287. {$endif x86_64}
  10288. else
  10289. InternalError(2021120301);
  10290. end;
  10291. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10292. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10293. taicpu(hp2).opsize := NewSize;
  10294. RemoveInstruction(hp1);
  10295. { With TEST, it's best to keep the MOVX instruction at the top }
  10296. if (taicpu(hp2).opcode <> A_TEST) then
  10297. begin
  10298. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10299. asml.Remove(p);
  10300. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10301. asml.InsertAfter(p, hp2);
  10302. p := hp2;
  10303. end
  10304. else
  10305. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10306. Result := True;
  10307. Exit;
  10308. end;
  10309. end;
  10310. end;
  10311. if taicpu(p).opcode=A_MOVZX then
  10312. begin
  10313. { removes superfluous And's after movzx's }
  10314. if reg_and_hp1_is_instr and
  10315. (taicpu(hp1).opcode = A_AND) and
  10316. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10317. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10318. {$ifdef x86_64}
  10319. { check for implicit extension to 64 bit }
  10320. or
  10321. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10322. (taicpu(hp1).opsize=S_Q) and
  10323. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10324. )
  10325. {$endif x86_64}
  10326. )
  10327. then
  10328. begin
  10329. case taicpu(p).opsize Of
  10330. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10331. if (taicpu(hp1).oper[0]^.val = $ff) then
  10332. begin
  10333. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10334. RemoveInstruction(hp1);
  10335. Result:=true;
  10336. exit;
  10337. end;
  10338. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10339. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10340. begin
  10341. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10342. RemoveInstruction(hp1);
  10343. Result:=true;
  10344. exit;
  10345. end;
  10346. {$ifdef x86_64}
  10347. S_LQ:
  10348. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10349. begin
  10350. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10351. RemoveInstruction(hp1);
  10352. Result:=true;
  10353. exit;
  10354. end;
  10355. {$endif x86_64}
  10356. else
  10357. ;
  10358. end;
  10359. { we cannot get rid of the and, but can we get rid of the movz ?}
  10360. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10361. begin
  10362. case taicpu(p).opsize Of
  10363. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10364. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10365. begin
  10366. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10367. RemoveCurrentP(p,hp1);
  10368. Result:=true;
  10369. exit;
  10370. end;
  10371. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10372. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10373. begin
  10374. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10375. RemoveCurrentP(p,hp1);
  10376. Result:=true;
  10377. exit;
  10378. end;
  10379. {$ifdef x86_64}
  10380. S_LQ:
  10381. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10382. begin
  10383. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10384. RemoveCurrentP(p,hp1);
  10385. Result:=true;
  10386. exit;
  10387. end;
  10388. {$endif x86_64}
  10389. else
  10390. ;
  10391. end;
  10392. end;
  10393. end;
  10394. { changes some movzx constructs to faster synonyms (all examples
  10395. are given with eax/ax, but are also valid for other registers)}
  10396. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10397. begin
  10398. case taicpu(p).opsize of
  10399. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10400. (the machine code is equivalent to movzbl %al,%eax), but the
  10401. code generator still generates that assembler instruction and
  10402. it is silently converted. This should probably be checked.
  10403. [Kit] }
  10404. S_BW:
  10405. begin
  10406. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10407. (
  10408. not IsMOVZXAcceptable
  10409. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10410. or (
  10411. (cs_opt_size in current_settings.optimizerswitches) and
  10412. (taicpu(p).oper[1]^.reg = NR_AX)
  10413. )
  10414. ) then
  10415. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10416. begin
  10417. DebugMsg(SPeepholeOptimization + 'var7',p);
  10418. taicpu(p).opcode := A_AND;
  10419. taicpu(p).changeopsize(S_W);
  10420. taicpu(p).loadConst(0,$ff);
  10421. Result := True;
  10422. end
  10423. else if not IsMOVZXAcceptable and
  10424. GetNextInstruction(p, hp1) and
  10425. (tai(hp1).typ = ait_instruction) and
  10426. (taicpu(hp1).opcode = A_AND) and
  10427. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10428. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10429. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10430. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10431. begin
  10432. DebugMsg(SPeepholeOptimization + 'var8',p);
  10433. taicpu(p).opcode := A_MOV;
  10434. taicpu(p).changeopsize(S_W);
  10435. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10436. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10437. Result := True;
  10438. end;
  10439. end;
  10440. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10441. S_BL:
  10442. begin
  10443. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10444. (
  10445. not IsMOVZXAcceptable
  10446. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10447. or (
  10448. (cs_opt_size in current_settings.optimizerswitches) and
  10449. (taicpu(p).oper[1]^.reg = NR_EAX)
  10450. )
  10451. ) then
  10452. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10453. begin
  10454. DebugMsg(SPeepholeOptimization + 'var9',p);
  10455. taicpu(p).opcode := A_AND;
  10456. taicpu(p).changeopsize(S_L);
  10457. taicpu(p).loadConst(0,$ff);
  10458. Result := True;
  10459. end
  10460. else if not IsMOVZXAcceptable and
  10461. GetNextInstruction(p, hp1) and
  10462. (tai(hp1).typ = ait_instruction) and
  10463. (taicpu(hp1).opcode = A_AND) and
  10464. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10465. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10466. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10467. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10468. begin
  10469. DebugMsg(SPeepholeOptimization + 'var10',p);
  10470. taicpu(p).opcode := A_MOV;
  10471. taicpu(p).changeopsize(S_L);
  10472. { do not use R_SUBWHOLE
  10473. as movl %rdx,%eax
  10474. is invalid in assembler PM }
  10475. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10476. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10477. Result := True;
  10478. end;
  10479. end;
  10480. {$endif i8086}
  10481. S_WL:
  10482. if not IsMOVZXAcceptable then
  10483. begin
  10484. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10485. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10486. begin
  10487. DebugMsg(SPeepholeOptimization + 'var11',p);
  10488. taicpu(p).opcode := A_AND;
  10489. taicpu(p).changeopsize(S_L);
  10490. taicpu(p).loadConst(0,$ffff);
  10491. Result := True;
  10492. end
  10493. else if GetNextInstruction(p, hp1) and
  10494. (tai(hp1).typ = ait_instruction) and
  10495. (taicpu(hp1).opcode = A_AND) and
  10496. (taicpu(hp1).oper[0]^.typ = top_const) and
  10497. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10498. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10499. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10500. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10501. begin
  10502. DebugMsg(SPeepholeOptimization + 'var12',p);
  10503. taicpu(p).opcode := A_MOV;
  10504. taicpu(p).changeopsize(S_L);
  10505. { do not use R_SUBWHOLE
  10506. as movl %rdx,%eax
  10507. is invalid in assembler PM }
  10508. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10509. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10510. Result := True;
  10511. end;
  10512. end;
  10513. else
  10514. InternalError(2017050705);
  10515. end;
  10516. end
  10517. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10518. begin
  10519. if GetNextInstruction(p, hp1) and
  10520. (tai(hp1).typ = ait_instruction) and
  10521. (taicpu(hp1).opcode = A_AND) and
  10522. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10523. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10524. begin
  10525. //taicpu(p).opcode := A_MOV;
  10526. case taicpu(p).opsize Of
  10527. S_BL:
  10528. begin
  10529. DebugMsg(SPeepholeOptimization + 'var13',p);
  10530. taicpu(hp1).changeopsize(S_L);
  10531. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10532. end;
  10533. S_WL:
  10534. begin
  10535. DebugMsg(SPeepholeOptimization + 'var14',p);
  10536. taicpu(hp1).changeopsize(S_L);
  10537. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10538. end;
  10539. S_BW:
  10540. begin
  10541. DebugMsg(SPeepholeOptimization + 'var15',p);
  10542. taicpu(hp1).changeopsize(S_W);
  10543. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10544. end;
  10545. else
  10546. Internalerror(2017050704)
  10547. end;
  10548. Result := True;
  10549. end;
  10550. end;
  10551. end;
  10552. end;
  10553. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10554. var
  10555. hp1, hp2 : tai;
  10556. MaskLength : Cardinal;
  10557. MaskedBits : TCgInt;
  10558. ActiveReg : TRegister;
  10559. begin
  10560. Result:=false;
  10561. { There are no optimisations for reference targets }
  10562. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10563. Exit;
  10564. while GetNextInstruction(p, hp1) and
  10565. (hp1.typ = ait_instruction) do
  10566. begin
  10567. if (taicpu(p).oper[0]^.typ = top_const) then
  10568. begin
  10569. case taicpu(hp1).opcode of
  10570. A_AND:
  10571. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10572. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10573. { the second register must contain the first one, so compare their subreg types }
  10574. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10575. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10576. { change
  10577. and const1, reg
  10578. and const2, reg
  10579. to
  10580. and (const1 and const2), reg
  10581. }
  10582. begin
  10583. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10584. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10585. RemoveCurrentP(p, hp1);
  10586. Result:=true;
  10587. exit;
  10588. end;
  10589. A_CMP:
  10590. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10591. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10592. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10593. { Just check that the condition on the next instruction is compatible }
  10594. GetNextInstruction(hp1, hp2) and
  10595. (hp2.typ = ait_instruction) and
  10596. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10597. then
  10598. { change
  10599. and 2^n, reg
  10600. cmp 2^n, reg
  10601. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10602. to
  10603. and 2^n, reg
  10604. test reg, reg
  10605. j(~c) / set(~c) / cmov(~c)
  10606. }
  10607. begin
  10608. { Keep TEST instruction in, rather than remove it, because
  10609. it may trigger other optimisations such as MovAndTest2Test }
  10610. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10611. taicpu(hp1).opcode := A_TEST;
  10612. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10613. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10614. Result := True;
  10615. Exit;
  10616. end;
  10617. A_MOVZX:
  10618. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10619. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10620. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10621. (
  10622. (
  10623. (taicpu(p).opsize=S_W) and
  10624. (taicpu(hp1).opsize=S_BW)
  10625. ) or
  10626. (
  10627. (taicpu(p).opsize=S_L) and
  10628. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10629. )
  10630. {$ifdef x86_64}
  10631. or
  10632. (
  10633. (taicpu(p).opsize=S_Q) and
  10634. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10635. )
  10636. {$endif x86_64}
  10637. ) then
  10638. begin
  10639. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10640. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10641. ) or
  10642. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10643. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10644. then
  10645. begin
  10646. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10647. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10648. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10649. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10650. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10651. }
  10652. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10653. RemoveInstruction(hp1);
  10654. { See if there are other optimisations possible }
  10655. Continue;
  10656. end;
  10657. end;
  10658. A_SHL:
  10659. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10660. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10661. begin
  10662. {$ifopt R+}
  10663. {$define RANGE_WAS_ON}
  10664. {$R-}
  10665. {$endif}
  10666. { get length of potential and mask }
  10667. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10668. { really a mask? }
  10669. {$ifdef RANGE_WAS_ON}
  10670. {$R+}
  10671. {$endif}
  10672. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10673. { unmasked part shifted out? }
  10674. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10675. begin
  10676. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10677. RemoveCurrentP(p, hp1);
  10678. Result:=true;
  10679. exit;
  10680. end;
  10681. end;
  10682. A_SHR:
  10683. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10684. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10685. (taicpu(hp1).oper[0]^.val <= 63) then
  10686. begin
  10687. { Does SHR combined with the AND cover all the bits?
  10688. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10689. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10690. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10691. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10692. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10693. begin
  10694. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10695. RemoveCurrentP(p, hp1);
  10696. Result := True;
  10697. Exit;
  10698. end;
  10699. end;
  10700. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10701. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10702. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10703. begin
  10704. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10705. (
  10706. (
  10707. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10708. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10709. ) or (
  10710. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10711. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10712. {$ifdef x86_64}
  10713. ) or (
  10714. (taicpu(hp1).opsize = S_LQ) and
  10715. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10716. {$endif x86_64}
  10717. )
  10718. ) then
  10719. begin
  10720. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10721. begin
  10722. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10723. RemoveInstruction(hp1);
  10724. { See if there are other optimisations possible }
  10725. Continue;
  10726. end;
  10727. { The super-registers are the same though.
  10728. Note that this change by itself doesn't improve
  10729. code speed, but it opens up other optimisations. }
  10730. {$ifdef x86_64}
  10731. { Convert 64-bit register to 32-bit }
  10732. case taicpu(hp1).opsize of
  10733. S_BQ:
  10734. begin
  10735. taicpu(hp1).opsize := S_BL;
  10736. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10737. end;
  10738. S_WQ:
  10739. begin
  10740. taicpu(hp1).opsize := S_WL;
  10741. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10742. end
  10743. else
  10744. ;
  10745. end;
  10746. {$endif x86_64}
  10747. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10748. taicpu(hp1).opcode := A_MOVZX;
  10749. { See if there are other optimisations possible }
  10750. Continue;
  10751. end;
  10752. end;
  10753. else
  10754. ;
  10755. end;
  10756. end
  10757. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10758. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10759. begin
  10760. {$ifdef x86_64}
  10761. if (taicpu(p).opsize = S_Q) then
  10762. begin
  10763. { Never necessary }
  10764. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10765. RemoveCurrentP(p, hp1);
  10766. Result := True;
  10767. Exit;
  10768. end;
  10769. {$endif x86_64}
  10770. { Forward check to determine necessity of and %reg,%reg }
  10771. TransferUsedRegs(TmpUsedRegs);
  10772. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10773. { Saves on a bunch of dereferences }
  10774. ActiveReg := taicpu(p).oper[1]^.reg;
  10775. case taicpu(hp1).opcode of
  10776. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10777. if (
  10778. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10779. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10780. ) and
  10781. (
  10782. (taicpu(hp1).opcode <> A_MOV) or
  10783. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10784. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10785. ) and
  10786. not (
  10787. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10788. (taicpu(hp1).opcode = A_MOV) and
  10789. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10790. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10791. ) and
  10792. (
  10793. (
  10794. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10795. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10796. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10797. ) or
  10798. (
  10799. {$ifdef x86_64}
  10800. (
  10801. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10802. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10803. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10804. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10805. ) and
  10806. {$endif x86_64}
  10807. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10808. )
  10809. ) then
  10810. begin
  10811. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10812. RemoveCurrentP(p, hp1);
  10813. Result := True;
  10814. Exit;
  10815. end;
  10816. A_ADD,
  10817. A_AND,
  10818. A_BSF,
  10819. A_BSR,
  10820. A_BTC,
  10821. A_BTR,
  10822. A_BTS,
  10823. A_OR,
  10824. A_SUB,
  10825. A_XOR:
  10826. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10827. if (
  10828. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10829. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10830. ) and
  10831. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10832. begin
  10833. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10834. RemoveCurrentP(p, hp1);
  10835. Result := True;
  10836. Exit;
  10837. end;
  10838. A_CMP,
  10839. A_TEST:
  10840. if (
  10841. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10842. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10843. ) and
  10844. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10845. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10846. begin
  10847. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10848. RemoveCurrentP(p, hp1);
  10849. Result := True;
  10850. Exit;
  10851. end;
  10852. A_BSWAP,
  10853. A_NEG,
  10854. A_NOT:
  10855. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10856. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10857. begin
  10858. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10859. RemoveCurrentP(p, hp1);
  10860. Result := True;
  10861. Exit;
  10862. end;
  10863. else
  10864. ;
  10865. end;
  10866. end;
  10867. if (taicpu(hp1).is_jmp) and
  10868. (taicpu(hp1).opcode<>A_JMP) and
  10869. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10870. begin
  10871. { change
  10872. and x, reg
  10873. jxx
  10874. to
  10875. test x, reg
  10876. jxx
  10877. if reg is deallocated before the
  10878. jump, but only if it's a conditional jump (PFV)
  10879. }
  10880. taicpu(p).opcode := A_TEST;
  10881. Exit;
  10882. end;
  10883. Break;
  10884. end;
  10885. { Lone AND tests }
  10886. if (taicpu(p).oper[0]^.typ = top_const) then
  10887. begin
  10888. {
  10889. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10890. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10891. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10892. }
  10893. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10894. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10895. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10896. begin
  10897. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10898. if taicpu(p).opsize = S_L then
  10899. begin
  10900. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10901. Result := True;
  10902. end;
  10903. end;
  10904. end;
  10905. { Backward check to determine necessity of and %reg,%reg }
  10906. if (taicpu(p).oper[0]^.typ = top_reg) and
  10907. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10908. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10909. GetLastInstruction(p, hp2) and
  10910. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10911. { Check size of adjacent instruction to determine if the AND is
  10912. effectively a null operation }
  10913. (
  10914. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10915. { Note: Don't include S_Q }
  10916. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10917. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10918. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10919. ) then
  10920. begin
  10921. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10922. { If GetNextInstruction returned False, hp1 will be nil }
  10923. RemoveCurrentP(p, hp1);
  10924. Result := True;
  10925. Exit;
  10926. end;
  10927. end;
  10928. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10929. var
  10930. hp1: tai; NewRef: TReference;
  10931. { This entire nested function is used in an if-statement below, but we
  10932. want to avoid all the used reg transfers and GetNextInstruction calls
  10933. until we really have to check }
  10934. function MemRegisterNotUsedLater: Boolean; inline;
  10935. var
  10936. hp2: tai;
  10937. begin
  10938. TransferUsedRegs(TmpUsedRegs);
  10939. hp2 := p;
  10940. repeat
  10941. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10942. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10943. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10944. end;
  10945. begin
  10946. Result := False;
  10947. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10948. Exit;
  10949. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10950. begin
  10951. { Change:
  10952. add %reg2,%reg1
  10953. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10954. To:
  10955. mov/s/z #(%reg1,%reg2),%reg1
  10956. }
  10957. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10958. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10959. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10960. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10961. (
  10962. (
  10963. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10964. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10965. { r/esp cannot be an index }
  10966. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10967. ) or (
  10968. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10969. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10970. )
  10971. ) and (
  10972. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10973. (
  10974. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10975. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10976. MemRegisterNotUsedLater
  10977. )
  10978. ) then
  10979. begin
  10980. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10981. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10982. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10983. RemoveCurrentp(p, hp1);
  10984. Result := True;
  10985. Exit;
  10986. end;
  10987. { Change:
  10988. addl/q $x,%reg1
  10989. movl/q %reg1,%reg2
  10990. To:
  10991. leal/q $x(%reg1),%reg2
  10992. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10993. Breaks the dependency chain.
  10994. }
  10995. if MatchOpType(taicpu(p),top_const,top_reg) and
  10996. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10997. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10998. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10999. (
  11000. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11001. not (cs_opt_size in current_settings.optimizerswitches) or
  11002. (
  11003. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11004. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11005. )
  11006. ) then
  11007. begin
  11008. { Change the MOV instruction to a LEA instruction, and update the
  11009. first operand }
  11010. reference_reset(NewRef, 1, []);
  11011. NewRef.base := taicpu(p).oper[1]^.reg;
  11012. NewRef.scalefactor := 1;
  11013. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11014. taicpu(hp1).opcode := A_LEA;
  11015. taicpu(hp1).loadref(0, NewRef);
  11016. TransferUsedRegs(TmpUsedRegs);
  11017. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11018. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11019. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11020. begin
  11021. { Move what is now the LEA instruction to before the SUB instruction }
  11022. Asml.Remove(hp1);
  11023. Asml.InsertBefore(hp1, p);
  11024. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11025. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11026. p := hp1;
  11027. end
  11028. else
  11029. begin
  11030. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11031. RemoveCurrentP(p, hp1);
  11032. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11033. end;
  11034. Result := True;
  11035. end;
  11036. end;
  11037. end;
  11038. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11039. var
  11040. SubReg: TSubRegister;
  11041. begin
  11042. Result:=false;
  11043. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11044. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11045. with taicpu(p).oper[0]^.ref^ do
  11046. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11047. begin
  11048. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11049. begin
  11050. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11051. taicpu(p).opcode := A_ADD;
  11052. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11053. Result := True;
  11054. end
  11055. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11056. begin
  11057. if (base <> NR_NO) then
  11058. begin
  11059. if (scalefactor <= 1) then
  11060. begin
  11061. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11062. taicpu(p).opcode := A_ADD;
  11063. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11064. Result := True;
  11065. end;
  11066. end
  11067. else
  11068. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11069. if (scalefactor in [2, 4, 8]) then
  11070. begin
  11071. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11072. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11073. taicpu(p).opcode := A_SHL;
  11074. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11075. Result := True;
  11076. end;
  11077. end;
  11078. end;
  11079. end;
  11080. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11081. var
  11082. hp1: tai; NewRef: TReference;
  11083. begin
  11084. { Change:
  11085. subl/q $x,%reg1
  11086. movl/q %reg1,%reg2
  11087. To:
  11088. leal/q $-x(%reg1),%reg2
  11089. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11090. Breaks the dependency chain and potentially permits the removal of
  11091. a CMP instruction if one follows.
  11092. }
  11093. Result := False;
  11094. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11095. MatchOpType(taicpu(p),top_const,top_reg) and
  11096. GetNextInstruction(p, hp1) and
  11097. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11098. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11099. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11100. (
  11101. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11102. not (cs_opt_size in current_settings.optimizerswitches) or
  11103. (
  11104. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11105. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11106. )
  11107. ) then
  11108. begin
  11109. { Change the MOV instruction to a LEA instruction, and update the
  11110. first operand }
  11111. reference_reset(NewRef, 1, []);
  11112. NewRef.base := taicpu(p).oper[1]^.reg;
  11113. NewRef.scalefactor := 1;
  11114. NewRef.offset := -taicpu(p).oper[0]^.val;
  11115. taicpu(hp1).opcode := A_LEA;
  11116. taicpu(hp1).loadref(0, NewRef);
  11117. TransferUsedRegs(TmpUsedRegs);
  11118. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11119. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11120. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11121. begin
  11122. { Move what is now the LEA instruction to before the SUB instruction }
  11123. Asml.Remove(hp1);
  11124. Asml.InsertBefore(hp1, p);
  11125. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11126. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11127. p := hp1;
  11128. end
  11129. else
  11130. begin
  11131. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11132. RemoveCurrentP(p, hp1);
  11133. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11134. end;
  11135. Result := True;
  11136. end;
  11137. end;
  11138. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11139. begin
  11140. { we can skip all instructions not messing with the stack pointer }
  11141. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11142. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11143. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11144. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11145. ({(taicpu(hp1).ops=0) or }
  11146. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11147. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11148. ) and }
  11149. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11150. )
  11151. ) do
  11152. GetNextInstruction(hp1,hp1);
  11153. Result:=assigned(hp1);
  11154. end;
  11155. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11156. var
  11157. hp1, hp2, hp3, hp4, hp5: tai;
  11158. begin
  11159. Result:=false;
  11160. hp5:=nil;
  11161. { replace
  11162. leal(q) x(<stackpointer>),<stackpointer>
  11163. call procname
  11164. leal(q) -x(<stackpointer>),<stackpointer>
  11165. ret
  11166. by
  11167. jmp procname
  11168. but do it only on level 4 because it destroys stack back traces
  11169. }
  11170. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11171. MatchOpType(taicpu(p),top_ref,top_reg) and
  11172. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11173. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11174. { the -8 or -24 are not required, but bail out early if possible,
  11175. higher values are unlikely }
  11176. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11177. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11178. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11179. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11180. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11181. GetNextInstruction(p, hp1) and
  11182. { Take a copy of hp1 }
  11183. SetAndTest(hp1, hp4) and
  11184. { trick to skip label }
  11185. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11186. SkipSimpleInstructions(hp1) and
  11187. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11188. GetNextInstruction(hp1, hp2) and
  11189. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11190. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11191. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11192. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11193. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11194. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11195. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11196. { Segment register will be NR_NO }
  11197. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11198. GetNextInstruction(hp2, hp3) and
  11199. { trick to skip label }
  11200. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11201. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11202. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11203. SetAndTest(hp3,hp5) and
  11204. GetNextInstruction(hp3,hp3) and
  11205. MatchInstruction(hp3,A_RET,[S_NO])
  11206. )
  11207. ) and
  11208. (taicpu(hp3).ops=0) then
  11209. begin
  11210. taicpu(hp1).opcode := A_JMP;
  11211. taicpu(hp1).is_jmp := true;
  11212. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11213. RemoveCurrentP(p, hp4);
  11214. RemoveInstruction(hp2);
  11215. RemoveInstruction(hp3);
  11216. if Assigned(hp5) then
  11217. begin
  11218. AsmL.Remove(hp5);
  11219. ASmL.InsertBefore(hp5,hp1)
  11220. end;
  11221. Result:=true;
  11222. end;
  11223. end;
  11224. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11225. {$ifdef x86_64}
  11226. var
  11227. hp1, hp2, hp3, hp4, hp5: tai;
  11228. {$endif x86_64}
  11229. begin
  11230. Result:=false;
  11231. {$ifdef x86_64}
  11232. hp5:=nil;
  11233. { replace
  11234. push %rax
  11235. call procname
  11236. pop %rcx
  11237. ret
  11238. by
  11239. jmp procname
  11240. but do it only on level 4 because it destroys stack back traces
  11241. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11242. for all supported calling conventions
  11243. }
  11244. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11245. MatchOpType(taicpu(p),top_reg) and
  11246. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11247. GetNextInstruction(p, hp1) and
  11248. { Take a copy of hp1 }
  11249. SetAndTest(hp1, hp4) and
  11250. { trick to skip label }
  11251. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11252. SkipSimpleInstructions(hp1) and
  11253. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11254. GetNextInstruction(hp1, hp2) and
  11255. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11256. MatchOpType(taicpu(hp2),top_reg) and
  11257. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11258. GetNextInstruction(hp2, hp3) and
  11259. { trick to skip label }
  11260. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11261. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11262. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11263. SetAndTest(hp3,hp5) and
  11264. GetNextInstruction(hp3,hp3) and
  11265. MatchInstruction(hp3,A_RET,[S_NO])
  11266. )
  11267. ) and
  11268. (taicpu(hp3).ops=0) then
  11269. begin
  11270. taicpu(hp1).opcode := A_JMP;
  11271. taicpu(hp1).is_jmp := true;
  11272. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11273. RemoveCurrentP(p, hp4);
  11274. RemoveInstruction(hp2);
  11275. RemoveInstruction(hp3);
  11276. if Assigned(hp5) then
  11277. begin
  11278. AsmL.Remove(hp5);
  11279. ASmL.InsertBefore(hp5,hp1)
  11280. end;
  11281. Result:=true;
  11282. end;
  11283. {$endif x86_64}
  11284. end;
  11285. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11286. var
  11287. Value, RegName: string;
  11288. begin
  11289. Result:=false;
  11290. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11291. begin
  11292. case taicpu(p).oper[0]^.val of
  11293. 0:
  11294. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11295. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11296. begin
  11297. { change "mov $0,%reg" into "xor %reg,%reg" }
  11298. taicpu(p).opcode := A_XOR;
  11299. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11300. Result := True;
  11301. {$ifdef x86_64}
  11302. end
  11303. else if (taicpu(p).opsize = S_Q) then
  11304. begin
  11305. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11306. { The actual optimization }
  11307. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11308. taicpu(p).changeopsize(S_L);
  11309. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11310. Result := True;
  11311. end;
  11312. $1..$FFFFFFFF:
  11313. begin
  11314. { Code size reduction by J. Gareth "Kit" Moreton }
  11315. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11316. case taicpu(p).opsize of
  11317. S_Q:
  11318. begin
  11319. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11320. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11321. { The actual optimization }
  11322. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11323. taicpu(p).changeopsize(S_L);
  11324. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11325. Result := True;
  11326. end;
  11327. else
  11328. { Do nothing };
  11329. end;
  11330. {$endif x86_64}
  11331. end;
  11332. -1:
  11333. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11334. if (cs_opt_size in current_settings.optimizerswitches) and
  11335. (taicpu(p).opsize <> S_B) and
  11336. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11337. begin
  11338. { change "mov $-1,%reg" into "or $-1,%reg" }
  11339. { NOTES:
  11340. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11341. - This operation creates a false dependency on the register, so only do it when optimising for size
  11342. - 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
  11343. }
  11344. taicpu(p).opcode := A_OR;
  11345. Result := True;
  11346. end;
  11347. else
  11348. { Do nothing };
  11349. end;
  11350. end;
  11351. end;
  11352. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11353. var
  11354. hp1: tai;
  11355. begin
  11356. { Detect:
  11357. andw x, %ax (0 <= x < $8000)
  11358. ...
  11359. movzwl %ax,%eax
  11360. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11361. }
  11362. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11363. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11364. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11365. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11366. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11367. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11368. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11369. begin
  11370. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11371. taicpu(hp1).opcode := A_CWDE;
  11372. taicpu(hp1).clearop(0);
  11373. taicpu(hp1).clearop(1);
  11374. taicpu(hp1).ops := 0;
  11375. { A change was made, but not with p, so move forward 1 }
  11376. p := tai(p.Next);
  11377. Result := True;
  11378. end;
  11379. end;
  11380. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11381. begin
  11382. Result := False;
  11383. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11384. Exit;
  11385. { Convert:
  11386. movswl %ax,%eax -> cwtl
  11387. movslq %eax,%rax -> cdqe
  11388. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11389. refer to the same opcode and depends only on the assembler's
  11390. current operand-size attribute. [Kit]
  11391. }
  11392. with taicpu(p) do
  11393. case opsize of
  11394. S_WL:
  11395. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11396. begin
  11397. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11398. opcode := A_CWDE;
  11399. clearop(0);
  11400. clearop(1);
  11401. ops := 0;
  11402. Result := True;
  11403. end;
  11404. {$ifdef x86_64}
  11405. S_LQ:
  11406. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11407. begin
  11408. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11409. opcode := A_CDQE;
  11410. clearop(0);
  11411. clearop(1);
  11412. ops := 0;
  11413. Result := True;
  11414. end;
  11415. {$endif x86_64}
  11416. else
  11417. ;
  11418. end;
  11419. end;
  11420. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11421. var
  11422. hp1: tai;
  11423. begin
  11424. { Detect:
  11425. shr x, %ax (x > 0)
  11426. ...
  11427. movzwl %ax,%eax
  11428. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11429. }
  11430. Result := False;
  11431. if MatchOpType(taicpu(p), top_const, top_reg) and
  11432. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11433. (taicpu(p).oper[0]^.val > 0) and
  11434. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11435. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11436. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11437. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11438. begin
  11439. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11440. taicpu(hp1).opcode := A_CWDE;
  11441. taicpu(hp1).clearop(0);
  11442. taicpu(hp1).clearop(1);
  11443. taicpu(hp1).ops := 0;
  11444. { A change was made, but not with p, so move forward 1 }
  11445. p := tai(p.Next);
  11446. Result := True;
  11447. end;
  11448. end;
  11449. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11450. var
  11451. hp1, hp2: tai;
  11452. Opposite, SecondOpposite: TAsmOp;
  11453. NewCond: TAsmCond;
  11454. begin
  11455. Result := False;
  11456. { Change:
  11457. add/sub 128,(dest)
  11458. To:
  11459. sub/add -128,(dest)
  11460. This generaally takes fewer bytes to encode because -128 can be stored
  11461. in a signed byte, whereas +128 cannot.
  11462. }
  11463. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11464. begin
  11465. if taicpu(p).opcode = A_ADD then
  11466. Opposite := A_SUB
  11467. else
  11468. Opposite := A_ADD;
  11469. { Be careful if the flags are in use, because the CF flag inverts
  11470. when changing from ADD to SUB and vice versa }
  11471. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11472. GetNextInstruction(p, hp1) then
  11473. begin
  11474. TransferUsedRegs(TmpUsedRegs);
  11475. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11476. hp2 := hp1;
  11477. { Scan ahead to check if everything's safe }
  11478. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11479. begin
  11480. if (hp1.typ <> ait_instruction) then
  11481. { Probably unsafe since the flags are still in use }
  11482. Exit;
  11483. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11484. { Stop searching at an unconditional jump }
  11485. Break;
  11486. if not
  11487. (
  11488. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11489. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11490. ) and
  11491. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11492. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11493. Exit;
  11494. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11495. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11496. { Move to the next instruction }
  11497. GetNextInstruction(hp1, hp1);
  11498. end;
  11499. while Assigned(hp2) and (hp2 <> hp1) do
  11500. begin
  11501. NewCond := C_None;
  11502. case taicpu(hp2).condition of
  11503. C_A, C_NBE:
  11504. NewCond := C_BE;
  11505. C_B, C_C, C_NAE:
  11506. NewCond := C_AE;
  11507. C_AE, C_NB, C_NC:
  11508. NewCond := C_B;
  11509. C_BE, C_NA:
  11510. NewCond := C_A;
  11511. else
  11512. { No change needed };
  11513. end;
  11514. if NewCond <> C_None then
  11515. begin
  11516. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11517. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11518. taicpu(hp2).condition := NewCond;
  11519. end
  11520. else
  11521. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11522. begin
  11523. { Because of the flipping of the carry bit, to ensure
  11524. the operation remains equivalent, ADC becomes SBB
  11525. and vice versa, and the constant is not-inverted.
  11526. If multiple ADCs or SBBs appear in a row, each one
  11527. changed causes the carry bit to invert, so they all
  11528. need to be flipped }
  11529. if taicpu(hp2).opcode = A_ADC then
  11530. SecondOpposite := A_SBB
  11531. else
  11532. SecondOpposite := A_ADC;
  11533. if taicpu(hp2).oper[0]^.typ <> top_const then
  11534. { Should have broken out of this optimisation already }
  11535. InternalError(2021112901);
  11536. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  11537. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  11538. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11539. taicpu(hp2).opcode := SecondOpposite;
  11540. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11541. end;
  11542. { Move to the next instruction }
  11543. GetNextInstruction(hp2, hp2);
  11544. end;
  11545. if (hp2 <> hp1) then
  11546. InternalError(2021111501);
  11547. end;
  11548. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11549. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11550. taicpu(p).opcode := Opposite;
  11551. taicpu(p).oper[0]^.val := -128;
  11552. { No further optimisations can be made on this instruction, so move
  11553. onto the next one to save time }
  11554. p := tai(p.Next);
  11555. UpdateUsedRegs(p);
  11556. Result := True;
  11557. Exit;
  11558. end;
  11559. { Detect:
  11560. add/sub %reg2,(dest)
  11561. add/sub x, (dest)
  11562. (dest can be a register or a reference)
  11563. Swap the instructions to minimise a pipeline stall. This reverses the
  11564. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11565. optimisations could be made.
  11566. }
  11567. if (taicpu(p).oper[0]^.typ = top_reg) and
  11568. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11569. (
  11570. (
  11571. (taicpu(p).oper[1]^.typ = top_reg) and
  11572. { We can try searching further ahead if we're writing to a register }
  11573. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11574. ) or
  11575. (
  11576. (taicpu(p).oper[1]^.typ = top_ref) and
  11577. GetNextInstruction(p, hp1)
  11578. )
  11579. ) and
  11580. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11581. (taicpu(hp1).oper[0]^.typ = top_const) and
  11582. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11583. begin
  11584. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11585. TransferUsedRegs(TmpUsedRegs);
  11586. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11587. hp2 := p;
  11588. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11589. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11590. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11591. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11592. begin
  11593. asml.remove(hp1);
  11594. asml.InsertBefore(hp1, p);
  11595. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11596. Result := True;
  11597. end;
  11598. end;
  11599. end;
  11600. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11601. begin
  11602. Result:=false;
  11603. { change "cmp $0, %reg" to "test %reg, %reg" }
  11604. if MatchOpType(taicpu(p),top_const,top_reg) and
  11605. (taicpu(p).oper[0]^.val = 0) then
  11606. begin
  11607. taicpu(p).opcode := A_TEST;
  11608. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11609. Result:=true;
  11610. end;
  11611. end;
  11612. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11613. var
  11614. IsTestConstX : Boolean;
  11615. hp1,hp2 : tai;
  11616. begin
  11617. Result:=false;
  11618. { removes the line marked with (x) from the sequence
  11619. and/or/xor/add/sub/... $x, %y
  11620. test/or %y, %y | test $-1, %y (x)
  11621. j(n)z _Label
  11622. as the first instruction already adjusts the ZF
  11623. %y operand may also be a reference }
  11624. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11625. MatchOperand(taicpu(p).oper[0]^,-1);
  11626. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11627. GetLastInstruction(p, hp1) and
  11628. (tai(hp1).typ = ait_instruction) and
  11629. GetNextInstruction(p,hp2) and
  11630. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11631. case taicpu(hp1).opcode Of
  11632. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11633. { These two instructions set the zero flag if the result is zero }
  11634. A_POPCNT, A_LZCNT:
  11635. begin
  11636. if (
  11637. { With POPCNT, an input of zero will set the zero flag
  11638. because the population count of zero is zero }
  11639. (taicpu(hp1).opcode = A_POPCNT) and
  11640. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11641. (
  11642. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11643. { Faster than going through the second half of the 'or'
  11644. condition below }
  11645. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11646. )
  11647. ) or (
  11648. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11649. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11650. { and in case of carry for A(E)/B(E)/C/NC }
  11651. (
  11652. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11653. (
  11654. (taicpu(hp1).opcode <> A_ADD) and
  11655. (taicpu(hp1).opcode <> A_SUB) and
  11656. (taicpu(hp1).opcode <> A_LZCNT)
  11657. )
  11658. )
  11659. ) then
  11660. begin
  11661. RemoveCurrentP(p, hp2);
  11662. Result:=true;
  11663. Exit;
  11664. end;
  11665. end;
  11666. A_SHL, A_SAL, A_SHR, A_SAR:
  11667. begin
  11668. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11669. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11670. { therefore, it's only safe to do this optimization for }
  11671. { shifts by a (nonzero) constant }
  11672. (taicpu(hp1).oper[0]^.typ = top_const) and
  11673. (taicpu(hp1).oper[0]^.val <> 0) and
  11674. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11675. { and in case of carry for A(E)/B(E)/C/NC }
  11676. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11677. begin
  11678. RemoveCurrentP(p, hp2);
  11679. Result:=true;
  11680. Exit;
  11681. end;
  11682. end;
  11683. A_DEC, A_INC, A_NEG:
  11684. begin
  11685. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11686. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11687. { and in case of carry for A(E)/B(E)/C/NC }
  11688. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11689. begin
  11690. RemoveCurrentP(p, hp2);
  11691. Result:=true;
  11692. Exit;
  11693. end;
  11694. end
  11695. else
  11696. ;
  11697. end; { case }
  11698. { change "test $-1,%reg" into "test %reg,%reg" }
  11699. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11700. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11701. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11702. if MatchInstruction(p, A_OR, []) and
  11703. { Can only match if they're both registers }
  11704. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11705. begin
  11706. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11707. taicpu(p).opcode := A_TEST;
  11708. { No need to set Result to True, as we've done all the optimisations we can }
  11709. end;
  11710. end;
  11711. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11712. var
  11713. hp1,hp3 : tai;
  11714. {$ifndef x86_64}
  11715. hp2 : taicpu;
  11716. {$endif x86_64}
  11717. begin
  11718. Result:=false;
  11719. hp3:=nil;
  11720. {$ifndef x86_64}
  11721. { don't do this on modern CPUs, this really hurts them due to
  11722. broken call/ret pairing }
  11723. if (current_settings.optimizecputype < cpu_Pentium2) and
  11724. not(cs_create_pic in current_settings.moduleswitches) and
  11725. GetNextInstruction(p, hp1) and
  11726. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11727. MatchOpType(taicpu(hp1),top_ref) and
  11728. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11729. begin
  11730. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11731. InsertLLItem(p.previous, p, hp2);
  11732. taicpu(p).opcode := A_JMP;
  11733. taicpu(p).is_jmp := true;
  11734. RemoveInstruction(hp1);
  11735. Result:=true;
  11736. end
  11737. else
  11738. {$endif x86_64}
  11739. { replace
  11740. call procname
  11741. ret
  11742. by
  11743. jmp procname
  11744. but do it only on level 4 because it destroys stack back traces
  11745. else if the subroutine is marked as no return, remove the ret
  11746. }
  11747. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11748. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11749. GetNextInstruction(p, hp1) and
  11750. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11751. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11752. SetAndTest(hp1,hp3) and
  11753. GetNextInstruction(hp1,hp1) and
  11754. MatchInstruction(hp1,A_RET,[S_NO])
  11755. )
  11756. ) and
  11757. (taicpu(hp1).ops=0) then
  11758. begin
  11759. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11760. { we might destroy stack alignment here if we do not do a call }
  11761. (target_info.stackalign<=sizeof(SizeUInt)) then
  11762. begin
  11763. taicpu(p).opcode := A_JMP;
  11764. taicpu(p).is_jmp := true;
  11765. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11766. end
  11767. else
  11768. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11769. RemoveInstruction(hp1);
  11770. if Assigned(hp3) then
  11771. begin
  11772. AsmL.Remove(hp3);
  11773. AsmL.InsertBefore(hp3,p)
  11774. end;
  11775. Result:=true;
  11776. end;
  11777. end;
  11778. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11779. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11780. begin
  11781. case OpSize of
  11782. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11783. Result := (Val <= $FF) and (Val >= -128);
  11784. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11785. Result := (Val <= $FFFF) and (Val >= -32768);
  11786. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11787. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11788. else
  11789. Result := True;
  11790. end;
  11791. end;
  11792. var
  11793. hp1, hp2 : tai;
  11794. SizeChange: Boolean;
  11795. PreMessage: string;
  11796. begin
  11797. Result := False;
  11798. if (taicpu(p).oper[0]^.typ = top_reg) and
  11799. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11800. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11801. begin
  11802. { Change (using movzbl %al,%eax as an example):
  11803. movzbl %al, %eax movzbl %al, %eax
  11804. cmpl x, %eax testl %eax,%eax
  11805. To:
  11806. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11807. movzbl %al, %eax movzbl %al, %eax
  11808. Smaller instruction and minimises pipeline stall as the CPU
  11809. doesn't have to wait for the register to get zero-extended. [Kit]
  11810. Also allow if the smaller of the two registers is being checked,
  11811. as this still removes the false dependency.
  11812. }
  11813. if
  11814. (
  11815. (
  11816. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11817. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11818. ) or (
  11819. { If MatchOperand returns True, they must both be registers }
  11820. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11821. )
  11822. ) and
  11823. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11824. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11825. begin
  11826. 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);
  11827. asml.Remove(hp1);
  11828. asml.InsertBefore(hp1, p);
  11829. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11830. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11831. begin
  11832. taicpu(hp1).opcode := A_TEST;
  11833. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11834. end;
  11835. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11836. case taicpu(p).opsize of
  11837. S_BW, S_BL:
  11838. begin
  11839. SizeChange := taicpu(hp1).opsize <> S_B;
  11840. taicpu(hp1).changeopsize(S_B);
  11841. end;
  11842. S_WL:
  11843. begin
  11844. SizeChange := taicpu(hp1).opsize <> S_W;
  11845. taicpu(hp1).changeopsize(S_W);
  11846. end
  11847. else
  11848. InternalError(2020112701);
  11849. end;
  11850. UpdateUsedRegs(tai(p.Next));
  11851. { Check if the register is used aferwards - if not, we can
  11852. remove the movzx instruction completely }
  11853. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11854. begin
  11855. { Hp1 is a better position than p for debugging purposes }
  11856. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11857. RemoveCurrentp(p, hp1);
  11858. Result := True;
  11859. end;
  11860. if SizeChange then
  11861. DebugMsg(SPeepholeOptimization + PreMessage +
  11862. 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)
  11863. else
  11864. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11865. Exit;
  11866. end;
  11867. { Change (using movzwl %ax,%eax as an example):
  11868. movzwl %ax, %eax
  11869. movb %al, (dest) (Register is smaller than read register in movz)
  11870. To:
  11871. movb %al, (dest) (Move one back to avoid a false dependency)
  11872. movzwl %ax, %eax
  11873. }
  11874. if (taicpu(hp1).opcode = A_MOV) and
  11875. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11876. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11877. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11878. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11879. begin
  11880. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11881. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11882. asml.Remove(hp1);
  11883. asml.InsertBefore(hp1, p);
  11884. if taicpu(hp1).oper[1]^.typ = top_reg then
  11885. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11886. { Check if the register is used aferwards - if not, we can
  11887. remove the movzx instruction completely }
  11888. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11889. begin
  11890. { Hp1 is a better position than p for debugging purposes }
  11891. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11892. RemoveCurrentp(p, hp1);
  11893. Result := True;
  11894. end;
  11895. Exit;
  11896. end;
  11897. end;
  11898. end;
  11899. {$ifdef x86_64}
  11900. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11901. var
  11902. PreMessage, RegName: string;
  11903. begin
  11904. { Code size reduction by J. Gareth "Kit" Moreton }
  11905. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11906. as this removes the REX prefix }
  11907. Result := False;
  11908. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11909. Exit;
  11910. if taicpu(p).oper[0]^.typ <> top_reg then
  11911. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11912. InternalError(2018011500);
  11913. case taicpu(p).opsize of
  11914. S_Q:
  11915. begin
  11916. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11917. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11918. { The actual optimization }
  11919. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11920. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11921. taicpu(p).changeopsize(S_L);
  11922. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11923. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11924. end;
  11925. else
  11926. ;
  11927. end;
  11928. end;
  11929. {$endif}
  11930. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11931. var
  11932. XReg: TRegister;
  11933. begin
  11934. Result := False;
  11935. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11936. Smaller encoding and slightly faster on some platforms (also works for
  11937. ZMM-sized registers) }
  11938. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11939. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11940. begin
  11941. XReg := taicpu(p).oper[0]^.reg;
  11942. if (taicpu(p).oper[1]^.reg = XReg) then
  11943. begin
  11944. taicpu(p).changeopsize(S_XMM);
  11945. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11946. if (cs_opt_size in current_settings.optimizerswitches) then
  11947. begin
  11948. { Change input registers to %xmm0 to reduce size. Note that
  11949. there's a risk of a false dependency doing this, so only
  11950. optimise for size here }
  11951. XReg := NR_XMM0;
  11952. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11953. end
  11954. else
  11955. begin
  11956. setsubreg(XReg, R_SUBMMX);
  11957. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11958. end;
  11959. taicpu(p).oper[0]^.reg := XReg;
  11960. taicpu(p).oper[1]^.reg := XReg;
  11961. Result := True;
  11962. end;
  11963. end;
  11964. end;
  11965. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11966. var
  11967. OperIdx: Integer;
  11968. begin
  11969. for OperIdx := 0 to p.ops - 1 do
  11970. if p.oper[OperIdx]^.typ = top_ref then
  11971. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11972. end;
  11973. end.