aoptx86.pas 625 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p : tai) : boolean; static;
  102. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  103. conversion was successful }
  104. function ConvertLEA(const p : taicpu): Boolean;
  105. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  106. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  107. procedure DebugMsg(const s : string; p : tai);inline;
  108. class function IsExitCode(p : tai) : boolean; static;
  109. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  110. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  111. procedure RemoveLastDeallocForFuncRes(p : tai);
  112. function DoArithCombineOpt(var p : tai) : Boolean;
  113. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  114. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  115. function PrePeepholeOptSxx(var p : tai) : boolean;
  116. function PrePeepholeOptIMUL(var p : tai) : boolean;
  117. function PrePeepholeOptAND(var p : tai) : boolean;
  118. function OptPass1Test(var p: tai): boolean;
  119. function OptPass1Add(var p: tai): boolean;
  120. function OptPass1AND(var p : tai) : boolean;
  121. function OptPass1_V_MOVAP(var p : tai) : boolean;
  122. function OptPass1VOP(var p : tai) : boolean;
  123. function OptPass1MOV(var p : tai) : boolean;
  124. function OptPass1Movx(var p : tai) : boolean;
  125. function OptPass1MOVXX(var p : tai) : boolean;
  126. function OptPass1OP(var p : tai) : boolean;
  127. function OptPass1LEA(var p : tai) : boolean;
  128. function OptPass1Sub(var p : tai) : boolean;
  129. function OptPass1SHLSAL(var p : tai) : boolean;
  130. function OptPass1SHR(var p : tai) : boolean;
  131. function OptPass1FSTP(var p : tai) : boolean;
  132. function OptPass1FLD(var p : tai) : boolean;
  133. function OptPass1Cmp(var p : tai) : boolean;
  134. function OptPass1PXor(var p : tai) : boolean;
  135. function OptPass1VPXor(var p: tai): boolean;
  136. function OptPass1Imul(var p : tai) : boolean;
  137. function OptPass1Jcc(var p : tai) : boolean;
  138. function OptPass1SHXX(var p: tai): boolean;
  139. function OptPass1VMOVDQ(var p: tai): Boolean;
  140. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  141. function OptPass2Movx(var p : tai): Boolean;
  142. function OptPass2MOV(var p : tai) : boolean;
  143. function OptPass2Imul(var p : tai) : boolean;
  144. function OptPass2Jmp(var p : tai) : boolean;
  145. function OptPass2Jcc(var p : tai) : boolean;
  146. function OptPass2Lea(var p: tai): Boolean;
  147. function OptPass2SUB(var p: tai): Boolean;
  148. function OptPass2ADD(var p : tai): Boolean;
  149. function OptPass2SETcc(var p : tai) : boolean;
  150. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  151. function PostPeepholeOptMov(var p : tai) : Boolean;
  152. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  153. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  154. function PostPeepholeOptXor(var p : tai) : Boolean;
  155. {$endif x86_64}
  156. function PostPeepholeOptAnd(var p : tai) : boolean;
  157. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  158. function PostPeepholeOptCmp(var p : tai) : Boolean;
  159. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  160. function PostPeepholeOptCall(var p : tai) : Boolean;
  161. function PostPeepholeOptLea(var p : tai) : Boolean;
  162. function PostPeepholeOptPush(var p: tai): Boolean;
  163. function PostPeepholeOptShr(var p : tai) : boolean;
  164. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  165. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  166. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  167. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  168. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  169. { Processor-dependent reference optimisation }
  170. class procedure OptimizeRefs(var p: taicpu); static;
  171. end;
  172. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  173. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  174. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  175. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  176. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  177. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  178. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  179. {$if max_operands>2}
  180. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  181. {$endif max_operands>2}
  182. function RefsEqual(const r1, r2: treference): boolean;
  183. { Note that Result is set to True if the references COULD overlap but the
  184. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  185. might still overlap because %reg2 could be equal to %reg1-4 }
  186. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  187. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  188. { returns true, if ref is a reference using only the registers passed as base and index
  189. and having an offset }
  190. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  191. implementation
  192. uses
  193. cutils,verbose,
  194. systems,
  195. globals,
  196. cpuinfo,
  197. procinfo,
  198. paramgr,
  199. aasmbase,
  200. aoptbase,aoptutils,
  201. symconst,symsym,
  202. cgx86,
  203. itcpugas;
  204. {$ifdef DEBUG_AOPTCPU}
  205. const
  206. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  207. {$else DEBUG_AOPTCPU}
  208. { Empty strings help the optimizer to remove string concatenations that won't
  209. ever appear to the user on release builds. [Kit] }
  210. const
  211. SPeepholeOptimization = '';
  212. {$endif DEBUG_AOPTCPU}
  213. LIST_STEP_SIZE = 4;
  214. type
  215. TJumpTrackingItem = class(TLinkedListItem)
  216. private
  217. FSymbol: TAsmSymbol;
  218. FRefs: LongInt;
  219. public
  220. constructor Create(ASymbol: TAsmSymbol);
  221. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  222. property Symbol: TAsmSymbol read FSymbol;
  223. property Refs: LongInt read FRefs;
  224. end;
  225. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  226. begin
  227. inherited Create;
  228. FSymbol := ASymbol;
  229. FRefs := 0;
  230. end;
  231. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  232. begin
  233. Inc(FRefs);
  234. end;
  235. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. (taicpu(instr).opcode = op) and
  240. ((opsize = []) or (taicpu(instr).opsize in opsize));
  241. end;
  242. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. ((taicpu(instr).opcode = op1) or
  247. (taicpu(instr).opcode = op2)
  248. ) and
  249. ((opsize = []) or (taicpu(instr).opsize in opsize));
  250. end;
  251. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  252. begin
  253. result :=
  254. (instr.typ = ait_instruction) and
  255. ((taicpu(instr).opcode = op1) or
  256. (taicpu(instr).opcode = op2) or
  257. (taicpu(instr).opcode = op3)
  258. ) and
  259. ((opsize = []) or (taicpu(instr).opsize in opsize));
  260. end;
  261. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  262. const opsize : topsizes) : boolean;
  263. var
  264. op : TAsmOp;
  265. begin
  266. result:=false;
  267. if (instr.typ <> ait_instruction) or
  268. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  269. exit;
  270. for op in ops do
  271. begin
  272. if taicpu(instr).opcode = op then
  273. begin
  274. result:=true;
  275. exit;
  276. end;
  277. end;
  278. end;
  279. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  280. begin
  281. result := (oper.typ = top_reg) and (oper.reg = reg);
  282. end;
  283. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  284. begin
  285. result := (oper.typ = top_const) and (oper.val = a);
  286. end;
  287. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  288. begin
  289. result := oper1.typ = oper2.typ;
  290. if result then
  291. case oper1.typ of
  292. top_const:
  293. Result:=oper1.val = oper2.val;
  294. top_reg:
  295. Result:=oper1.reg = oper2.reg;
  296. top_ref:
  297. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  298. else
  299. internalerror(2013102801);
  300. end
  301. end;
  302. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  303. begin
  304. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  305. if result then
  306. case oper1.typ of
  307. top_const:
  308. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  309. top_reg:
  310. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  311. top_ref:
  312. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  313. else
  314. internalerror(2020052401);
  315. end
  316. end;
  317. function RefsEqual(const r1, r2: treference): boolean;
  318. begin
  319. RefsEqual :=
  320. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  321. (r1.relsymbol = r2.relsymbol) and
  322. (r1.segment = r2.segment) and (r1.base = r2.base) and
  323. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  324. (r1.offset = r2.offset) and
  325. (r1.volatility + r2.volatility = []);
  326. end;
  327. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  328. begin
  329. if (r1.symbol<>r2.symbol) then
  330. { If the index registers are different, there's a chance one could
  331. be set so it equals the other symbol }
  332. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  333. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  334. (r1.relsymbol = r2.relsymbol) and
  335. (r1.segment = r2.segment) and (r1.base = r2.base) and
  336. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  337. (r1.volatility + r2.volatility = []) then
  338. { In this case, it all depends on the offsets }
  339. Exit(abs(r1.offset - r2.offset) < Range);
  340. { There's a chance things MIGHT overlap, so take no chances }
  341. Result := True;
  342. end;
  343. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  344. begin
  345. Result:=(ref.offset=0) and
  346. (ref.scalefactor in [0,1]) and
  347. (ref.segment=NR_NO) and
  348. (ref.symbol=nil) and
  349. (ref.relsymbol=nil) and
  350. ((base=NR_INVALID) or
  351. (ref.base=base)) and
  352. ((index=NR_INVALID) or
  353. (ref.index=index)) and
  354. (ref.volatility=[]);
  355. end;
  356. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  357. begin
  358. Result:=(ref.scalefactor in [0,1]) and
  359. (ref.segment=NR_NO) and
  360. (ref.symbol=nil) and
  361. (ref.relsymbol=nil) and
  362. ((base=NR_INVALID) or
  363. (ref.base=base)) and
  364. ((index=NR_INVALID) or
  365. (ref.index=index)) and
  366. (ref.volatility=[]);
  367. end;
  368. function InstrReadsFlags(p: tai): boolean;
  369. begin
  370. InstrReadsFlags := true;
  371. case p.typ of
  372. ait_instruction:
  373. if InsProp[taicpu(p).opcode].Ch*
  374. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  375. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  376. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  377. exit;
  378. ait_label:
  379. exit;
  380. else
  381. ;
  382. end;
  383. InstrReadsFlags := false;
  384. end;
  385. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  386. begin
  387. Next:=Current;
  388. repeat
  389. Result:=GetNextInstruction(Next,Next);
  390. until not (Result) or
  391. not(cs_opt_level3 in current_settings.optimizerswitches) or
  392. (Next.typ<>ait_instruction) or
  393. RegInInstruction(reg,Next) or
  394. is_calljmp(taicpu(Next).opcode);
  395. end;
  396. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  397. var
  398. GetNextResult: Boolean;
  399. begin
  400. Result:=0;
  401. Next:=Current;
  402. repeat
  403. GetNextResult := GetNextInstruction(Next,Next);
  404. if GetNextResult then
  405. Inc(Result)
  406. else
  407. { Must return zero upon hitting the end of the linked list without a match }
  408. Result := 0;
  409. until not (GetNextResult) or
  410. not(cs_opt_level3 in current_settings.optimizerswitches) or
  411. (Next.typ<>ait_instruction) or
  412. RegInInstruction(reg,Next) or
  413. is_calljmp(taicpu(Next).opcode);
  414. end;
  415. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  416. procedure TrackJump(Symbol: TAsmSymbol);
  417. var
  418. Search: TJumpTrackingItem;
  419. begin
  420. { See if an entry already exists in our jump tracking list
  421. (faster to search backwards due to the higher chance of
  422. matching destinations) }
  423. Search := TJumpTrackingItem(JumpTracking.Last);
  424. while Assigned(Search) do
  425. begin
  426. if Search.Symbol = Symbol then
  427. begin
  428. { Found it - remove it so it can be pushed to the front }
  429. JumpTracking.Remove(Search);
  430. Break;
  431. end;
  432. Search := TJumpTrackingItem(Search.Previous);
  433. end;
  434. if not Assigned(Search) then
  435. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  436. JumpTracking.Concat(Search);
  437. Search.IncRefs;
  438. end;
  439. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  440. var
  441. Search: TJumpTrackingItem;
  442. begin
  443. Result := False;
  444. { See if this label appears in the tracking list }
  445. Search := TJumpTrackingItem(JumpTracking.Last);
  446. while Assigned(Search) do
  447. begin
  448. if Search.Symbol = Symbol then
  449. begin
  450. { Found it - let's see what we can discover }
  451. if Search.Symbol.getrefs = Search.Refs then
  452. begin
  453. { Success - all the references are accounted for }
  454. JumpTracking.Remove(Search);
  455. Search.Free;
  456. { It is logically impossible for CrossJump to be false here
  457. because we must have run into a conditional jump for
  458. this label at some point }
  459. if not CrossJump then
  460. InternalError(2022041710);
  461. if JumpTracking.First = nil then
  462. { Tracking list is now empty - no more cross jumps }
  463. CrossJump := False;
  464. Result := True;
  465. Exit;
  466. end;
  467. { If the references don't match, it's possible to enter
  468. this label through other means, so drop out }
  469. Exit;
  470. end;
  471. Search := TJumpTrackingItem(Search.Previous);
  472. end;
  473. end;
  474. var
  475. Next_Label: tai;
  476. begin
  477. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  478. Next := Current;
  479. repeat
  480. Result := GetNextInstruction(Next,Next);
  481. if not Result then
  482. Break;
  483. if Next.typ = ait_align then
  484. Result := SkipAligns(Next, Next);
  485. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  486. if is_calljmpuncondret(taicpu(Next).opcode) then
  487. begin
  488. if (taicpu(Next).opcode = A_JMP) and
  489. { Remove dead code now to save time }
  490. RemoveDeadCodeAfterJump(taicpu(Next)) then
  491. { A jump was removed, but not the current instruction, and
  492. Result doesn't necessarily translate into an optimisation
  493. routine's Result, so use the "Force New Iteration" flag so
  494. mark a new pass }
  495. Include(OptsToCheck, aoc_ForceNewIteration);
  496. if not Assigned(JumpTracking) then
  497. begin
  498. { Cross-label optimisations often causes other optimisations
  499. to perform worse because they're not given the chance to
  500. optimise locally. In this case, don't do the cross-label
  501. optimisations yet, but flag them as a potential possibility
  502. for the next iteration of Pass 1 }
  503. if not NotFirstIteration then
  504. Include(OptsToCheck, aoc_ForceNewIteration);
  505. end
  506. else if IsJumpToLabel(taicpu(Next)) and
  507. GetNextInstruction(Next, Next_Label) and
  508. SkipAligns(Next_Label, Next_Label) then
  509. begin
  510. { If we have JMP .lbl, and the label after it has all of its
  511. references tracked, then this is probably an if-else style of
  512. block and we can keep tracking. If the label for this jump
  513. then appears later and is fully tracked, then it's the end
  514. of the if-else blocks and the code paths converge (thus
  515. marking the end of the cross-jump) }
  516. if (Next_Label.typ = ait_label) then
  517. begin
  518. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  519. begin
  520. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  521. Next := Next_Label;
  522. { CrossJump gets set to false by LabelAccountedFor if the
  523. list is completely emptied (as it indicates that all
  524. code paths have converged). We could avoid this nuance
  525. by moving the TrackJump call to before the
  526. LabelAccountedFor call, but this is slower in situations
  527. where LabelAccountedFor would return False due to the
  528. creation of a new object that is not used and destroyed
  529. soon after. }
  530. CrossJump := True;
  531. Continue;
  532. end;
  533. end
  534. else if (Next_Label.typ <> ait_marker) then
  535. { We just did a RemoveDeadCodeAfterJump, so either we find
  536. a label, the end of the procedure or some kind of marker}
  537. InternalError(2022041720);
  538. end;
  539. Result := False;
  540. Exit;
  541. end
  542. else
  543. begin
  544. if not Assigned(JumpTracking) then
  545. begin
  546. { Cross-label optimisations often causes other optimisations
  547. to perform worse because they're not given the chance to
  548. optimise locally. In this case, don't do the cross-label
  549. optimisations yet, but flag them as a potential possibility
  550. for the next iteration of Pass 1 }
  551. if not NotFirstIteration then
  552. Include(OptsToCheck, aoc_ForceNewIteration);
  553. end
  554. else if IsJumpToLabel(taicpu(Next)) then
  555. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  556. else
  557. { Conditional jumps should always be a jump to label }
  558. InternalError(2022041701);
  559. CrossJump := True;
  560. Continue;
  561. end;
  562. if Next.typ = ait_label then
  563. begin
  564. if not Assigned(JumpTracking) then
  565. begin
  566. { Cross-label optimisations often causes other optimisations
  567. to perform worse because they're not given the chance to
  568. optimise locally. In this case, don't do the cross-label
  569. optimisations yet, but flag them as a potential possibility
  570. for the next iteration of Pass 1 }
  571. if not NotFirstIteration then
  572. Include(OptsToCheck, aoc_ForceNewIteration);
  573. end
  574. else if LabelAccountedFor(tai_label(Next).labsym) then
  575. Continue;
  576. { If we reach here, we're at a label that hasn't been seen before
  577. (or JumpTracking was nil) }
  578. Break;
  579. end;
  580. until not Result or
  581. not (cs_opt_level3 in current_settings.optimizerswitches) or
  582. not (Next.typ in [ait_label, ait_instruction]) or
  583. RegInInstruction(reg,Next);
  584. end;
  585. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  586. begin
  587. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  588. begin
  589. Result:=GetNextInstruction(Current,Next);
  590. exit;
  591. end;
  592. Next:=tai(Current.Next);
  593. Result:=false;
  594. while assigned(Next) do
  595. begin
  596. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  597. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  598. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  599. exit
  600. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  601. begin
  602. Result:=true;
  603. exit;
  604. end;
  605. Next:=tai(Next.Next);
  606. end;
  607. end;
  608. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  609. begin
  610. Result:=RegReadByInstruction(reg,hp);
  611. end;
  612. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  613. var
  614. p: taicpu;
  615. opcount: longint;
  616. begin
  617. RegReadByInstruction := false;
  618. if hp.typ <> ait_instruction then
  619. exit;
  620. p := taicpu(hp);
  621. case p.opcode of
  622. A_CALL:
  623. regreadbyinstruction := true;
  624. A_IMUL:
  625. case p.ops of
  626. 1:
  627. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  628. (
  629. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  630. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  631. );
  632. 2,3:
  633. regReadByInstruction :=
  634. reginop(reg,p.oper[0]^) or
  635. reginop(reg,p.oper[1]^);
  636. else
  637. InternalError(2019112801);
  638. end;
  639. A_MUL:
  640. begin
  641. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  642. (
  643. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  644. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  645. );
  646. end;
  647. A_IDIV,A_DIV:
  648. begin
  649. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  650. (
  651. (getregtype(reg)=R_INTREGISTER) and
  652. (
  653. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  654. )
  655. );
  656. end;
  657. else
  658. begin
  659. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  660. begin
  661. RegReadByInstruction := false;
  662. exit;
  663. end;
  664. for opcount := 0 to p.ops-1 do
  665. if (p.oper[opCount]^.typ = top_ref) and
  666. RegInRef(reg,p.oper[opcount]^.ref^) then
  667. begin
  668. RegReadByInstruction := true;
  669. exit
  670. end;
  671. { special handling for SSE MOVSD }
  672. if (p.opcode=A_MOVSD) and (p.ops>0) then
  673. begin
  674. if p.ops<>2 then
  675. internalerror(2017042702);
  676. regReadByInstruction := reginop(reg,p.oper[0]^) or
  677. (
  678. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  679. );
  680. exit;
  681. end;
  682. with insprop[p.opcode] do
  683. begin
  684. case getregtype(reg) of
  685. R_INTREGISTER:
  686. begin
  687. case getsupreg(reg) of
  688. RS_EAX:
  689. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  690. begin
  691. RegReadByInstruction := true;
  692. exit
  693. end;
  694. RS_ECX:
  695. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  696. begin
  697. RegReadByInstruction := true;
  698. exit
  699. end;
  700. RS_EDX:
  701. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  702. begin
  703. RegReadByInstruction := true;
  704. exit
  705. end;
  706. RS_EBX:
  707. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  708. begin
  709. RegReadByInstruction := true;
  710. exit
  711. end;
  712. RS_ESP:
  713. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  714. begin
  715. RegReadByInstruction := true;
  716. exit
  717. end;
  718. RS_EBP:
  719. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  720. begin
  721. RegReadByInstruction := true;
  722. exit
  723. end;
  724. RS_ESI:
  725. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  726. begin
  727. RegReadByInstruction := true;
  728. exit
  729. end;
  730. RS_EDI:
  731. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  732. begin
  733. RegReadByInstruction := true;
  734. exit
  735. end;
  736. end;
  737. end;
  738. R_MMREGISTER:
  739. begin
  740. case getsupreg(reg) of
  741. RS_XMM0:
  742. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  743. begin
  744. RegReadByInstruction := true;
  745. exit
  746. end;
  747. end;
  748. end;
  749. else
  750. ;
  751. end;
  752. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  753. begin
  754. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  755. begin
  756. case p.condition of
  757. C_A,C_NBE, { CF=0 and ZF=0 }
  758. C_BE,C_NA: { CF=1 or ZF=1 }
  759. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  760. C_AE,C_NB,C_NC, { CF=0 }
  761. C_B,C_NAE,C_C: { CF=1 }
  762. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  763. C_NE,C_NZ, { ZF=0 }
  764. C_E,C_Z: { ZF=1 }
  765. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  766. C_G,C_NLE, { ZF=0 and SF=OF }
  767. C_LE,C_NG: { ZF=1 or SF<>OF }
  768. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  769. C_GE,C_NL, { SF=OF }
  770. C_L,C_NGE: { SF<>OF }
  771. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  772. C_NO, { OF=0 }
  773. C_O: { OF=1 }
  774. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  775. C_NP,C_PO, { PF=0 }
  776. C_P,C_PE: { PF=1 }
  777. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  778. C_NS, { SF=0 }
  779. C_S: { SF=1 }
  780. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  781. else
  782. internalerror(2017042701);
  783. end;
  784. if RegReadByInstruction then
  785. exit;
  786. end;
  787. case getsubreg(reg) of
  788. R_SUBW,R_SUBD,R_SUBQ:
  789. RegReadByInstruction :=
  790. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  791. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  792. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  793. R_SUBFLAGCARRY:
  794. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  795. R_SUBFLAGPARITY:
  796. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  797. R_SUBFLAGAUXILIARY:
  798. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  799. R_SUBFLAGZERO:
  800. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  801. R_SUBFLAGSIGN:
  802. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  803. R_SUBFLAGOVERFLOW:
  804. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  805. R_SUBFLAGINTERRUPT:
  806. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  807. R_SUBFLAGDIRECTION:
  808. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  809. else
  810. internalerror(2017042601);
  811. end;
  812. exit;
  813. end;
  814. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  815. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  816. (p.oper[0]^.reg=p.oper[1]^.reg) then
  817. exit;
  818. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  819. begin
  820. RegReadByInstruction := true;
  821. exit
  822. end;
  823. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  824. begin
  825. RegReadByInstruction := true;
  826. exit
  827. end;
  828. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  829. begin
  830. RegReadByInstruction := true;
  831. exit
  832. end;
  833. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  834. begin
  835. RegReadByInstruction := true;
  836. exit
  837. end;
  838. end;
  839. end;
  840. end;
  841. end;
  842. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  843. begin
  844. result:=false;
  845. if p1.typ<>ait_instruction then
  846. exit;
  847. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  848. exit(true);
  849. if (getregtype(reg)=R_INTREGISTER) and
  850. { change information for xmm movsd are not correct }
  851. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  852. begin
  853. case getsupreg(reg) of
  854. { RS_EAX = RS_RAX on x86-64 }
  855. RS_EAX:
  856. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  857. RS_ECX:
  858. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  859. RS_EDX:
  860. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  861. RS_EBX:
  862. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  863. RS_ESP:
  864. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  865. RS_EBP:
  866. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  867. RS_ESI:
  868. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. RS_EDI:
  870. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. else
  872. ;
  873. end;
  874. if result then
  875. exit;
  876. end
  877. else if getregtype(reg)=R_MMREGISTER then
  878. begin
  879. case getsupreg(reg) of
  880. RS_XMM0:
  881. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  882. else
  883. ;
  884. end;
  885. if result then
  886. exit;
  887. end
  888. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  889. begin
  890. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  891. exit(true);
  892. case getsubreg(reg) of
  893. R_SUBFLAGCARRY:
  894. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. R_SUBFLAGPARITY:
  896. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  897. R_SUBFLAGAUXILIARY:
  898. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  899. R_SUBFLAGZERO:
  900. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  901. R_SUBFLAGSIGN:
  902. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  903. R_SUBFLAGOVERFLOW:
  904. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  905. R_SUBFLAGINTERRUPT:
  906. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. R_SUBFLAGDIRECTION:
  908. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  909. R_SUBW,R_SUBD,R_SUBQ:
  910. { Everything except the direction bits }
  911. Result:=
  912. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  913. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  914. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  915. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  916. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  917. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  918. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  919. else
  920. ;
  921. end;
  922. if result then
  923. exit;
  924. end
  925. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  926. exit(true);
  927. Result:=inherited RegInInstruction(Reg, p1);
  928. end;
  929. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  930. const
  931. WriteOps: array[0..3] of set of TInsChange =
  932. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  933. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  934. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  935. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  936. var
  937. OperIdx: Integer;
  938. begin
  939. Result := False;
  940. if p1.typ <> ait_instruction then
  941. exit;
  942. with insprop[taicpu(p1).opcode] do
  943. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  944. begin
  945. case getsubreg(reg) of
  946. R_SUBW,R_SUBD,R_SUBQ:
  947. Result :=
  948. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  949. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  950. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  951. R_SUBFLAGCARRY:
  952. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  953. R_SUBFLAGPARITY:
  954. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  955. R_SUBFLAGAUXILIARY:
  956. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  957. R_SUBFLAGZERO:
  958. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  959. R_SUBFLAGSIGN:
  960. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  961. R_SUBFLAGOVERFLOW:
  962. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  963. R_SUBFLAGINTERRUPT:
  964. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  965. R_SUBFLAGDIRECTION:
  966. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  967. else
  968. internalerror(2017042602);
  969. end;
  970. exit;
  971. end;
  972. case taicpu(p1).opcode of
  973. A_CALL:
  974. { We could potentially set Result to False if the register in
  975. question is non-volatile for the subroutine's calling convention,
  976. but this would require detecting the calling convention in use and
  977. also assuming that the routine doesn't contain malformed assembly
  978. language, for example... so it could only be done under -O4 as it
  979. would be considered a side-effect. [Kit] }
  980. Result := True;
  981. A_MOVSD:
  982. { special handling for SSE MOVSD }
  983. if (taicpu(p1).ops>0) then
  984. begin
  985. if taicpu(p1).ops<>2 then
  986. internalerror(2017042703);
  987. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  988. end;
  989. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  990. so fix it here (FK)
  991. }
  992. A_VMOVSS,
  993. A_VMOVSD:
  994. begin
  995. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  996. exit;
  997. end;
  998. A_IMUL:
  999. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1000. else
  1001. ;
  1002. end;
  1003. if Result then
  1004. exit;
  1005. with insprop[taicpu(p1).opcode] do
  1006. begin
  1007. if getregtype(reg)=R_INTREGISTER then
  1008. begin
  1009. case getsupreg(reg) of
  1010. RS_EAX:
  1011. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1012. begin
  1013. Result := True;
  1014. exit
  1015. end;
  1016. RS_ECX:
  1017. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1018. begin
  1019. Result := True;
  1020. exit
  1021. end;
  1022. RS_EDX:
  1023. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1024. begin
  1025. Result := True;
  1026. exit
  1027. end;
  1028. RS_EBX:
  1029. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1030. begin
  1031. Result := True;
  1032. exit
  1033. end;
  1034. RS_ESP:
  1035. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1036. begin
  1037. Result := True;
  1038. exit
  1039. end;
  1040. RS_EBP:
  1041. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1042. begin
  1043. Result := True;
  1044. exit
  1045. end;
  1046. RS_ESI:
  1047. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1048. begin
  1049. Result := True;
  1050. exit
  1051. end;
  1052. RS_EDI:
  1053. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1054. begin
  1055. Result := True;
  1056. exit
  1057. end;
  1058. end;
  1059. end;
  1060. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1061. if (WriteOps[OperIdx]*Ch<>[]) and
  1062. { The register doesn't get modified inside a reference }
  1063. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1064. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1065. begin
  1066. Result := true;
  1067. exit
  1068. end;
  1069. end;
  1070. end;
  1071. {$ifdef DEBUG_AOPTCPU}
  1072. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1073. begin
  1074. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1075. end;
  1076. function debug_tostr(i: tcgint): string; inline;
  1077. begin
  1078. Result := tostr(i);
  1079. end;
  1080. function debug_regname(r: TRegister): string; inline;
  1081. begin
  1082. Result := '%' + std_regname(r);
  1083. end;
  1084. { Debug output function - creates a string representation of an operator }
  1085. function debug_operstr(oper: TOper): string;
  1086. begin
  1087. case oper.typ of
  1088. top_const:
  1089. Result := '$' + debug_tostr(oper.val);
  1090. top_reg:
  1091. Result := debug_regname(oper.reg);
  1092. top_ref:
  1093. begin
  1094. if oper.ref^.offset <> 0 then
  1095. Result := debug_tostr(oper.ref^.offset) + '('
  1096. else
  1097. Result := '(';
  1098. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1099. begin
  1100. Result := Result + debug_regname(oper.ref^.base);
  1101. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1102. Result := Result + ',' + debug_regname(oper.ref^.index);
  1103. end
  1104. else
  1105. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1106. Result := Result + debug_regname(oper.ref^.index);
  1107. if (oper.ref^.scalefactor > 1) then
  1108. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1109. else
  1110. Result := Result + ')';
  1111. end;
  1112. else
  1113. Result := '[UNKNOWN]';
  1114. end;
  1115. end;
  1116. function debug_op2str(opcode: tasmop): string; inline;
  1117. begin
  1118. Result := std_op2str[opcode];
  1119. end;
  1120. function debug_opsize2str(opsize: topsize): string; inline;
  1121. begin
  1122. Result := gas_opsize2str[opsize];
  1123. end;
  1124. {$else DEBUG_AOPTCPU}
  1125. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1126. begin
  1127. end;
  1128. function debug_tostr(i: tcgint): string; inline;
  1129. begin
  1130. Result := '';
  1131. end;
  1132. function debug_regname(r: TRegister): string; inline;
  1133. begin
  1134. Result := '';
  1135. end;
  1136. function debug_operstr(oper: TOper): string; inline;
  1137. begin
  1138. Result := '';
  1139. end;
  1140. function debug_op2str(opcode: tasmop): string; inline;
  1141. begin
  1142. Result := '';
  1143. end;
  1144. function debug_opsize2str(opsize: topsize): string; inline;
  1145. begin
  1146. Result := '';
  1147. end;
  1148. {$endif DEBUG_AOPTCPU}
  1149. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1150. begin
  1151. {$ifdef x86_64}
  1152. { Always fine on x86-64 }
  1153. Result := True;
  1154. {$else x86_64}
  1155. Result :=
  1156. {$ifdef i8086}
  1157. (current_settings.cputype >= cpu_386) and
  1158. {$endif i8086}
  1159. (
  1160. { Always accept if optimising for size }
  1161. (cs_opt_size in current_settings.optimizerswitches) or
  1162. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1163. (current_settings.optimizecputype >= cpu_Pentium2)
  1164. );
  1165. {$endif x86_64}
  1166. end;
  1167. { Attempts to allocate a volatile integer register for use between p and hp,
  1168. using AUsedRegs for the current register usage information. Returns NR_NO
  1169. if no free register could be found }
  1170. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1171. var
  1172. RegSet: TCPURegisterSet;
  1173. CurrentSuperReg: Integer;
  1174. CurrentReg: TRegister;
  1175. Currentp: tai;
  1176. Breakout: Boolean;
  1177. begin
  1178. Result := NR_NO;
  1179. RegSet :=
  1180. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1181. current_procinfo.saved_regs_int;
  1182. for CurrentSuperReg in RegSet do
  1183. begin
  1184. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1185. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1186. {$if defined(i386) or defined(i8086)}
  1187. { If the target size is 8-bit, make sure we can actually encode it }
  1188. and (
  1189. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1190. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1191. )
  1192. {$endif i386 or i8086}
  1193. then
  1194. begin
  1195. Currentp := p;
  1196. Breakout := False;
  1197. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1198. begin
  1199. case Currentp.typ of
  1200. ait_instruction:
  1201. begin
  1202. if RegInInstruction(CurrentReg, Currentp) then
  1203. begin
  1204. Breakout := True;
  1205. Break;
  1206. end;
  1207. { Cannot allocate across an unconditional jump }
  1208. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1209. Exit;
  1210. end;
  1211. ait_marker:
  1212. { Don't try anything more if a marker is hit }
  1213. Exit;
  1214. ait_regalloc:
  1215. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1216. begin
  1217. Breakout := True;
  1218. Break;
  1219. end;
  1220. else
  1221. ;
  1222. end;
  1223. end;
  1224. if Breakout then
  1225. { Try the next register }
  1226. Continue;
  1227. { We have a free register available }
  1228. Result := CurrentReg;
  1229. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1230. Exit;
  1231. end;
  1232. end;
  1233. end;
  1234. { Attempts to allocate a volatile MM register for use between p and hp,
  1235. using AUsedRegs for the current register usage information. Returns NR_NO
  1236. if no free register could be found }
  1237. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1238. var
  1239. RegSet: TCPURegisterSet;
  1240. CurrentSuperReg: Integer;
  1241. CurrentReg: TRegister;
  1242. Currentp: tai;
  1243. Breakout: Boolean;
  1244. begin
  1245. Result := NR_NO;
  1246. RegSet :=
  1247. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1248. current_procinfo.saved_regs_mm;
  1249. for CurrentSuperReg in RegSet do
  1250. begin
  1251. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1252. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1253. begin
  1254. Currentp := p;
  1255. Breakout := False;
  1256. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1257. begin
  1258. case Currentp.typ of
  1259. ait_instruction:
  1260. begin
  1261. if RegInInstruction(CurrentReg, Currentp) then
  1262. begin
  1263. Breakout := True;
  1264. Break;
  1265. end;
  1266. { Cannot allocate across an unconditional jump }
  1267. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1268. Exit;
  1269. end;
  1270. ait_marker:
  1271. { Don't try anything more if a marker is hit }
  1272. Exit;
  1273. ait_regalloc:
  1274. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1275. begin
  1276. Breakout := True;
  1277. Break;
  1278. end;
  1279. else
  1280. ;
  1281. end;
  1282. end;
  1283. if Breakout then
  1284. { Try the next register }
  1285. Continue;
  1286. { We have a free register available }
  1287. Result := CurrentReg;
  1288. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1289. Exit;
  1290. end;
  1291. end;
  1292. end;
  1293. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1294. begin
  1295. if not SuperRegistersEqual(reg1,reg2) then
  1296. exit(false);
  1297. if getregtype(reg1)<>R_INTREGISTER then
  1298. exit(true); {because SuperRegisterEqual is true}
  1299. case getsubreg(reg1) of
  1300. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1301. higher, it preserves the high bits, so the new value depends on
  1302. reg2's previous value. In other words, it is equivalent to doing:
  1303. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1304. R_SUBL:
  1305. exit(getsubreg(reg2)=R_SUBL);
  1306. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1307. higher, it actually does a:
  1308. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1309. R_SUBH:
  1310. exit(getsubreg(reg2)=R_SUBH);
  1311. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1312. bits of reg2:
  1313. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1314. R_SUBW:
  1315. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1316. { a write to R_SUBD always overwrites every other subregister,
  1317. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1318. R_SUBD,
  1319. R_SUBQ:
  1320. exit(true);
  1321. else
  1322. internalerror(2017042801);
  1323. end;
  1324. end;
  1325. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1326. begin
  1327. if not SuperRegistersEqual(reg1,reg2) then
  1328. exit(false);
  1329. if getregtype(reg1)<>R_INTREGISTER then
  1330. exit(true); {because SuperRegisterEqual is true}
  1331. case getsubreg(reg1) of
  1332. R_SUBL:
  1333. exit(getsubreg(reg2)<>R_SUBH);
  1334. R_SUBH:
  1335. exit(getsubreg(reg2)<>R_SUBL);
  1336. R_SUBW,
  1337. R_SUBD,
  1338. R_SUBQ:
  1339. exit(true);
  1340. else
  1341. internalerror(2017042802);
  1342. end;
  1343. end;
  1344. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1345. var
  1346. hp1 : tai;
  1347. l : TCGInt;
  1348. begin
  1349. result:=false;
  1350. { changes the code sequence
  1351. shr/sar const1, x
  1352. shl const2, x
  1353. to
  1354. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1355. if GetNextInstruction(p, hp1) and
  1356. MatchInstruction(hp1,A_SHL,[]) and
  1357. (taicpu(p).oper[0]^.typ = top_const) and
  1358. (taicpu(hp1).oper[0]^.typ = top_const) and
  1359. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1360. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1361. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1362. begin
  1363. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1364. not(cs_opt_size in current_settings.optimizerswitches) then
  1365. begin
  1366. { shr/sar const1, %reg
  1367. shl const2, %reg
  1368. with const1 > const2 }
  1369. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1370. taicpu(hp1).opcode := A_AND;
  1371. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1372. case taicpu(p).opsize Of
  1373. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1374. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1375. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1376. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1377. else
  1378. Internalerror(2017050703)
  1379. end;
  1380. end
  1381. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1382. not(cs_opt_size in current_settings.optimizerswitches) then
  1383. begin
  1384. { shr/sar const1, %reg
  1385. shl const2, %reg
  1386. with const1 < const2 }
  1387. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1388. taicpu(p).opcode := A_AND;
  1389. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1390. case taicpu(p).opsize Of
  1391. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1392. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1393. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1394. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1395. else
  1396. Internalerror(2017050702)
  1397. end;
  1398. end
  1399. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1400. begin
  1401. { shr/sar const1, %reg
  1402. shl const2, %reg
  1403. with const1 = const2 }
  1404. taicpu(p).opcode := A_AND;
  1405. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1406. case taicpu(p).opsize Of
  1407. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1408. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1409. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1410. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1411. else
  1412. Internalerror(2017050701)
  1413. end;
  1414. RemoveInstruction(hp1);
  1415. end;
  1416. end;
  1417. end;
  1418. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1419. var
  1420. opsize : topsize;
  1421. hp1, hp2 : tai;
  1422. tmpref : treference;
  1423. ShiftValue : Cardinal;
  1424. BaseValue : TCGInt;
  1425. begin
  1426. result:=false;
  1427. opsize:=taicpu(p).opsize;
  1428. { changes certain "imul const, %reg"'s to lea sequences }
  1429. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1430. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1431. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1432. if (taicpu(p).oper[0]^.val = 1) then
  1433. if (taicpu(p).ops = 2) then
  1434. { remove "imul $1, reg" }
  1435. begin
  1436. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1437. Result := RemoveCurrentP(p);
  1438. end
  1439. else
  1440. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1441. begin
  1442. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1443. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1444. asml.InsertAfter(hp1, p);
  1445. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1446. RemoveCurrentP(p, hp1);
  1447. Result := True;
  1448. end
  1449. else if ((taicpu(p).ops <= 2) or
  1450. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1451. not(cs_opt_size in current_settings.optimizerswitches) and
  1452. (not(GetNextInstruction(p, hp1)) or
  1453. not((tai(hp1).typ = ait_instruction) and
  1454. ((taicpu(hp1).opcode=A_Jcc) and
  1455. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1456. begin
  1457. {
  1458. imul X, reg1, reg2 to
  1459. lea (reg1,reg1,Y), reg2
  1460. shl ZZ,reg2
  1461. imul XX, reg1 to
  1462. lea (reg1,reg1,YY), reg1
  1463. shl ZZ,reg2
  1464. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1465. it does not exist as a separate optimization target in FPC though.
  1466. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1467. at most two zeros
  1468. }
  1469. reference_reset(tmpref,1,[]);
  1470. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1471. begin
  1472. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1473. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1474. TmpRef.base := taicpu(p).oper[1]^.reg;
  1475. TmpRef.index := taicpu(p).oper[1]^.reg;
  1476. if not(BaseValue in [3,5,9]) then
  1477. Internalerror(2018110101);
  1478. TmpRef.ScaleFactor := BaseValue-1;
  1479. if (taicpu(p).ops = 2) then
  1480. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1481. else
  1482. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1483. AsmL.InsertAfter(hp1,p);
  1484. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1485. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1486. RemoveCurrentP(p, hp1);
  1487. if ShiftValue>0 then
  1488. begin
  1489. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1490. AsmL.InsertAfter(hp2,hp1);
  1491. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1492. end;
  1493. Result := True;
  1494. end;
  1495. end;
  1496. end;
  1497. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1498. begin
  1499. Result := False;
  1500. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1501. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1502. begin
  1503. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1504. taicpu(p).opcode := A_MOV;
  1505. Result := True;
  1506. end;
  1507. end;
  1508. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1509. var
  1510. p: taicpu absolute hp; { Implicit typecast }
  1511. i: Integer;
  1512. begin
  1513. Result := False;
  1514. if not assigned(hp) or
  1515. (hp.typ <> ait_instruction) then
  1516. Exit;
  1517. Prefetch(insprop[p.opcode]);
  1518. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1519. with insprop[p.opcode] do
  1520. begin
  1521. case getsubreg(reg) of
  1522. R_SUBW,R_SUBD,R_SUBQ:
  1523. Result:=
  1524. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1525. uncommon flags are checked first }
  1526. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1527. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1528. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1529. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1530. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1531. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1532. R_SUBFLAGCARRY:
  1533. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1534. R_SUBFLAGPARITY:
  1535. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1536. R_SUBFLAGAUXILIARY:
  1537. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1538. R_SUBFLAGZERO:
  1539. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1540. R_SUBFLAGSIGN:
  1541. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1542. R_SUBFLAGOVERFLOW:
  1543. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1544. R_SUBFLAGINTERRUPT:
  1545. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1546. R_SUBFLAGDIRECTION:
  1547. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1548. else
  1549. internalerror(2017050501);
  1550. end;
  1551. exit;
  1552. end;
  1553. { Handle special cases first }
  1554. case p.opcode of
  1555. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1556. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1557. begin
  1558. Result :=
  1559. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1560. (p.oper[1]^.typ = top_reg) and
  1561. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1562. (
  1563. (p.oper[0]^.typ = top_const) or
  1564. (
  1565. (p.oper[0]^.typ = top_reg) and
  1566. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1567. ) or (
  1568. (p.oper[0]^.typ = top_ref) and
  1569. not RegInRef(reg,p.oper[0]^.ref^)
  1570. )
  1571. );
  1572. end;
  1573. A_MUL, A_IMUL:
  1574. Result :=
  1575. (
  1576. (p.ops=3) and { IMUL only }
  1577. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1578. (
  1579. (
  1580. (p.oper[1]^.typ=top_reg) and
  1581. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1582. ) or (
  1583. (p.oper[1]^.typ=top_ref) and
  1584. not RegInRef(reg,p.oper[1]^.ref^)
  1585. )
  1586. )
  1587. ) or (
  1588. (
  1589. (p.ops=1) and
  1590. (
  1591. (
  1592. (
  1593. (p.oper[0]^.typ=top_reg) and
  1594. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1595. )
  1596. ) or (
  1597. (p.oper[0]^.typ=top_ref) and
  1598. not RegInRef(reg,p.oper[0]^.ref^)
  1599. )
  1600. ) and (
  1601. (
  1602. (p.opsize=S_B) and
  1603. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1604. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1605. ) or (
  1606. (p.opsize=S_W) and
  1607. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1608. ) or (
  1609. (p.opsize=S_L) and
  1610. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1611. {$ifdef x86_64}
  1612. ) or (
  1613. (p.opsize=S_Q) and
  1614. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1615. {$endif x86_64}
  1616. )
  1617. )
  1618. )
  1619. );
  1620. A_CBW:
  1621. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1622. {$ifndef x86_64}
  1623. A_LDS:
  1624. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1625. A_LES:
  1626. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1627. {$endif not x86_64}
  1628. A_LFS:
  1629. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1630. A_LGS:
  1631. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1632. A_LSS:
  1633. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1634. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1635. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1636. A_LODSB:
  1637. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1638. A_LODSW:
  1639. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1640. {$ifdef x86_64}
  1641. A_LODSQ:
  1642. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1643. {$endif x86_64}
  1644. A_LODSD:
  1645. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1646. A_FSTSW, A_FNSTSW:
  1647. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1648. else
  1649. begin
  1650. with insprop[p.opcode] do
  1651. begin
  1652. if (
  1653. { xor %reg,%reg etc. is classed as a new value }
  1654. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1655. MatchOpType(p, top_reg, top_reg) and
  1656. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1657. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1658. ) then
  1659. begin
  1660. Result := True;
  1661. Exit;
  1662. end;
  1663. { Make sure the entire register is overwritten }
  1664. if (getregtype(reg) = R_INTREGISTER) then
  1665. begin
  1666. if (p.ops > 0) then
  1667. begin
  1668. if RegInOp(reg, p.oper[0]^) then
  1669. begin
  1670. if (p.oper[0]^.typ = top_ref) then
  1671. begin
  1672. if RegInRef(reg, p.oper[0]^.ref^) then
  1673. begin
  1674. Result := False;
  1675. Exit;
  1676. end;
  1677. end
  1678. else if (p.oper[0]^.typ = top_reg) then
  1679. begin
  1680. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1681. begin
  1682. Result := False;
  1683. Exit;
  1684. end
  1685. else if ([Ch_WOp1]*Ch<>[]) then
  1686. begin
  1687. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1688. Result := True
  1689. else
  1690. begin
  1691. Result := False;
  1692. Exit;
  1693. end;
  1694. end;
  1695. end;
  1696. end;
  1697. if (p.ops > 1) then
  1698. begin
  1699. if RegInOp(reg, p.oper[1]^) then
  1700. begin
  1701. if (p.oper[1]^.typ = top_ref) then
  1702. begin
  1703. if RegInRef(reg, p.oper[1]^.ref^) then
  1704. begin
  1705. Result := False;
  1706. Exit;
  1707. end;
  1708. end
  1709. else if (p.oper[1]^.typ = top_reg) then
  1710. begin
  1711. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1712. begin
  1713. Result := False;
  1714. Exit;
  1715. end
  1716. else if ([Ch_WOp2]*Ch<>[]) then
  1717. begin
  1718. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1719. Result := True
  1720. else
  1721. begin
  1722. Result := False;
  1723. Exit;
  1724. end;
  1725. end;
  1726. end;
  1727. end;
  1728. if (p.ops > 2) then
  1729. begin
  1730. if RegInOp(reg, p.oper[2]^) then
  1731. begin
  1732. if (p.oper[2]^.typ = top_ref) then
  1733. begin
  1734. if RegInRef(reg, p.oper[2]^.ref^) then
  1735. begin
  1736. Result := False;
  1737. Exit;
  1738. end;
  1739. end
  1740. else if (p.oper[2]^.typ = top_reg) then
  1741. begin
  1742. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1743. begin
  1744. Result := False;
  1745. Exit;
  1746. end
  1747. else if ([Ch_WOp3]*Ch<>[]) then
  1748. begin
  1749. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1750. Result := True
  1751. else
  1752. begin
  1753. Result := False;
  1754. Exit;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1760. begin
  1761. if (p.oper[3]^.typ = top_ref) then
  1762. begin
  1763. if RegInRef(reg, p.oper[3]^.ref^) then
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end
  1769. else if (p.oper[3]^.typ = top_reg) then
  1770. begin
  1771. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1772. begin
  1773. Result := False;
  1774. Exit;
  1775. end
  1776. else if ([Ch_WOp4]*Ch<>[]) then
  1777. begin
  1778. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1779. Result := True
  1780. else
  1781. begin
  1782. Result := False;
  1783. Exit;
  1784. end;
  1785. end;
  1786. end;
  1787. end;
  1788. end;
  1789. end;
  1790. end;
  1791. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1792. case getsupreg(reg) of
  1793. RS_EAX:
  1794. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1795. begin
  1796. Result := True;
  1797. Exit;
  1798. end;
  1799. RS_ECX:
  1800. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1801. begin
  1802. Result := True;
  1803. Exit;
  1804. end;
  1805. RS_EDX:
  1806. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1807. begin
  1808. Result := True;
  1809. Exit;
  1810. end;
  1811. RS_EBX:
  1812. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1813. begin
  1814. Result := True;
  1815. Exit;
  1816. end;
  1817. RS_ESP:
  1818. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1819. begin
  1820. Result := True;
  1821. Exit;
  1822. end;
  1823. RS_EBP:
  1824. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1825. begin
  1826. Result := True;
  1827. Exit;
  1828. end;
  1829. RS_ESI:
  1830. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1831. begin
  1832. Result := True;
  1833. Exit;
  1834. end;
  1835. RS_EDI:
  1836. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1837. begin
  1838. Result := True;
  1839. Exit;
  1840. end;
  1841. else
  1842. ;
  1843. end;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. end;
  1849. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1850. var
  1851. hp2,hp3 : tai;
  1852. begin
  1853. { some x86-64 issue a NOP before the real exit code }
  1854. if MatchInstruction(p,A_NOP,[]) then
  1855. GetNextInstruction(p,p);
  1856. result:=assigned(p) and (p.typ=ait_instruction) and
  1857. ((taicpu(p).opcode = A_RET) or
  1858. ((taicpu(p).opcode=A_LEAVE) and
  1859. GetNextInstruction(p,hp2) and
  1860. MatchInstruction(hp2,A_RET,[S_NO])
  1861. ) or
  1862. (((taicpu(p).opcode=A_LEA) and
  1863. MatchOpType(taicpu(p),top_ref,top_reg) and
  1864. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1865. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1866. ) and
  1867. GetNextInstruction(p,hp2) and
  1868. MatchInstruction(hp2,A_RET,[S_NO])
  1869. ) or
  1870. ((((taicpu(p).opcode=A_MOV) and
  1871. MatchOpType(taicpu(p),top_reg,top_reg) and
  1872. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1873. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1874. ((taicpu(p).opcode=A_LEA) and
  1875. MatchOpType(taicpu(p),top_ref,top_reg) and
  1876. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1877. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1878. )
  1879. ) and
  1880. GetNextInstruction(p,hp2) and
  1881. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1882. MatchOpType(taicpu(hp2),top_reg) and
  1883. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1884. GetNextInstruction(hp2,hp3) and
  1885. MatchInstruction(hp3,A_RET,[S_NO])
  1886. )
  1887. );
  1888. end;
  1889. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1890. begin
  1891. isFoldableArithOp := False;
  1892. case hp1.opcode of
  1893. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1894. isFoldableArithOp :=
  1895. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1896. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1897. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1898. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1899. (taicpu(hp1).oper[1]^.reg = reg);
  1900. A_INC,A_DEC,A_NEG,A_NOT:
  1901. isFoldableArithOp :=
  1902. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1903. (taicpu(hp1).oper[0]^.reg = reg);
  1904. else
  1905. ;
  1906. end;
  1907. end;
  1908. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1909. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1910. var
  1911. hp2: tai;
  1912. begin
  1913. hp2 := p;
  1914. repeat
  1915. hp2 := tai(hp2.previous);
  1916. if assigned(hp2) and
  1917. (hp2.typ = ait_regalloc) and
  1918. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1919. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1920. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1921. begin
  1922. RemoveInstruction(hp2);
  1923. break;
  1924. end;
  1925. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1926. end;
  1927. begin
  1928. case current_procinfo.procdef.returndef.typ of
  1929. arraydef,recorddef,pointerdef,
  1930. stringdef,enumdef,procdef,objectdef,errordef,
  1931. filedef,setdef,procvardef,
  1932. classrefdef,forwarddef:
  1933. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1934. orddef:
  1935. if current_procinfo.procdef.returndef.size <> 0 then
  1936. begin
  1937. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1938. { for int64/qword }
  1939. if current_procinfo.procdef.returndef.size = 8 then
  1940. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1941. end;
  1942. else
  1943. ;
  1944. end;
  1945. end;
  1946. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1947. var
  1948. hp1,hp2 : tai;
  1949. begin
  1950. result:=false;
  1951. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1952. begin
  1953. { vmova* reg1,reg1
  1954. =>
  1955. <nop> }
  1956. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1957. begin
  1958. RemoveCurrentP(p);
  1959. result:=true;
  1960. exit;
  1961. end
  1962. else if GetNextInstruction(p,hp1) then
  1963. begin
  1964. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1965. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1966. begin
  1967. { vmova* reg1,reg2
  1968. vmova* reg2,reg3
  1969. dealloc reg2
  1970. =>
  1971. vmova* reg1,reg3 }
  1972. TransferUsedRegs(TmpUsedRegs);
  1973. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1974. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1975. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1976. begin
  1977. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1978. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1979. RemoveInstruction(hp1);
  1980. result:=true;
  1981. exit;
  1982. end
  1983. { special case:
  1984. vmova* reg1,<op>
  1985. vmova* <op>,reg1
  1986. =>
  1987. vmova* reg1,<op> }
  1988. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1989. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1990. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1991. ) then
  1992. begin
  1993. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1994. RemoveInstruction(hp1);
  1995. result:=true;
  1996. exit;
  1997. end
  1998. end
  1999. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2000. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2001. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2002. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2003. ) and
  2004. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2005. begin
  2006. { vmova* reg1,reg2
  2007. vmovs* reg2,<op>
  2008. dealloc reg2
  2009. =>
  2010. vmovs* reg1,reg3 }
  2011. TransferUsedRegs(TmpUsedRegs);
  2012. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2013. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2014. begin
  2015. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2016. taicpu(p).opcode:=taicpu(hp1).opcode;
  2017. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2018. RemoveInstruction(hp1);
  2019. result:=true;
  2020. exit;
  2021. end
  2022. end;
  2023. end;
  2024. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2025. begin
  2026. if MatchInstruction(hp1,[A_VFMADDPD,
  2027. A_VFMADD132PD,
  2028. A_VFMADD132PS,
  2029. A_VFMADD132SD,
  2030. A_VFMADD132SS,
  2031. A_VFMADD213PD,
  2032. A_VFMADD213PS,
  2033. A_VFMADD213SD,
  2034. A_VFMADD213SS,
  2035. A_VFMADD231PD,
  2036. A_VFMADD231PS,
  2037. A_VFMADD231SD,
  2038. A_VFMADD231SS,
  2039. A_VFMADDSUB132PD,
  2040. A_VFMADDSUB132PS,
  2041. A_VFMADDSUB213PD,
  2042. A_VFMADDSUB213PS,
  2043. A_VFMADDSUB231PD,
  2044. A_VFMADDSUB231PS,
  2045. A_VFMSUB132PD,
  2046. A_VFMSUB132PS,
  2047. A_VFMSUB132SD,
  2048. A_VFMSUB132SS,
  2049. A_VFMSUB213PD,
  2050. A_VFMSUB213PS,
  2051. A_VFMSUB213SD,
  2052. A_VFMSUB213SS,
  2053. A_VFMSUB231PD,
  2054. A_VFMSUB231PS,
  2055. A_VFMSUB231SD,
  2056. A_VFMSUB231SS,
  2057. A_VFMSUBADD132PD,
  2058. A_VFMSUBADD132PS,
  2059. A_VFMSUBADD213PD,
  2060. A_VFMSUBADD213PS,
  2061. A_VFMSUBADD231PD,
  2062. A_VFMSUBADD231PS,
  2063. A_VFNMADD132PD,
  2064. A_VFNMADD132PS,
  2065. A_VFNMADD132SD,
  2066. A_VFNMADD132SS,
  2067. A_VFNMADD213PD,
  2068. A_VFNMADD213PS,
  2069. A_VFNMADD213SD,
  2070. A_VFNMADD213SS,
  2071. A_VFNMADD231PD,
  2072. A_VFNMADD231PS,
  2073. A_VFNMADD231SD,
  2074. A_VFNMADD231SS,
  2075. A_VFNMSUB132PD,
  2076. A_VFNMSUB132PS,
  2077. A_VFNMSUB132SD,
  2078. A_VFNMSUB132SS,
  2079. A_VFNMSUB213PD,
  2080. A_VFNMSUB213PS,
  2081. A_VFNMSUB213SD,
  2082. A_VFNMSUB213SS,
  2083. A_VFNMSUB231PD,
  2084. A_VFNMSUB231PS,
  2085. A_VFNMSUB231SD,
  2086. A_VFNMSUB231SS],[S_NO]) and
  2087. { we mix single and double opperations here because we assume that the compiler
  2088. generates vmovapd only after double operations and vmovaps only after single operations }
  2089. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2090. GetNextInstruction(hp1,hp2) and
  2091. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2092. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2093. begin
  2094. TransferUsedRegs(TmpUsedRegs);
  2095. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2096. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2097. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2098. begin
  2099. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2100. RemoveCurrentP(p);
  2101. RemoveInstruction(hp2);
  2102. end;
  2103. end
  2104. else if (hp1.typ = ait_instruction) and
  2105. GetNextInstruction(hp1, hp2) and
  2106. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2107. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2108. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2109. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2110. (((taicpu(p).opcode=A_MOVAPS) and
  2111. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2112. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2113. ((taicpu(p).opcode=A_MOVAPD) and
  2114. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2115. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2116. ) then
  2117. { change
  2118. movapX reg,reg2
  2119. addsX/subsX/... reg3, reg2
  2120. movapX reg2,reg
  2121. to
  2122. addsX/subsX/... reg3,reg
  2123. }
  2124. begin
  2125. TransferUsedRegs(TmpUsedRegs);
  2126. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2127. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2128. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2129. begin
  2130. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2131. debug_op2str(taicpu(p).opcode)+' '+
  2132. debug_op2str(taicpu(hp1).opcode)+' '+
  2133. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2134. { we cannot eliminate the first move if
  2135. the operations uses the same register for source and dest }
  2136. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2137. { Remember that hp1 is not necessarily the immediate
  2138. next instruction }
  2139. RemoveCurrentP(p);
  2140. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2141. RemoveInstruction(hp2);
  2142. result:=true;
  2143. end;
  2144. end
  2145. else if (hp1.typ = ait_instruction) and
  2146. (((taicpu(p).opcode=A_VMOVAPD) and
  2147. (taicpu(hp1).opcode=A_VCOMISD)) or
  2148. ((taicpu(p).opcode=A_VMOVAPS) and
  2149. ((taicpu(hp1).opcode=A_VCOMISS))
  2150. )
  2151. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2152. { change
  2153. movapX reg,reg1
  2154. vcomisX reg1,reg1
  2155. to
  2156. vcomisX reg,reg
  2157. }
  2158. begin
  2159. TransferUsedRegs(TmpUsedRegs);
  2160. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2161. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2162. begin
  2163. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2164. debug_op2str(taicpu(p).opcode)+' '+
  2165. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2166. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2167. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2168. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2169. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2170. RemoveCurrentP(p);
  2171. result:=true;
  2172. exit;
  2173. end;
  2174. end
  2175. end;
  2176. end;
  2177. end;
  2178. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2179. var
  2180. hp1 : tai;
  2181. begin
  2182. result:=false;
  2183. { replace
  2184. V<Op>X %mreg1,%mreg2,%mreg3
  2185. VMovX %mreg3,%mreg4
  2186. dealloc %mreg3
  2187. by
  2188. V<Op>X %mreg1,%mreg2,%mreg4
  2189. ?
  2190. }
  2191. if GetNextInstruction(p,hp1) and
  2192. { we mix single and double operations here because we assume that the compiler
  2193. generates vmovapd only after double operations and vmovaps only after single operations }
  2194. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2195. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2196. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2197. begin
  2198. TransferUsedRegs(TmpUsedRegs);
  2199. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2200. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2201. begin
  2202. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2203. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2204. RemoveInstruction(hp1);
  2205. result:=true;
  2206. end;
  2207. end;
  2208. end;
  2209. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2210. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2211. begin
  2212. Result := False;
  2213. { For safety reasons, only check for exact register matches }
  2214. { Check base register }
  2215. if (ref.base = AOldReg) then
  2216. begin
  2217. ref.base := ANewReg;
  2218. Result := True;
  2219. end;
  2220. { Check index register }
  2221. if (ref.index = AOldReg) then
  2222. begin
  2223. ref.index := ANewReg;
  2224. Result := True;
  2225. end;
  2226. end;
  2227. { Replaces all references to AOldReg in an operand to ANewReg }
  2228. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2229. var
  2230. OldSupReg, NewSupReg: TSuperRegister;
  2231. OldSubReg, NewSubReg: TSubRegister;
  2232. OldRegType: TRegisterType;
  2233. ThisOper: POper;
  2234. begin
  2235. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2236. Result := False;
  2237. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2238. InternalError(2020011801);
  2239. OldSupReg := getsupreg(AOldReg);
  2240. OldSubReg := getsubreg(AOldReg);
  2241. OldRegType := getregtype(AOldReg);
  2242. NewSupReg := getsupreg(ANewReg);
  2243. NewSubReg := getsubreg(ANewReg);
  2244. if OldRegType <> getregtype(ANewReg) then
  2245. InternalError(2020011802);
  2246. if OldSubReg <> NewSubReg then
  2247. InternalError(2020011803);
  2248. case ThisOper^.typ of
  2249. top_reg:
  2250. if (
  2251. (ThisOper^.reg = AOldReg) or
  2252. (
  2253. (OldRegType = R_INTREGISTER) and
  2254. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2255. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2256. (
  2257. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2258. {$ifndef x86_64}
  2259. and (
  2260. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2261. don't have an 8-bit representation }
  2262. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2263. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2264. )
  2265. {$endif x86_64}
  2266. )
  2267. )
  2268. ) then
  2269. begin
  2270. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2271. Result := True;
  2272. end;
  2273. top_ref:
  2274. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2275. Result := True;
  2276. else
  2277. ;
  2278. end;
  2279. end;
  2280. { Replaces all references to AOldReg in an instruction to ANewReg }
  2281. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2282. const
  2283. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2284. var
  2285. OperIdx: Integer;
  2286. begin
  2287. Result := False;
  2288. for OperIdx := 0 to p.ops - 1 do
  2289. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2290. begin
  2291. { The shift and rotate instructions can only use CL }
  2292. if not (
  2293. (OperIdx = 0) and
  2294. { This second condition just helps to avoid unnecessarily
  2295. calling MatchInstruction for 10 different opcodes }
  2296. (p.oper[0]^.reg = NR_CL) and
  2297. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2298. ) then
  2299. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2300. end
  2301. else if p.oper[OperIdx]^.typ = top_ref then
  2302. { It's okay to replace registers in references that get written to }
  2303. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2304. end;
  2305. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2306. begin
  2307. with ref^ do
  2308. Result :=
  2309. (index = NR_NO) and
  2310. (
  2311. {$ifdef x86_64}
  2312. (
  2313. (base = NR_RIP) and
  2314. (refaddr in [addr_pic, addr_pic_no_got])
  2315. ) or
  2316. {$endif x86_64}
  2317. (base = NR_STACK_POINTER_REG) or
  2318. (base = current_procinfo.framepointer)
  2319. );
  2320. end;
  2321. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2322. var
  2323. l: asizeint;
  2324. begin
  2325. Result := False;
  2326. { Should have been checked previously }
  2327. if p.opcode <> A_LEA then
  2328. InternalError(2020072501);
  2329. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2330. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2331. not(cs_opt_size in current_settings.optimizerswitches) then
  2332. exit;
  2333. with p.oper[0]^.ref^ do
  2334. begin
  2335. if (base <> p.oper[1]^.reg) or
  2336. (index <> NR_NO) or
  2337. assigned(symbol) then
  2338. exit;
  2339. l:=offset;
  2340. if (l=1) and UseIncDec then
  2341. begin
  2342. p.opcode:=A_INC;
  2343. p.loadreg(0,p.oper[1]^.reg);
  2344. p.ops:=1;
  2345. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2346. end
  2347. else if (l=-1) and UseIncDec then
  2348. begin
  2349. p.opcode:=A_DEC;
  2350. p.loadreg(0,p.oper[1]^.reg);
  2351. p.ops:=1;
  2352. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2353. end
  2354. else
  2355. begin
  2356. if (l<0) and (l<>-2147483648) then
  2357. begin
  2358. p.opcode:=A_SUB;
  2359. p.loadConst(0,-l);
  2360. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2361. end
  2362. else
  2363. begin
  2364. p.opcode:=A_ADD;
  2365. p.loadConst(0,l);
  2366. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2367. end;
  2368. end;
  2369. end;
  2370. Result := True;
  2371. end;
  2372. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2373. var
  2374. CurrentReg, ReplaceReg: TRegister;
  2375. begin
  2376. Result := False;
  2377. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2378. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2379. case hp.opcode of
  2380. A_FSTSW, A_FNSTSW,
  2381. A_IN, A_INS, A_OUT, A_OUTS,
  2382. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2383. { These routines have explicit operands, but they are restricted in
  2384. what they can be (e.g. IN and OUT can only read from AL, AX or
  2385. EAX. }
  2386. Exit;
  2387. A_IMUL:
  2388. begin
  2389. { The 1-operand version writes to implicit registers
  2390. The 2-operand version reads from the first operator, and reads
  2391. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2392. the 3-operand version reads from a register that it doesn't write to
  2393. }
  2394. case hp.ops of
  2395. 1:
  2396. if (
  2397. (
  2398. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2399. ) or
  2400. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2401. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2402. begin
  2403. Result := True;
  2404. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2405. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2406. end;
  2407. 2:
  2408. { Only modify the first parameter }
  2409. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2410. begin
  2411. Result := True;
  2412. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2413. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2414. end;
  2415. 3:
  2416. { Only modify the second parameter }
  2417. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2418. begin
  2419. Result := True;
  2420. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2421. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2422. end;
  2423. else
  2424. InternalError(2020012901);
  2425. end;
  2426. end;
  2427. else
  2428. if (hp.ops > 0) and
  2429. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2430. begin
  2431. Result := True;
  2432. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2433. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2434. end;
  2435. end;
  2436. end;
  2437. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2438. var
  2439. hp2: tai;
  2440. p_SourceReg, p_TargetReg: TRegister;
  2441. begin
  2442. Result := False;
  2443. { Backward optimisation. If we have:
  2444. func. %reg1,%reg2
  2445. mov %reg2,%reg3
  2446. (dealloc %reg2)
  2447. Change to:
  2448. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2449. Perform similar optimisations with 1, 3 and 4-operand instructions
  2450. that only have one output.
  2451. }
  2452. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2453. begin
  2454. p_SourceReg := taicpu(p).oper[0]^.reg;
  2455. p_TargetReg := taicpu(p).oper[1]^.reg;
  2456. TransferUsedRegs(TmpUsedRegs);
  2457. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2458. GetLastInstruction(p, hp2) and
  2459. (hp2.typ = ait_instruction) and
  2460. { Have to make sure it's an instruction that only reads from
  2461. the first operands and only writes (not reads or modifies) to
  2462. the last one; in essence, a pure function such as BSR, POPCNT
  2463. or ANDN }
  2464. (
  2465. (
  2466. (taicpu(hp2).ops = 1) and
  2467. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2468. ) or
  2469. (
  2470. (taicpu(hp2).ops = 2) and
  2471. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2472. ) or
  2473. (
  2474. (taicpu(hp2).ops = 3) and
  2475. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2476. ) or
  2477. (
  2478. (taicpu(hp2).ops = 4) and
  2479. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2480. )
  2481. ) and
  2482. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2483. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2484. begin
  2485. case taicpu(hp2).opcode of
  2486. A_FSTSW, A_FNSTSW,
  2487. A_IN, A_INS, A_OUT, A_OUTS,
  2488. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2489. { These routines have explicit operands, but they are restricted in
  2490. what they can be (e.g. IN and OUT can only read from AL, AX or
  2491. EAX. }
  2492. ;
  2493. else
  2494. begin
  2495. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2496. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2497. if not RegInInstruction(p_TargetReg, hp2) then
  2498. begin
  2499. { Since we're allocating from an earlier point, we
  2500. need to remove the register from the tracking }
  2501. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2502. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2503. end;
  2504. RemoveCurrentp(p, hp1);
  2505. { If the Func was another MOV instruction, we might get
  2506. "mov %reg,%reg" that doesn't get removed in Pass 2
  2507. otherwise, so deal with it here (also do something
  2508. similar with lea (%reg),%reg}
  2509. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2510. begin
  2511. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2512. if p = hp2 then
  2513. RemoveCurrentp(p)
  2514. else
  2515. RemoveInstruction(hp2);
  2516. end;
  2517. Result := True;
  2518. Exit;
  2519. end;
  2520. end;
  2521. end;
  2522. end;
  2523. end;
  2524. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2525. var
  2526. hp1, hp2, hp3: tai;
  2527. DoOptimisation, TempBool: Boolean;
  2528. {$ifdef x86_64}
  2529. NewConst: TCGInt;
  2530. {$endif x86_64}
  2531. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2532. begin
  2533. if taicpu(hp1).opcode = signed_movop then
  2534. begin
  2535. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2536. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2537. end
  2538. else
  2539. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2540. end;
  2541. function TryConstMerge(var p1, p2: tai): Boolean;
  2542. var
  2543. ThisRef: TReference;
  2544. begin
  2545. Result := False;
  2546. ThisRef := taicpu(p2).oper[1]^.ref^;
  2547. { Only permit writes to the stack, since we can guarantee alignment with that }
  2548. if (ThisRef.index = NR_NO) and
  2549. (
  2550. (ThisRef.base = NR_STACK_POINTER_REG) or
  2551. (ThisRef.base = current_procinfo.framepointer)
  2552. ) then
  2553. begin
  2554. case taicpu(p).opsize of
  2555. S_B:
  2556. begin
  2557. { Word writes must be on a 2-byte boundary }
  2558. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2559. begin
  2560. { Reduce offset of second reference to see if it is sequential with the first }
  2561. Dec(ThisRef.offset, 1);
  2562. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2563. begin
  2564. { Make sure the constants aren't represented as a
  2565. negative number, as these won't merge properly }
  2566. taicpu(p1).opsize := S_W;
  2567. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2568. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2569. RemoveInstruction(p2);
  2570. Result := True;
  2571. end;
  2572. end;
  2573. end;
  2574. S_W:
  2575. begin
  2576. { Longword writes must be on a 4-byte boundary }
  2577. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2578. begin
  2579. { Reduce offset of second reference to see if it is sequential with the first }
  2580. Dec(ThisRef.offset, 2);
  2581. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2582. begin
  2583. { Make sure the constants aren't represented as a
  2584. negative number, as these won't merge properly }
  2585. taicpu(p1).opsize := S_L;
  2586. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2587. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2588. RemoveInstruction(p2);
  2589. Result := True;
  2590. end;
  2591. end;
  2592. end;
  2593. {$ifdef x86_64}
  2594. S_L:
  2595. begin
  2596. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2597. see if the constants can be encoded this way. }
  2598. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2599. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2600. { Quadword writes must be on an 8-byte boundary }
  2601. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2602. begin
  2603. { Reduce offset of second reference to see if it is sequential with the first }
  2604. Dec(ThisRef.offset, 4);
  2605. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2606. begin
  2607. { Make sure the constants aren't represented as a
  2608. negative number, as these won't merge properly }
  2609. taicpu(p1).opsize := S_Q;
  2610. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2611. taicpu(p1).oper[0]^.val := NewConst;
  2612. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2613. RemoveInstruction(p2);
  2614. Result := True;
  2615. end;
  2616. end;
  2617. end;
  2618. {$endif x86_64}
  2619. else
  2620. ;
  2621. end;
  2622. end;
  2623. end;
  2624. var
  2625. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2626. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2627. NewSize: topsize; NewOffset: asizeint;
  2628. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2629. SourceRef, TargetRef: TReference;
  2630. MovAligned, MovUnaligned: TAsmOp;
  2631. ThisRef: TReference;
  2632. JumpTracking: TLinkedList;
  2633. begin
  2634. Result:=false;
  2635. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2636. { remove mov reg1,reg1? }
  2637. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2638. then
  2639. begin
  2640. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2641. { take care of the register (de)allocs following p }
  2642. RemoveCurrentP(p, hp1);
  2643. Result:=true;
  2644. exit;
  2645. end;
  2646. { All the next optimisations require a next instruction }
  2647. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2648. Exit;
  2649. { Prevent compiler warnings }
  2650. p_TargetReg := NR_NO;
  2651. if taicpu(p).oper[1]^.typ = top_reg then
  2652. begin
  2653. { Saves on a large number of dereferences }
  2654. p_TargetReg := taicpu(p).oper[1]^.reg;
  2655. { Look for:
  2656. mov %reg1,%reg2
  2657. ??? %reg2,r/m
  2658. Change to:
  2659. mov %reg1,%reg2
  2660. ??? %reg1,r/m
  2661. }
  2662. if taicpu(p).oper[0]^.typ = top_reg then
  2663. begin
  2664. if RegReadByInstruction(p_TargetReg, hp1) and
  2665. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2666. begin
  2667. { A change has occurred, just not in p }
  2668. Result := True;
  2669. TransferUsedRegs(TmpUsedRegs);
  2670. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2671. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2672. { Just in case something didn't get modified (e.g. an
  2673. implicit register) }
  2674. not RegReadByInstruction(p_TargetReg, hp1) then
  2675. begin
  2676. { We can remove the original MOV }
  2677. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2678. RemoveCurrentp(p, hp1);
  2679. { UsedRegs got updated by RemoveCurrentp }
  2680. Result := True;
  2681. Exit;
  2682. end;
  2683. { If we know a MOV instruction has become a null operation, we might as well
  2684. get rid of it now to save time. }
  2685. if (taicpu(hp1).opcode = A_MOV) and
  2686. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2687. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2688. { Just being a register is enough to confirm it's a null operation }
  2689. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2690. begin
  2691. Result := True;
  2692. { Speed-up to reduce a pipeline stall... if we had something like...
  2693. movl %eax,%edx
  2694. movw %dx,%ax
  2695. ... the second instruction would change to movw %ax,%ax, but
  2696. given that it is now %ax that's active rather than %eax,
  2697. penalties might occur due to a partial register write, so instead,
  2698. change it to a MOVZX instruction when optimising for speed.
  2699. }
  2700. if not (cs_opt_size in current_settings.optimizerswitches) and
  2701. IsMOVZXAcceptable and
  2702. (taicpu(hp1).opsize < taicpu(p).opsize)
  2703. {$ifdef x86_64}
  2704. { operations already implicitly set the upper 64 bits to zero }
  2705. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2706. {$endif x86_64}
  2707. then
  2708. begin
  2709. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2710. case taicpu(p).opsize of
  2711. S_W:
  2712. if taicpu(hp1).opsize = S_B then
  2713. taicpu(hp1).opsize := S_BL
  2714. else
  2715. InternalError(2020012911);
  2716. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2717. case taicpu(hp1).opsize of
  2718. S_B:
  2719. taicpu(hp1).opsize := S_BL;
  2720. S_W:
  2721. taicpu(hp1).opsize := S_WL;
  2722. else
  2723. InternalError(2020012912);
  2724. end;
  2725. else
  2726. InternalError(2020012910);
  2727. end;
  2728. taicpu(hp1).opcode := A_MOVZX;
  2729. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2730. end
  2731. else
  2732. begin
  2733. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2734. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2735. RemoveInstruction(hp1);
  2736. { The instruction after what was hp1 is now the immediate next instruction,
  2737. so we can continue to make optimisations if it's present }
  2738. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2739. Exit;
  2740. hp1 := hp2;
  2741. end;
  2742. end;
  2743. end;
  2744. end;
  2745. end;
  2746. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2747. overwrites the original destination register. e.g.
  2748. movl ###,%reg2d
  2749. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2750. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2751. }
  2752. if (taicpu(p).oper[1]^.typ = top_reg) and
  2753. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2754. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2755. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2756. begin
  2757. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2758. begin
  2759. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2760. case taicpu(p).oper[0]^.typ of
  2761. top_const:
  2762. { We have something like:
  2763. movb $x, %regb
  2764. movzbl %regb,%regd
  2765. Change to:
  2766. movl $x, %regd
  2767. }
  2768. begin
  2769. case taicpu(hp1).opsize of
  2770. S_BW:
  2771. begin
  2772. convert_mov_value(A_MOVSX, $FF);
  2773. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2774. taicpu(p).opsize := S_W;
  2775. end;
  2776. S_BL:
  2777. begin
  2778. convert_mov_value(A_MOVSX, $FF);
  2779. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2780. taicpu(p).opsize := S_L;
  2781. end;
  2782. S_WL:
  2783. begin
  2784. convert_mov_value(A_MOVSX, $FFFF);
  2785. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2786. taicpu(p).opsize := S_L;
  2787. end;
  2788. {$ifdef x86_64}
  2789. S_BQ:
  2790. begin
  2791. convert_mov_value(A_MOVSX, $FF);
  2792. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2793. taicpu(p).opsize := S_Q;
  2794. end;
  2795. S_WQ:
  2796. begin
  2797. convert_mov_value(A_MOVSX, $FFFF);
  2798. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2799. taicpu(p).opsize := S_Q;
  2800. end;
  2801. S_LQ:
  2802. begin
  2803. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2804. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2805. taicpu(p).opsize := S_Q;
  2806. end;
  2807. {$endif x86_64}
  2808. else
  2809. { If hp1 was a MOV instruction, it should have been
  2810. optimised already }
  2811. InternalError(2020021001);
  2812. end;
  2813. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2814. RemoveInstruction(hp1);
  2815. Result := True;
  2816. Exit;
  2817. end;
  2818. top_ref:
  2819. begin
  2820. { We have something like:
  2821. movb mem, %regb
  2822. movzbl %regb,%regd
  2823. Change to:
  2824. movzbl mem, %regd
  2825. }
  2826. ThisRef := taicpu(p).oper[0]^.ref^;
  2827. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2828. begin
  2829. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2830. taicpu(hp1).loadref(0, ThisRef);
  2831. { Make sure any registers in the references are properly tracked }
  2832. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2833. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2834. if (ThisRef.index <> NR_NO) then
  2835. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2836. RemoveCurrentP(p, hp1);
  2837. Result := True;
  2838. Exit;
  2839. end;
  2840. end;
  2841. else
  2842. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2843. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2844. Exit;
  2845. end;
  2846. end
  2847. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2848. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2849. optimised }
  2850. else
  2851. begin
  2852. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2853. RemoveCurrentP(p, hp1);
  2854. Result := True;
  2855. Exit;
  2856. end;
  2857. end;
  2858. if (taicpu(hp1).opcode = A_AND) and
  2859. (taicpu(p).oper[1]^.typ = top_reg) and
  2860. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2861. begin
  2862. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2863. begin
  2864. case taicpu(p).opsize of
  2865. S_L:
  2866. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2867. begin
  2868. { Optimize out:
  2869. mov x, %reg
  2870. and ffffffffh, %reg
  2871. }
  2872. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2873. RemoveInstruction(hp1);
  2874. Result:=true;
  2875. exit;
  2876. end;
  2877. S_Q: { TODO: Confirm if this is even possible }
  2878. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2879. begin
  2880. { Optimize out:
  2881. mov x, %reg
  2882. and ffffffffffffffffh, %reg
  2883. }
  2884. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2885. RemoveInstruction(hp1);
  2886. Result:=true;
  2887. exit;
  2888. end;
  2889. else
  2890. ;
  2891. end;
  2892. if (
  2893. (taicpu(p).oper[0]^.typ=top_reg) or
  2894. (
  2895. (taicpu(p).oper[0]^.typ=top_ref) and
  2896. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2897. )
  2898. ) and
  2899. GetNextInstruction(hp1,hp2) and
  2900. MatchInstruction(hp2,A_TEST,[]) and
  2901. (
  2902. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2903. (
  2904. { If the register being tested is smaller than the one
  2905. that received a bitwise AND, permit it if the constant
  2906. fits into the smaller size }
  2907. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2908. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2909. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2910. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2911. (
  2912. (
  2913. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2914. (taicpu(hp1).oper[0]^.val <= $FF)
  2915. ) or
  2916. (
  2917. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2918. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2919. {$ifdef x86_64}
  2920. ) or
  2921. (
  2922. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2923. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2924. {$endif x86_64}
  2925. )
  2926. )
  2927. )
  2928. ) and
  2929. (
  2930. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2931. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2932. ) and
  2933. GetNextInstruction(hp2,hp3) and
  2934. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2935. (taicpu(hp3).condition in [C_E,C_NE]) then
  2936. begin
  2937. TransferUsedRegs(TmpUsedRegs);
  2938. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2939. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2940. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2941. begin
  2942. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2943. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2944. taicpu(hp1).opcode:=A_TEST;
  2945. { Shrink the TEST instruction down to the smallest possible size }
  2946. case taicpu(hp1).oper[0]^.val of
  2947. 0..255:
  2948. if (taicpu(hp1).opsize <> S_B)
  2949. {$ifndef x86_64}
  2950. and (
  2951. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2952. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2953. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2954. )
  2955. {$endif x86_64}
  2956. then
  2957. begin
  2958. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2959. { Only print debug message if the TEST instruction
  2960. is a different size before and after }
  2961. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2962. taicpu(hp1).opsize := S_B;
  2963. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2964. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2965. end;
  2966. 256..65535:
  2967. if (taicpu(hp1).opsize <> S_W) then
  2968. begin
  2969. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2970. { Only print debug message if the TEST instruction
  2971. is a different size before and after }
  2972. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2973. taicpu(hp1).opsize := S_W;
  2974. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2975. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2976. end;
  2977. {$ifdef x86_64}
  2978. 65536..$7FFFFFFF:
  2979. if (taicpu(hp1).opsize <> S_L) then
  2980. begin
  2981. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2982. { Only print debug message if the TEST instruction
  2983. is a different size before and after }
  2984. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2985. taicpu(hp1).opsize := S_L;
  2986. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2987. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2988. end;
  2989. {$endif x86_64}
  2990. else
  2991. ;
  2992. end;
  2993. RemoveInstruction(hp2);
  2994. RemoveCurrentP(p, hp1);
  2995. Result:=true;
  2996. exit;
  2997. end;
  2998. end;
  2999. end
  3000. else if IsMOVZXAcceptable and
  3001. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3002. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3003. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3004. then
  3005. begin
  3006. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3007. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3008. case taicpu(p).opsize of
  3009. S_B:
  3010. if (taicpu(hp1).oper[0]^.val = $ff) then
  3011. begin
  3012. { Convert:
  3013. movb x, %regl movb x, %regl
  3014. andw ffh, %regw andl ffh, %regd
  3015. To:
  3016. movzbw x, %regd movzbl x, %regd
  3017. (Identical registers, just different sizes)
  3018. }
  3019. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3020. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3021. case taicpu(hp1).opsize of
  3022. S_W: NewSize := S_BW;
  3023. S_L: NewSize := S_BL;
  3024. {$ifdef x86_64}
  3025. S_Q: NewSize := S_BQ;
  3026. {$endif x86_64}
  3027. else
  3028. InternalError(2018011510);
  3029. end;
  3030. end
  3031. else
  3032. NewSize := S_NO;
  3033. S_W:
  3034. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3035. begin
  3036. { Convert:
  3037. movw x, %regw
  3038. andl ffffh, %regd
  3039. To:
  3040. movzwl x, %regd
  3041. (Identical registers, just different sizes)
  3042. }
  3043. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3044. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3045. case taicpu(hp1).opsize of
  3046. S_L: NewSize := S_WL;
  3047. {$ifdef x86_64}
  3048. S_Q: NewSize := S_WQ;
  3049. {$endif x86_64}
  3050. else
  3051. InternalError(2018011511);
  3052. end;
  3053. end
  3054. else
  3055. NewSize := S_NO;
  3056. else
  3057. NewSize := S_NO;
  3058. end;
  3059. if NewSize <> S_NO then
  3060. begin
  3061. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3062. { The actual optimization }
  3063. taicpu(p).opcode := A_MOVZX;
  3064. taicpu(p).changeopsize(NewSize);
  3065. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3066. { Safeguard if "and" is followed by a conditional command }
  3067. TransferUsedRegs(TmpUsedRegs);
  3068. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3069. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3070. begin
  3071. { At this point, the "and" command is effectively equivalent to
  3072. "test %reg,%reg". This will be handled separately by the
  3073. Peephole Optimizer. [Kit] }
  3074. DebugMsg(SPeepholeOptimization + PreMessage +
  3075. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3076. end
  3077. else
  3078. begin
  3079. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3080. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3081. RemoveInstruction(hp1);
  3082. end;
  3083. Result := True;
  3084. Exit;
  3085. end;
  3086. end;
  3087. end;
  3088. if (taicpu(hp1).opcode = A_OR) and
  3089. (taicpu(p).oper[1]^.typ = top_reg) and
  3090. MatchOperand(taicpu(p).oper[0]^, 0) and
  3091. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3092. begin
  3093. { mov 0, %reg
  3094. or ###,%reg
  3095. Change to (only if the flags are not used):
  3096. mov ###,%reg
  3097. }
  3098. TransferUsedRegs(TmpUsedRegs);
  3099. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3100. DoOptimisation := True;
  3101. { Even if the flags are used, we might be able to do the optimisation
  3102. if the conditions are predictable }
  3103. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3104. begin
  3105. { Only perform if ### = %reg (the same register) or equal to 0,
  3106. so %reg is guaranteed to still have a value of zero }
  3107. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3108. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3109. begin
  3110. hp2 := hp1;
  3111. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3112. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3113. GetNextInstruction(hp2, hp3) do
  3114. begin
  3115. { Don't continue modifying if the flags state is getting changed }
  3116. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3117. Break;
  3118. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3119. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3120. begin
  3121. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3122. begin
  3123. { Condition is always true }
  3124. case taicpu(hp3).opcode of
  3125. A_Jcc:
  3126. begin
  3127. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3128. { Check for jump shortcuts before we destroy the condition }
  3129. DoJumpOptimizations(hp3, TempBool);
  3130. MakeUnconditional(taicpu(hp3));
  3131. Result := True;
  3132. end;
  3133. A_CMOVcc:
  3134. begin
  3135. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3136. taicpu(hp3).opcode := A_MOV;
  3137. taicpu(hp3).condition := C_None;
  3138. Result := True;
  3139. end;
  3140. A_SETcc:
  3141. begin
  3142. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3143. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3144. taicpu(hp3).opcode := A_MOV;
  3145. taicpu(hp3).ops := 2;
  3146. taicpu(hp3).condition := C_None;
  3147. taicpu(hp3).opsize := S_B;
  3148. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3149. taicpu(hp3).loadconst(0, 1);
  3150. Result := True;
  3151. end;
  3152. else
  3153. InternalError(2021090701);
  3154. end;
  3155. end
  3156. 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
  3157. begin
  3158. { Condition is always false }
  3159. case taicpu(hp3).opcode of
  3160. A_Jcc:
  3161. begin
  3162. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3163. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3164. RemoveInstruction(hp3);
  3165. Result := True;
  3166. { Since hp3 was deleted, hp2 must not be updated }
  3167. Continue;
  3168. end;
  3169. A_CMOVcc:
  3170. begin
  3171. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3172. RemoveInstruction(hp3);
  3173. Result := True;
  3174. { Since hp3 was deleted, hp2 must not be updated }
  3175. Continue;
  3176. end;
  3177. A_SETcc:
  3178. begin
  3179. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3180. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3181. taicpu(hp3).opcode := A_MOV;
  3182. taicpu(hp3).ops := 2;
  3183. taicpu(hp3).condition := C_None;
  3184. taicpu(hp3).opsize := S_B;
  3185. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3186. taicpu(hp3).loadconst(0, 0);
  3187. Result := True;
  3188. end;
  3189. else
  3190. InternalError(2021090702);
  3191. end;
  3192. end
  3193. else
  3194. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3195. DoOptimisation := False;
  3196. end;
  3197. hp2 := hp3;
  3198. end;
  3199. { Flags are still in use - don't optimise }
  3200. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3201. DoOptimisation := False;
  3202. end
  3203. else
  3204. DoOptimisation := False;
  3205. end;
  3206. if DoOptimisation then
  3207. begin
  3208. {$ifdef x86_64}
  3209. { OR only supports 32-bit sign-extended constants for 64-bit
  3210. instructions, so compensate for this if the constant is
  3211. encoded as a value greater than or equal to 2^31 }
  3212. if (taicpu(hp1).opsize = S_Q) and
  3213. (taicpu(hp1).oper[0]^.typ = top_const) and
  3214. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3215. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3216. {$endif x86_64}
  3217. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3218. taicpu(hp1).opcode := A_MOV;
  3219. RemoveCurrentP(p, hp1);
  3220. Result := True;
  3221. Exit;
  3222. end;
  3223. end;
  3224. { Next instruction is also a MOV ? }
  3225. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3226. begin
  3227. if MatchOpType(taicpu(p), top_const, top_ref) and
  3228. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3229. TryConstMerge(p, hp1) then
  3230. begin
  3231. Result := True;
  3232. { In case we have four byte writes in a row, check for 2 more
  3233. right now so we don't have to wait for another iteration of
  3234. pass 1
  3235. }
  3236. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3237. case taicpu(p).opsize of
  3238. S_W:
  3239. begin
  3240. if GetNextInstruction(p, hp1) and
  3241. MatchInstruction(hp1, A_MOV, [S_B]) and
  3242. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3243. GetNextInstruction(hp1, hp2) and
  3244. MatchInstruction(hp2, A_MOV, [S_B]) and
  3245. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3246. { Try to merge the two bytes }
  3247. TryConstMerge(hp1, hp2) then
  3248. { Now try to merge the two words (hp2 will get deleted) }
  3249. TryConstMerge(p, hp1);
  3250. end;
  3251. S_L:
  3252. begin
  3253. { Though this only really benefits x86_64 and not i386, it
  3254. gets a potential optimisation done faster and hence
  3255. reduces the number of times OptPass1MOV is entered }
  3256. if GetNextInstruction(p, hp1) and
  3257. MatchInstruction(hp1, A_MOV, [S_W]) and
  3258. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3259. GetNextInstruction(hp1, hp2) and
  3260. MatchInstruction(hp2, A_MOV, [S_W]) and
  3261. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3262. { Try to merge the two words }
  3263. TryConstMerge(hp1, hp2) then
  3264. { This will always fail on i386, so don't bother
  3265. calling it unless we're doing x86_64 }
  3266. {$ifdef x86_64}
  3267. { Now try to merge the two longwords (hp2 will get deleted) }
  3268. TryConstMerge(p, hp1)
  3269. {$endif x86_64}
  3270. ;
  3271. end;
  3272. else
  3273. ;
  3274. end;
  3275. Exit;
  3276. end;
  3277. if (taicpu(p).oper[1]^.typ = top_reg) and
  3278. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3279. begin
  3280. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3281. TransferUsedRegs(TmpUsedRegs);
  3282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3283. { we have
  3284. mov x, %treg
  3285. mov %treg, y
  3286. }
  3287. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3288. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3289. { we've got
  3290. mov x, %treg
  3291. mov %treg, y
  3292. with %treg is not used after }
  3293. case taicpu(p).oper[0]^.typ Of
  3294. { top_reg is covered by DeepMOVOpt }
  3295. top_const:
  3296. begin
  3297. { change
  3298. mov const, %treg
  3299. mov %treg, y
  3300. to
  3301. mov const, y
  3302. }
  3303. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3304. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3305. begin
  3306. if taicpu(hp1).oper[1]^.typ=top_reg then
  3307. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3308. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3309. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3310. RemoveInstruction(hp1);
  3311. Result:=true;
  3312. Exit;
  3313. end;
  3314. end;
  3315. top_ref:
  3316. case taicpu(hp1).oper[1]^.typ of
  3317. top_reg:
  3318. begin
  3319. { change
  3320. mov mem, %treg
  3321. mov %treg, %reg
  3322. to
  3323. mov mem, %reg"
  3324. }
  3325. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3326. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3327. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3328. RemoveInstruction(hp1);
  3329. Result:=true;
  3330. Exit;
  3331. end;
  3332. top_ref:
  3333. begin
  3334. {$ifdef x86_64}
  3335. { Look for the following to simplify:
  3336. mov x(mem1), %reg
  3337. mov %reg, y(mem2)
  3338. mov x+8(mem1), %reg
  3339. mov %reg, y+8(mem2)
  3340. Change to:
  3341. movdqu x(mem1), %xmmreg
  3342. movdqu %xmmreg, y(mem2)
  3343. ...but only as long as the memory blocks don't overlap
  3344. }
  3345. SourceRef := taicpu(p).oper[0]^.ref^;
  3346. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3347. if (taicpu(p).opsize = S_Q) and
  3348. GetNextInstruction(hp1, hp2) and
  3349. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3350. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3351. begin
  3352. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3353. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3354. Inc(SourceRef.offset, 8);
  3355. if UseAVX then
  3356. begin
  3357. MovAligned := A_VMOVDQA;
  3358. MovUnaligned := A_VMOVDQU;
  3359. end
  3360. else
  3361. begin
  3362. MovAligned := A_MOVDQA;
  3363. MovUnaligned := A_MOVDQU;
  3364. end;
  3365. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3366. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3367. begin
  3368. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3369. Inc(TargetRef.offset, 8);
  3370. if GetNextInstruction(hp2, hp3) and
  3371. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3372. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3373. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3374. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3375. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3376. begin
  3377. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3378. if NewMMReg <> NR_NO then
  3379. begin
  3380. { Remember that the offsets are 8 ahead }
  3381. if ((SourceRef.offset mod 16) = 8) and
  3382. (
  3383. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3384. (SourceRef.base = current_procinfo.framepointer) or
  3385. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3386. ) then
  3387. taicpu(p).opcode := MovAligned
  3388. else
  3389. taicpu(p).opcode := MovUnaligned;
  3390. taicpu(p).opsize := S_XMM;
  3391. taicpu(p).oper[1]^.reg := NewMMReg;
  3392. if ((TargetRef.offset mod 16) = 8) and
  3393. (
  3394. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3395. (TargetRef.base = current_procinfo.framepointer) or
  3396. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3397. ) then
  3398. taicpu(hp1).opcode := MovAligned
  3399. else
  3400. taicpu(hp1).opcode := MovUnaligned;
  3401. taicpu(hp1).opsize := S_XMM;
  3402. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3403. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3404. RemoveInstruction(hp2);
  3405. RemoveInstruction(hp3);
  3406. Result := True;
  3407. Exit;
  3408. end;
  3409. end;
  3410. end
  3411. else
  3412. begin
  3413. { See if the next references are 8 less rather than 8 greater }
  3414. Dec(SourceRef.offset, 16); { -8 the other way }
  3415. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3416. begin
  3417. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3418. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3419. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3420. GetNextInstruction(hp2, hp3) and
  3421. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3422. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3423. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3424. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3425. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3426. begin
  3427. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3428. if NewMMReg <> NR_NO then
  3429. begin
  3430. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3431. if ((SourceRef.offset mod 16) = 0) and
  3432. (
  3433. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3434. (SourceRef.base = current_procinfo.framepointer) or
  3435. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3436. ) then
  3437. taicpu(hp2).opcode := MovAligned
  3438. else
  3439. taicpu(hp2).opcode := MovUnaligned;
  3440. taicpu(hp2).opsize := S_XMM;
  3441. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3442. if ((TargetRef.offset mod 16) = 0) and
  3443. (
  3444. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3445. (TargetRef.base = current_procinfo.framepointer) or
  3446. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3447. ) then
  3448. taicpu(hp3).opcode := MovAligned
  3449. else
  3450. taicpu(hp3).opcode := MovUnaligned;
  3451. taicpu(hp3).opsize := S_XMM;
  3452. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3453. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3454. RemoveInstruction(hp1);
  3455. RemoveCurrentP(p, hp2);
  3456. Result := True;
  3457. Exit;
  3458. end;
  3459. end;
  3460. end;
  3461. end;
  3462. end;
  3463. {$endif x86_64}
  3464. end;
  3465. else
  3466. { The write target should be a reg or a ref }
  3467. InternalError(2021091601);
  3468. end;
  3469. else
  3470. ;
  3471. end
  3472. else
  3473. { %treg is used afterwards, but all eventualities
  3474. other than the first MOV instruction being a constant
  3475. are covered by DeepMOVOpt, so only check for that }
  3476. if (taicpu(p).oper[0]^.typ = top_const) and
  3477. (
  3478. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3479. not (cs_opt_size in current_settings.optimizerswitches) or
  3480. (taicpu(hp1).opsize = S_B)
  3481. ) and
  3482. (
  3483. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3484. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3485. ) then
  3486. begin
  3487. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3488. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3489. end;
  3490. end;
  3491. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3492. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3493. { mov reg1, mem1 or mov mem1, reg1
  3494. mov mem2, reg2 mov reg2, mem2}
  3495. begin
  3496. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3497. { mov reg1, mem1 or mov mem1, reg1
  3498. mov mem2, reg1 mov reg2, mem1}
  3499. begin
  3500. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3501. { Removes the second statement from
  3502. mov reg1, mem1/reg2
  3503. mov mem1/reg2, reg1 }
  3504. begin
  3505. if taicpu(p).oper[0]^.typ=top_reg then
  3506. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3507. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3508. RemoveInstruction(hp1);
  3509. Result:=true;
  3510. exit;
  3511. end
  3512. else
  3513. begin
  3514. TransferUsedRegs(TmpUsedRegs);
  3515. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3516. if (taicpu(p).oper[1]^.typ = top_ref) and
  3517. { mov reg1, mem1
  3518. mov mem2, reg1 }
  3519. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3520. GetNextInstruction(hp1, hp2) and
  3521. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3522. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3523. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3524. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3525. { change to
  3526. mov reg1, mem1 mov reg1, mem1
  3527. mov mem2, reg1 cmp reg1, mem2
  3528. cmp mem1, reg1
  3529. }
  3530. begin
  3531. RemoveInstruction(hp2);
  3532. taicpu(hp1).opcode := A_CMP;
  3533. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3534. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3535. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3536. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3537. end;
  3538. end;
  3539. end
  3540. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3541. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3542. begin
  3543. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3544. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3545. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3546. end
  3547. else
  3548. begin
  3549. TransferUsedRegs(TmpUsedRegs);
  3550. if GetNextInstruction(hp1, hp2) and
  3551. MatchOpType(taicpu(p),top_ref,top_reg) and
  3552. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3553. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3554. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3555. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3556. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3557. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3558. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3559. { mov mem1, %reg1
  3560. mov %reg1, mem2
  3561. mov mem2, reg2
  3562. to:
  3563. mov mem1, reg2
  3564. mov reg2, mem2}
  3565. begin
  3566. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3567. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3568. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3569. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3570. RemoveInstruction(hp2);
  3571. Result := True;
  3572. end
  3573. {$ifdef i386}
  3574. { this is enabled for i386 only, as the rules to create the reg sets below
  3575. are too complicated for x86-64, so this makes this code too error prone
  3576. on x86-64
  3577. }
  3578. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3579. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3580. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3581. { mov mem1, reg1 mov mem1, reg1
  3582. mov reg1, mem2 mov reg1, mem2
  3583. mov mem2, reg2 mov mem2, reg1
  3584. to: to:
  3585. mov mem1, reg1 mov mem1, reg1
  3586. mov mem1, reg2 mov reg1, mem2
  3587. mov reg1, mem2
  3588. or (if mem1 depends on reg1
  3589. and/or if mem2 depends on reg2)
  3590. to:
  3591. mov mem1, reg1
  3592. mov reg1, mem2
  3593. mov reg1, reg2
  3594. }
  3595. begin
  3596. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3597. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3598. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3599. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3600. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3601. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3602. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3603. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3604. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3605. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3606. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3607. end
  3608. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3609. begin
  3610. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3611. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3612. end
  3613. else
  3614. begin
  3615. RemoveInstruction(hp2);
  3616. end
  3617. {$endif i386}
  3618. ;
  3619. end;
  3620. end
  3621. { movl [mem1],reg1
  3622. movl [mem1],reg2
  3623. to
  3624. movl [mem1],reg1
  3625. movl reg1,reg2
  3626. }
  3627. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3628. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3629. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3630. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3631. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3632. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3633. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3634. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3635. begin
  3636. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3637. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3638. end;
  3639. { movl const1,[mem1]
  3640. movl [mem1],reg1
  3641. to
  3642. movl const1,reg1
  3643. movl reg1,[mem1]
  3644. }
  3645. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3646. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3647. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3648. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3649. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3650. begin
  3651. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3652. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3653. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3654. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3655. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3656. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3657. Result:=true;
  3658. exit;
  3659. end;
  3660. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3661. { Change:
  3662. movl %reg1,%reg2
  3663. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3664. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3665. To:
  3666. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3667. movl x(%reg1),%reg1
  3668. movl %reg1,%regX
  3669. }
  3670. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3671. begin
  3672. p_SourceReg := taicpu(p).oper[0]^.reg;
  3673. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3674. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3675. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3676. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3677. GetNextInstruction(hp1, hp2) and
  3678. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3679. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3680. begin
  3681. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3682. if RegInRef(p_TargetReg, SourceRef) and
  3683. { If %reg1 also appears in the second reference, then it will
  3684. not refer to the same memory block as the first reference }
  3685. not RegInRef(p_SourceReg, SourceRef) then
  3686. begin
  3687. { Check to see if the references match if %reg2 is changed to %reg1 }
  3688. if SourceRef.base = p_TargetReg then
  3689. SourceRef.base := p_SourceReg;
  3690. if SourceRef.index = p_TargetReg then
  3691. SourceRef.index := p_SourceReg;
  3692. { RefsEqual also checks to ensure both references are non-volatile }
  3693. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3694. begin
  3695. taicpu(hp2).loadreg(0, p_SourceReg);
  3696. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3697. Result := True;
  3698. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3699. begin
  3700. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3701. RemoveCurrentP(p, hp1);
  3702. Exit;
  3703. end
  3704. else
  3705. begin
  3706. { Check to see if %reg2 is no longer in use }
  3707. TransferUsedRegs(TmpUsedRegs);
  3708. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3709. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3710. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3711. begin
  3712. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3713. RemoveCurrentP(p, hp1);
  3714. Exit;
  3715. end;
  3716. end;
  3717. { If we reach this point, p and hp1 weren't actually modified,
  3718. so we can do a bit more work on this pass }
  3719. end;
  3720. end;
  3721. end;
  3722. end;
  3723. end;
  3724. { search further than the next instruction for a mov (as long as it's not a jump) }
  3725. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3726. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3727. (taicpu(p).oper[1]^.typ = top_reg) and
  3728. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3729. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3730. begin
  3731. { we work with hp2 here, so hp1 can be still used later on when
  3732. checking for GetNextInstruction_p }
  3733. hp3 := hp1;
  3734. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3735. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3736. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3737. TransferUsedRegs(TmpUsedRegs);
  3738. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3739. if NotFirstIteration then
  3740. JumpTracking := TLinkedList.Create
  3741. else
  3742. JumpTracking := nil;
  3743. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3744. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3745. (hp2.typ=ait_instruction) do
  3746. begin
  3747. case taicpu(hp2).opcode of
  3748. A_POP:
  3749. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3750. begin
  3751. if not CrossJump and
  3752. not RegUsedBetween(p_TargetReg, p, hp2) then
  3753. begin
  3754. { We can remove the original MOV since the register
  3755. wasn't used between it and its popping from the stack }
  3756. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3757. RemoveCurrentp(p, hp1);
  3758. Result := True;
  3759. JumpTracking.Free;
  3760. Exit;
  3761. end;
  3762. { Can't go any further }
  3763. Break;
  3764. end;
  3765. A_MOV:
  3766. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3767. ((taicpu(p).oper[0]^.typ=top_const) or
  3768. ((taicpu(p).oper[0]^.typ=top_reg) and
  3769. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3770. )
  3771. ) then
  3772. begin
  3773. { we have
  3774. mov x, %treg
  3775. mov %treg, y
  3776. }
  3777. { We don't need to call UpdateUsedRegs for every instruction between
  3778. p and hp2 because the register we're concerned about will not
  3779. become deallocated (otherwise GetNextInstructionUsingReg would
  3780. have stopped at an earlier instruction). [Kit] }
  3781. TempRegUsed :=
  3782. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3783. RegReadByInstruction(p_TargetReg, hp3) or
  3784. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3785. case taicpu(p).oper[0]^.typ Of
  3786. top_reg:
  3787. begin
  3788. { change
  3789. mov %reg, %treg
  3790. mov %treg, y
  3791. to
  3792. mov %reg, y
  3793. }
  3794. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3795. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3796. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3797. begin
  3798. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3799. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3800. if TempRegUsed then
  3801. begin
  3802. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3803. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3804. { Set the start of the next GetNextInstructionUsingRegCond search
  3805. to start at the entry right before hp2 (which is about to be removed) }
  3806. hp3 := tai(hp2.Previous);
  3807. RemoveInstruction(hp2);
  3808. { See if there's more we can optimise }
  3809. Continue;
  3810. end
  3811. else
  3812. begin
  3813. RemoveInstruction(hp2);
  3814. { We can remove the original MOV too }
  3815. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3816. RemoveCurrentP(p, hp1);
  3817. Result:=true;
  3818. JumpTracking.Free;
  3819. Exit;
  3820. end;
  3821. end
  3822. else
  3823. begin
  3824. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3825. taicpu(hp2).loadReg(0, p_SourceReg);
  3826. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3827. { Check to see if the register also appears in the reference }
  3828. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3829. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3830. { Don't remove the first instruction if the temporary register is in use }
  3831. if not TempRegUsed and
  3832. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3833. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3834. begin
  3835. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3836. RemoveCurrentP(p, hp1);
  3837. Result:=true;
  3838. JumpTracking.Free;
  3839. Exit;
  3840. end;
  3841. { No need to set Result to True here. If there's another instruction later
  3842. on that can be optimised, it will be detected when the main Pass 1 loop
  3843. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3844. end;
  3845. end;
  3846. top_const:
  3847. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3848. begin
  3849. { change
  3850. mov const, %treg
  3851. mov %treg, y
  3852. to
  3853. mov const, y
  3854. }
  3855. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3856. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3857. begin
  3858. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3859. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3860. if TempRegUsed then
  3861. begin
  3862. { Don't remove the first instruction if the temporary register is in use }
  3863. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3864. { No need to set Result to True. If there's another instruction later on
  3865. that can be optimised, it will be detected when the main Pass 1 loop
  3866. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3867. end
  3868. else
  3869. begin
  3870. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3871. RemoveCurrentP(p, hp1);
  3872. Result:=true;
  3873. Exit;
  3874. end;
  3875. end;
  3876. end;
  3877. else
  3878. Internalerror(2019103001);
  3879. end;
  3880. end
  3881. else
  3882. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3883. begin
  3884. if not CrossJump and
  3885. not RegUsedBetween(p_TargetReg, p, hp2) and
  3886. not RegReadByInstruction(p_TargetReg, hp2) then
  3887. begin
  3888. { Register is not used before it is overwritten }
  3889. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3890. RemoveCurrentp(p, hp1);
  3891. Result := True;
  3892. Exit;
  3893. end;
  3894. if (taicpu(p).oper[0]^.typ = top_const) and
  3895. (taicpu(hp2).oper[0]^.typ = top_const) then
  3896. begin
  3897. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3898. begin
  3899. { Same value - register hasn't changed }
  3900. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3901. RemoveInstruction(hp2);
  3902. Result := True;
  3903. { See if there's more we can optimise }
  3904. Continue;
  3905. end;
  3906. end;
  3907. end;
  3908. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3909. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3910. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3911. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3912. begin
  3913. {
  3914. Change from:
  3915. mov ###, %reg
  3916. ...
  3917. movs/z %reg,%reg (Same register, just different sizes)
  3918. To:
  3919. movs/z ###, %reg (Longer version)
  3920. ...
  3921. (remove)
  3922. }
  3923. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3924. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3925. { Keep the first instruction as mov if ### is a constant }
  3926. if taicpu(p).oper[0]^.typ = top_const then
  3927. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3928. else
  3929. begin
  3930. taicpu(p).opcode := taicpu(hp2).opcode;
  3931. taicpu(p).opsize := taicpu(hp2).opsize;
  3932. end;
  3933. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3934. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3935. RemoveInstruction(hp2);
  3936. Result := True;
  3937. JumpTracking.Free;
  3938. Exit;
  3939. end;
  3940. else
  3941. { Move down to the MatchOpType if-block below };
  3942. end;
  3943. { Also catches MOV/S/Z instructions that aren't modified }
  3944. if taicpu(p).oper[0]^.typ = top_reg then
  3945. begin
  3946. p_SourceReg := taicpu(p).oper[0]^.reg;
  3947. if
  3948. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3949. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3950. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3951. begin
  3952. Result := True;
  3953. { Just in case something didn't get modified (e.g. an
  3954. implicit register). Also, if it does read from this
  3955. register, then there's no longer an advantage to
  3956. changing the register on subsequent instructions.}
  3957. if not RegReadByInstruction(p_TargetReg, hp2) then
  3958. begin
  3959. { If a conditional jump was crossed, do not delete
  3960. the original MOV no matter what }
  3961. if not CrossJump and
  3962. { RegEndOfLife returns True if the register is
  3963. deallocated before the next instruction or has
  3964. been loaded with a new value }
  3965. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3966. begin
  3967. { We can remove the original MOV }
  3968. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3969. RemoveCurrentp(p, hp1);
  3970. JumpTracking.Free;
  3971. Result := True;
  3972. Exit;
  3973. end;
  3974. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3975. begin
  3976. { See if there's more we can optimise }
  3977. hp3 := hp2;
  3978. Continue;
  3979. end;
  3980. end;
  3981. end;
  3982. end;
  3983. { Break out of the while loop under normal circumstances }
  3984. Break;
  3985. end;
  3986. JumpTracking.Free;
  3987. end;
  3988. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3989. (taicpu(p).oper[1]^.typ = top_reg) and
  3990. (taicpu(p).opsize = S_L) and
  3991. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3992. (hp2.typ = ait_instruction) and
  3993. (taicpu(hp2).opcode = A_AND) and
  3994. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3995. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3996. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3997. ) then
  3998. begin
  3999. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4000. begin
  4001. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4002. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4003. begin
  4004. { Optimize out:
  4005. mov x, %reg
  4006. and ffffffffh, %reg
  4007. }
  4008. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4009. RemoveInstruction(hp2);
  4010. Result:=true;
  4011. exit;
  4012. end;
  4013. end;
  4014. end;
  4015. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4016. x >= RetOffset) as it doesn't do anything (it writes either to a
  4017. parameter or to the temporary storage room for the function
  4018. result)
  4019. }
  4020. if IsExitCode(hp1) and
  4021. (taicpu(p).oper[1]^.typ = top_ref) and
  4022. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4023. (
  4024. (
  4025. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4026. not (
  4027. assigned(current_procinfo.procdef.funcretsym) and
  4028. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4029. )
  4030. ) or
  4031. { Also discard writes to the stack that are below the base pointer,
  4032. as this is temporary storage rather than a function result on the
  4033. stack, say. }
  4034. (
  4035. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4036. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4037. )
  4038. ) then
  4039. begin
  4040. RemoveCurrentp(p, hp1);
  4041. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4042. RemoveLastDeallocForFuncRes(p);
  4043. Result:=true;
  4044. exit;
  4045. end;
  4046. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4047. begin
  4048. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4049. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4050. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4051. begin
  4052. { change
  4053. mov reg1, mem1
  4054. test/cmp x, mem1
  4055. to
  4056. mov reg1, mem1
  4057. test/cmp x, reg1
  4058. }
  4059. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4060. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4062. Result := True;
  4063. Exit;
  4064. end;
  4065. if DoMovCmpMemOpt(p, hp1, True) then
  4066. begin
  4067. Result := True;
  4068. Exit;
  4069. end;
  4070. end;
  4071. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4072. { If the flags register is in use, don't change the instruction to an
  4073. ADD otherwise this will scramble the flags. [Kit] }
  4074. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4075. begin
  4076. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4077. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4078. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4079. ) or
  4080. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4081. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4082. )
  4083. ) then
  4084. { mov reg1,ref
  4085. lea reg2,[reg1,reg2]
  4086. to
  4087. add reg2,ref}
  4088. begin
  4089. TransferUsedRegs(TmpUsedRegs);
  4090. { reg1 may not be used afterwards }
  4091. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4092. begin
  4093. Taicpu(hp1).opcode:=A_ADD;
  4094. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4095. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4096. RemoveCurrentp(p, hp1);
  4097. result:=true;
  4098. exit;
  4099. end;
  4100. end;
  4101. { If the LEA instruction can be converted into an arithmetic instruction,
  4102. it may be possible to then fold it in the next optimisation, otherwise
  4103. there's nothing more that can be optimised here. }
  4104. if not ConvertLEA(taicpu(hp1)) then
  4105. Exit;
  4106. end;
  4107. if (taicpu(p).oper[1]^.typ = top_reg) and
  4108. (hp1.typ = ait_instruction) and
  4109. GetNextInstruction(hp1, hp2) and
  4110. MatchInstruction(hp2,A_MOV,[]) and
  4111. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4112. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4113. (
  4114. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4115. {$ifdef x86_64}
  4116. or
  4117. (
  4118. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4119. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4120. )
  4121. {$endif x86_64}
  4122. ) then
  4123. begin
  4124. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4125. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4126. { change movsX/movzX reg/ref, reg2
  4127. add/sub/or/... reg3/$const, reg2
  4128. mov reg2 reg/ref
  4129. dealloc reg2
  4130. to
  4131. add/sub/or/... reg3/$const, reg/ref }
  4132. begin
  4133. TransferUsedRegs(TmpUsedRegs);
  4134. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4135. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4136. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4137. begin
  4138. { by example:
  4139. movswl %si,%eax movswl %si,%eax p
  4140. decl %eax addl %edx,%eax hp1
  4141. movw %ax,%si movw %ax,%si hp2
  4142. ->
  4143. movswl %si,%eax movswl %si,%eax p
  4144. decw %eax addw %edx,%eax hp1
  4145. movw %ax,%si movw %ax,%si hp2
  4146. }
  4147. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4148. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4149. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4150. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4151. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4152. {
  4153. ->
  4154. movswl %si,%eax movswl %si,%eax p
  4155. decw %si addw %dx,%si hp1
  4156. movw %ax,%si movw %ax,%si hp2
  4157. }
  4158. case taicpu(hp1).ops of
  4159. 1:
  4160. begin
  4161. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4162. if taicpu(hp1).oper[0]^.typ=top_reg then
  4163. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4164. end;
  4165. 2:
  4166. begin
  4167. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4168. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4169. (taicpu(hp1).opcode<>A_SHL) and
  4170. (taicpu(hp1).opcode<>A_SHR) and
  4171. (taicpu(hp1).opcode<>A_SAR) then
  4172. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4173. end;
  4174. else
  4175. internalerror(2008042701);
  4176. end;
  4177. {
  4178. ->
  4179. decw %si addw %dx,%si p
  4180. }
  4181. RemoveInstruction(hp2);
  4182. RemoveCurrentP(p, hp1);
  4183. Result:=True;
  4184. Exit;
  4185. end;
  4186. end;
  4187. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4188. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4189. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4190. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4191. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4192. )
  4193. {$ifdef i386}
  4194. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4195. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4196. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4197. {$endif i386}
  4198. then
  4199. { change movsX/movzX reg/ref, reg2
  4200. add/sub/or/... regX/$const, reg2
  4201. mov reg2, reg3
  4202. dealloc reg2
  4203. to
  4204. movsX/movzX reg/ref, reg3
  4205. add/sub/or/... reg3/$const, reg3
  4206. }
  4207. begin
  4208. TransferUsedRegs(TmpUsedRegs);
  4209. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4210. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4211. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4212. begin
  4213. { by example:
  4214. movswl %si,%eax movswl %si,%eax p
  4215. decl %eax addl %edx,%eax hp1
  4216. movw %ax,%si movw %ax,%si hp2
  4217. ->
  4218. movswl %si,%eax movswl %si,%eax p
  4219. decw %eax addw %edx,%eax hp1
  4220. movw %ax,%si movw %ax,%si hp2
  4221. }
  4222. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4223. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4224. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4225. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4226. { limit size of constants as well to avoid assembler errors, but
  4227. check opsize to avoid overflow when left shifting the 1 }
  4228. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4229. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4230. {$ifdef x86_64}
  4231. { Be careful of, for example:
  4232. movl %reg1,%reg2
  4233. addl %reg3,%reg2
  4234. movq %reg2,%reg4
  4235. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4236. }
  4237. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4238. begin
  4239. taicpu(hp2).changeopsize(S_L);
  4240. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4241. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4242. end;
  4243. {$endif x86_64}
  4244. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4245. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4246. if taicpu(p).oper[0]^.typ=top_reg then
  4247. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4248. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4249. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4250. {
  4251. ->
  4252. movswl %si,%eax movswl %si,%eax p
  4253. decw %si addw %dx,%si hp1
  4254. movw %ax,%si movw %ax,%si hp2
  4255. }
  4256. case taicpu(hp1).ops of
  4257. 1:
  4258. begin
  4259. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4260. if taicpu(hp1).oper[0]^.typ=top_reg then
  4261. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4262. end;
  4263. 2:
  4264. begin
  4265. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4266. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4267. (taicpu(hp1).opcode<>A_SHL) and
  4268. (taicpu(hp1).opcode<>A_SHR) and
  4269. (taicpu(hp1).opcode<>A_SAR) then
  4270. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4271. end;
  4272. else
  4273. internalerror(2018111801);
  4274. end;
  4275. {
  4276. ->
  4277. decw %si addw %dx,%si p
  4278. }
  4279. RemoveInstruction(hp2);
  4280. end;
  4281. end;
  4282. end;
  4283. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4284. GetNextInstruction(hp1, hp2) and
  4285. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4286. MatchOperand(Taicpu(p).oper[0]^,0) and
  4287. (Taicpu(p).oper[1]^.typ = top_reg) and
  4288. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4289. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4290. { mov reg1,0
  4291. bts reg1,operand1 --> mov reg1,operand2
  4292. or reg1,operand2 bts reg1,operand1}
  4293. begin
  4294. Taicpu(hp2).opcode:=A_MOV;
  4295. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4296. asml.remove(hp1);
  4297. insertllitem(hp2,hp2.next,hp1);
  4298. RemoveCurrentp(p, hp1);
  4299. Result:=true;
  4300. exit;
  4301. end;
  4302. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4303. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4304. GetNextInstruction(hp1, hp2) and
  4305. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4306. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4307. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4308. { change
  4309. mov reg1,reg2
  4310. sub reg3,reg2
  4311. cmp reg3,reg1
  4312. into
  4313. mov reg1,reg2
  4314. sub reg3,reg2
  4315. }
  4316. begin
  4317. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4318. RemoveInstruction(hp2);
  4319. Result:=true;
  4320. exit;
  4321. end;
  4322. {
  4323. mov ref,reg0
  4324. <op> reg0,reg1
  4325. dealloc reg0
  4326. to
  4327. <op> ref,reg1
  4328. }
  4329. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4330. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4331. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4332. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4333. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4334. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4335. begin
  4336. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4337. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4338. RemoveCurrentp(p, hp1);
  4339. Result:=true;
  4340. exit;
  4341. end;
  4342. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4343. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4344. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4345. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4346. begin
  4347. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4348. {$ifdef x86_64}
  4349. { Convert:
  4350. movq x(ref),%reg64
  4351. shrq y,%reg64
  4352. To:
  4353. movl x+4(ref),%reg32
  4354. shrl y-32,%reg32 (Remove if y = 32)
  4355. }
  4356. if (taicpu(p).opsize = S_Q) and
  4357. (taicpu(hp1).opcode = A_SHR) and
  4358. (taicpu(hp1).oper[0]^.val >= 32) then
  4359. begin
  4360. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4361. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4362. { Convert to 32-bit }
  4363. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4364. taicpu(p).opsize := S_L;
  4365. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4366. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4367. if (taicpu(hp1).oper[0]^.val = 32) then
  4368. begin
  4369. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4370. RemoveInstruction(hp1);
  4371. end
  4372. else
  4373. begin
  4374. { This will potentially open up more arithmetic operations since
  4375. the peephole optimizer now has a big hint that only the lower
  4376. 32 bits are currently in use (and opcodes are smaller in size) }
  4377. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4378. taicpu(hp1).opsize := S_L;
  4379. Dec(taicpu(hp1).oper[0]^.val, 32);
  4380. DebugMsg(SPeepholeOptimization + PreMessage +
  4381. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4382. end;
  4383. Result := True;
  4384. Exit;
  4385. end;
  4386. {$endif x86_64}
  4387. { Convert:
  4388. movl x(ref),%reg
  4389. shrl $24,%reg
  4390. To:
  4391. movzbl x+3(ref),%reg
  4392. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4393. Also accept sar instead of shr, but convert to movsx instead of movzx
  4394. }
  4395. if taicpu(hp1).opcode = A_SHR then
  4396. MovUnaligned := A_MOVZX
  4397. else
  4398. MovUnaligned := A_MOVSX;
  4399. NewSize := S_NO;
  4400. NewOffset := 0;
  4401. case taicpu(p).opsize of
  4402. S_B:
  4403. { No valid combinations };
  4404. S_W:
  4405. if (taicpu(hp1).oper[0]^.val = 8) then
  4406. begin
  4407. NewSize := S_BW;
  4408. NewOffset := 1;
  4409. end;
  4410. S_L:
  4411. case taicpu(hp1).oper[0]^.val of
  4412. 16:
  4413. begin
  4414. NewSize := S_WL;
  4415. NewOffset := 2;
  4416. end;
  4417. 24:
  4418. begin
  4419. NewSize := S_BL;
  4420. NewOffset := 3;
  4421. end;
  4422. else
  4423. ;
  4424. end;
  4425. {$ifdef x86_64}
  4426. S_Q:
  4427. case taicpu(hp1).oper[0]^.val of
  4428. 32:
  4429. begin
  4430. if taicpu(hp1).opcode = A_SAR then
  4431. begin
  4432. { 32-bit to 64-bit is a distinct instruction }
  4433. MovUnaligned := A_MOVSXD;
  4434. NewSize := S_LQ;
  4435. NewOffset := 4;
  4436. end
  4437. else
  4438. { Should have been handled by MovShr2Mov above }
  4439. InternalError(2022081811);
  4440. end;
  4441. 48:
  4442. begin
  4443. NewSize := S_WQ;
  4444. NewOffset := 6;
  4445. end;
  4446. 56:
  4447. begin
  4448. NewSize := S_BQ;
  4449. NewOffset := 7;
  4450. end;
  4451. else
  4452. ;
  4453. end;
  4454. {$endif x86_64}
  4455. else
  4456. InternalError(2022081810);
  4457. end;
  4458. if (NewSize <> S_NO) and
  4459. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4460. begin
  4461. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4462. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4463. debug_op2str(MovUnaligned);
  4464. {$ifdef x86_64}
  4465. if MovUnaligned <> A_MOVSXD then
  4466. { Don't add size suffix for MOVSXD }
  4467. {$endif x86_64}
  4468. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4469. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4470. taicpu(p).opcode := MovUnaligned;
  4471. taicpu(p).opsize := NewSize;
  4472. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4473. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4474. RemoveInstruction(hp1);
  4475. Result := True;
  4476. Exit;
  4477. end;
  4478. end;
  4479. { Backward optimisation shared with OptPass2MOV }
  4480. if FuncMov2Func(p, hp1) then
  4481. begin
  4482. Result := True;
  4483. Exit;
  4484. end;
  4485. end;
  4486. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4487. var
  4488. hp1 : tai;
  4489. begin
  4490. Result:=false;
  4491. if taicpu(p).ops <> 2 then
  4492. exit;
  4493. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4494. GetNextInstruction(p,hp1) then
  4495. begin
  4496. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4497. (taicpu(hp1).ops = 2) then
  4498. begin
  4499. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4500. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4501. { movXX reg1, mem1 or movXX mem1, reg1
  4502. movXX mem2, reg2 movXX reg2, mem2}
  4503. begin
  4504. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4505. { movXX reg1, mem1 or movXX mem1, reg1
  4506. movXX mem2, reg1 movXX reg2, mem1}
  4507. begin
  4508. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4509. begin
  4510. { Removes the second statement from
  4511. movXX reg1, mem1/reg2
  4512. movXX mem1/reg2, reg1
  4513. }
  4514. if taicpu(p).oper[0]^.typ=top_reg then
  4515. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4516. { Removes the second statement from
  4517. movXX mem1/reg1, reg2
  4518. movXX reg2, mem1/reg1
  4519. }
  4520. if (taicpu(p).oper[1]^.typ=top_reg) and
  4521. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4522. begin
  4523. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4524. RemoveInstruction(hp1);
  4525. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4526. Result:=true;
  4527. exit;
  4528. end
  4529. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4530. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4531. begin
  4532. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4533. RemoveInstruction(hp1);
  4534. Result:=true;
  4535. exit;
  4536. end;
  4537. end
  4538. end;
  4539. end;
  4540. end;
  4541. end;
  4542. end;
  4543. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4544. var
  4545. hp1 : tai;
  4546. begin
  4547. result:=false;
  4548. { replace
  4549. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4550. MovX %mreg2,%mreg1
  4551. dealloc %mreg2
  4552. by
  4553. <Op>X %mreg2,%mreg1
  4554. ?
  4555. }
  4556. if GetNextInstruction(p,hp1) and
  4557. { we mix single and double opperations here because we assume that the compiler
  4558. generates vmovapd only after double operations and vmovaps only after single operations }
  4559. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4560. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4561. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4562. (taicpu(p).oper[0]^.typ=top_reg) then
  4563. begin
  4564. TransferUsedRegs(TmpUsedRegs);
  4565. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4566. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4567. begin
  4568. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4569. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4570. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4571. RemoveInstruction(hp1);
  4572. result:=true;
  4573. end;
  4574. end;
  4575. end;
  4576. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4577. var
  4578. hp1, p_label, p_dist, hp1_dist: tai;
  4579. JumpLabel, JumpLabel_dist: TAsmLabel;
  4580. FirstValue, SecondValue: TCGInt;
  4581. begin
  4582. Result := False;
  4583. if (taicpu(p).oper[0]^.typ = top_const) and
  4584. (taicpu(p).oper[0]^.val <> -1) then
  4585. begin
  4586. { Convert unsigned maximum constants to -1 to aid optimisation }
  4587. case taicpu(p).opsize of
  4588. S_B:
  4589. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4590. begin
  4591. taicpu(p).oper[0]^.val := -1;
  4592. Result := True;
  4593. Exit;
  4594. end;
  4595. S_W:
  4596. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4597. begin
  4598. taicpu(p).oper[0]^.val := -1;
  4599. Result := True;
  4600. Exit;
  4601. end;
  4602. S_L:
  4603. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4604. begin
  4605. taicpu(p).oper[0]^.val := -1;
  4606. Result := True;
  4607. Exit;
  4608. end;
  4609. {$ifdef x86_64}
  4610. S_Q:
  4611. { Storing anything greater than $7FFFFFFF is not possible so do
  4612. nothing };
  4613. {$endif x86_64}
  4614. else
  4615. InternalError(2021121001);
  4616. end;
  4617. end;
  4618. if GetNextInstruction(p, hp1) and
  4619. TrySwapMovCmp(p, hp1) then
  4620. begin
  4621. Result := True;
  4622. Exit;
  4623. end;
  4624. { Search for:
  4625. test $x,(reg/ref)
  4626. jne @lbl1
  4627. test $y,(reg/ref) (same register or reference)
  4628. jne @lbl1
  4629. Change to:
  4630. test $(x or y),(reg/ref)
  4631. jne @lbl1
  4632. (Note, this doesn't work with je instead of jne)
  4633. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4634. Also search for:
  4635. test $x,(reg/ref)
  4636. je @lbl1
  4637. test $y,(reg/ref)
  4638. je/jne @lbl2
  4639. If (x or y) = x, then the second jump is deterministic
  4640. }
  4641. if (
  4642. (
  4643. (taicpu(p).oper[0]^.typ = top_const) or
  4644. (
  4645. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4646. (taicpu(p).oper[0]^.typ = top_reg) and
  4647. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4648. )
  4649. ) and
  4650. MatchInstruction(hp1, A_JCC, [])
  4651. ) then
  4652. begin
  4653. if (taicpu(p).oper[0]^.typ = top_reg) and
  4654. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4655. FirstValue := -1
  4656. else
  4657. FirstValue := taicpu(p).oper[0]^.val;
  4658. { If we have several test/jne's in a row, it might be the case that
  4659. the second label doesn't go to the same location, but the one
  4660. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4661. so accommodate for this with a while loop.
  4662. }
  4663. hp1_dist := hp1;
  4664. if GetNextInstruction(hp1, p_dist) and
  4665. (p_dist.typ = ait_instruction) and
  4666. (
  4667. (
  4668. (taicpu(p_dist).opcode = A_TEST) and
  4669. (
  4670. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4671. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4672. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4673. )
  4674. ) or
  4675. (
  4676. { cmp 0,%reg = test %reg,%reg }
  4677. (taicpu(p_dist).opcode = A_CMP) and
  4678. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4679. )
  4680. ) and
  4681. { Make sure the destination operands are actually the same }
  4682. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4683. GetNextInstruction(p_dist, hp1_dist) and
  4684. MatchInstruction(hp1_dist, A_JCC, []) then
  4685. begin
  4686. if
  4687. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4688. (
  4689. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4690. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4691. ) then
  4692. SecondValue := -1
  4693. else
  4694. SecondValue := taicpu(p_dist).oper[0]^.val;
  4695. { If both of the TEST constants are identical, delete the second
  4696. TEST that is unnecessary. }
  4697. if (FirstValue = SecondValue) then
  4698. begin
  4699. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4700. RemoveInstruction(p_dist);
  4701. { Don't let the flags register become deallocated and reallocated between the jumps }
  4702. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4703. Result := True;
  4704. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4705. begin
  4706. { Since the second jump's condition is a subset of the first, we
  4707. know it will never branch because the first jump dominates it.
  4708. Get it out of the way now rather than wait for the jump
  4709. optimisations for a speed boost. }
  4710. if IsJumpToLabel(taicpu(hp1_dist)) then
  4711. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4712. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4713. RemoveInstruction(hp1_dist);
  4714. end
  4715. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4716. begin
  4717. { If the inverse of the first condition is a subset of the second,
  4718. the second one will definitely branch if the first one doesn't }
  4719. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4720. MakeUnconditional(taicpu(hp1_dist));
  4721. RemoveDeadCodeAfterJump(hp1_dist);
  4722. end;
  4723. Exit;
  4724. end;
  4725. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4726. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4727. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4728. then the second jump will never branch, so it can also be
  4729. removed regardless of where it goes }
  4730. (
  4731. (FirstValue = -1) or
  4732. (SecondValue = -1) or
  4733. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4734. ) then
  4735. begin
  4736. { Same jump location... can be a register since nothing's changed }
  4737. { If any of the entries are equivalent to test %reg,%reg, then the
  4738. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4739. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4740. if IsJumpToLabel(taicpu(hp1_dist)) then
  4741. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4742. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4743. RemoveInstruction(hp1_dist);
  4744. { Only remove the second test if no jumps or other conditional instructions follow }
  4745. TransferUsedRegs(TmpUsedRegs);
  4746. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4747. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4748. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4749. RemoveInstruction(p_dist);
  4750. Result := True;
  4751. Exit;
  4752. end;
  4753. end;
  4754. end;
  4755. { Search for:
  4756. test %reg,%reg
  4757. j(c1) @lbl1
  4758. ...
  4759. @lbl:
  4760. test %reg,%reg (same register)
  4761. j(c2) @lbl2
  4762. If c2 is a subset of c1, change to:
  4763. test %reg,%reg
  4764. j(c1) @lbl2
  4765. (@lbl1 may become a dead label as a result)
  4766. }
  4767. if (taicpu(p).oper[1]^.typ = top_reg) and
  4768. (taicpu(p).oper[0]^.typ = top_reg) and
  4769. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4770. MatchInstruction(hp1, A_JCC, []) and
  4771. IsJumpToLabel(taicpu(hp1)) then
  4772. begin
  4773. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4774. p_label := nil;
  4775. if Assigned(JumpLabel) then
  4776. p_label := getlabelwithsym(JumpLabel);
  4777. if Assigned(p_label) and
  4778. GetNextInstruction(p_label, p_dist) and
  4779. MatchInstruction(p_dist, A_TEST, []) and
  4780. { It's fine if the second test uses smaller sub-registers }
  4781. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4782. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4783. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4784. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4785. GetNextInstruction(p_dist, hp1_dist) and
  4786. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4787. begin
  4788. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4789. if JumpLabel = JumpLabel_dist then
  4790. { This is an infinite loop }
  4791. Exit;
  4792. { Best optimisation when the first condition is a subset (or equal) of the second }
  4793. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4794. begin
  4795. { Any registers used here will already be allocated }
  4796. if Assigned(JumpLabel) then
  4797. JumpLabel.DecRefs;
  4798. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4799. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4800. Result := True;
  4801. Exit;
  4802. end;
  4803. end;
  4804. end;
  4805. end;
  4806. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4807. var
  4808. hp1, hp2: tai;
  4809. ActiveReg: TRegister;
  4810. OldOffset: asizeint;
  4811. ThisConst: TCGInt;
  4812. function RegDeallocated: Boolean;
  4813. begin
  4814. TransferUsedRegs(TmpUsedRegs);
  4815. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4816. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4817. end;
  4818. begin
  4819. result:=false;
  4820. hp1 := nil;
  4821. { replace
  4822. addX const,%reg1
  4823. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4824. dealloc %reg1
  4825. by
  4826. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4827. }
  4828. if MatchOpType(taicpu(p),top_const,top_reg) then
  4829. begin
  4830. ActiveReg := taicpu(p).oper[1]^.reg;
  4831. { Ensures the entire register was updated }
  4832. if (taicpu(p).opsize >= S_L) and
  4833. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4834. MatchInstruction(hp1,A_LEA,[]) and
  4835. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4836. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4837. (
  4838. { Cover the case where the register in the reference is also the destination register }
  4839. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4840. (
  4841. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4842. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4843. RegDeallocated
  4844. )
  4845. ) then
  4846. begin
  4847. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4848. {$push}
  4849. {$R-}{$Q-}
  4850. { Explicitly disable overflow checking for these offset calculation
  4851. as those do not matter for the final result }
  4852. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4853. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4854. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4855. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4856. {$pop}
  4857. {$ifdef x86_64}
  4858. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4859. begin
  4860. { Overflow; abort }
  4861. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4862. end
  4863. else
  4864. {$endif x86_64}
  4865. begin
  4866. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4867. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4868. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4869. RemoveCurrentP(p, hp1)
  4870. else
  4871. RemoveCurrentP(p);
  4872. result:=true;
  4873. Exit;
  4874. end;
  4875. end;
  4876. if (
  4877. { Save calling GetNextInstructionUsingReg again }
  4878. Assigned(hp1) or
  4879. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4880. ) and
  4881. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4882. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4883. begin
  4884. if taicpu(hp1).oper[0]^.typ = top_const then
  4885. begin
  4886. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4887. if taicpu(hp1).opcode = A_ADD then
  4888. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4889. else
  4890. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4891. Result := True;
  4892. { Handle any overflows }
  4893. case taicpu(p).opsize of
  4894. S_B:
  4895. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4896. S_W:
  4897. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4898. S_L:
  4899. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4900. {$ifdef x86_64}
  4901. S_Q:
  4902. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4903. { Overflow; abort }
  4904. Result := False
  4905. else
  4906. taicpu(p).oper[0]^.val := ThisConst;
  4907. {$endif x86_64}
  4908. else
  4909. InternalError(2021102610);
  4910. end;
  4911. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4912. if Result then
  4913. begin
  4914. if (taicpu(p).oper[0]^.val < 0) and
  4915. (
  4916. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4917. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4918. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4919. ) then
  4920. begin
  4921. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4922. taicpu(p).opcode := A_SUB;
  4923. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4924. end
  4925. else
  4926. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4927. RemoveInstruction(hp1);
  4928. end;
  4929. end
  4930. else
  4931. begin
  4932. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4933. TransferUsedRegs(TmpUsedRegs);
  4934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4935. hp2 := p;
  4936. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4937. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4938. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4939. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4940. begin
  4941. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4942. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4943. Asml.Remove(p);
  4944. Asml.InsertAfter(p, hp1);
  4945. p := hp1;
  4946. Result := True;
  4947. Exit;
  4948. end;
  4949. end;
  4950. end;
  4951. if DoArithCombineOpt(p) then
  4952. Result:=true;
  4953. end;
  4954. end;
  4955. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4956. var
  4957. hp1: tai;
  4958. ref: Integer;
  4959. saveref: treference;
  4960. Multiple: TCGInt;
  4961. Adjacent: Boolean;
  4962. begin
  4963. Result:=false;
  4964. { play save and throw an error if LEA uses a seg register prefix,
  4965. this is most likely an error somewhere else }
  4966. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4967. internalerror(2022022001);
  4968. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4969. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4970. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4971. (
  4972. { do not mess with leas accessing the stack pointer
  4973. unless it's a null operation }
  4974. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4975. (
  4976. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4977. (taicpu(p).oper[0]^.ref^.offset = 0)
  4978. )
  4979. ) and
  4980. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4981. begin
  4982. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4983. begin
  4984. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4985. begin
  4986. taicpu(p).opcode := A_MOV;
  4987. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4988. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4989. end
  4990. else
  4991. begin
  4992. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4993. RemoveCurrentP(p);
  4994. end;
  4995. Result:=true;
  4996. exit;
  4997. end
  4998. else if (
  4999. { continue to use lea to adjust the stack pointer,
  5000. it is the recommended way, but only if not optimizing for size }
  5001. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5002. (cs_opt_size in current_settings.optimizerswitches)
  5003. ) and
  5004. { If the flags register is in use, don't change the instruction
  5005. to an ADD otherwise this will scramble the flags. [Kit] }
  5006. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5007. ConvertLEA(taicpu(p)) then
  5008. begin
  5009. Result:=true;
  5010. exit;
  5011. end;
  5012. end;
  5013. { Don't optimise if the stack or frame pointer is the destination register }
  5014. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5015. Exit;
  5016. if GetNextInstruction(p,hp1) and
  5017. (hp1.typ=ait_instruction) then
  5018. begin
  5019. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5020. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5021. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5022. begin
  5023. TransferUsedRegs(TmpUsedRegs);
  5024. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5025. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5026. begin
  5027. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5028. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5029. RemoveInstruction(hp1);
  5030. result:=true;
  5031. exit;
  5032. end;
  5033. end;
  5034. { changes
  5035. lea <ref1>, reg1
  5036. <op> ...,<ref. with reg1>,...
  5037. to
  5038. <op> ...,<ref1>,... }
  5039. { find a reference which uses reg1 }
  5040. 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
  5041. ref:=0
  5042. 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
  5043. ref:=1
  5044. else
  5045. ref:=-1;
  5046. if (ref<>-1) and
  5047. { reg1 must be either the base or the index }
  5048. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5049. begin
  5050. { reg1 can be removed from the reference }
  5051. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5052. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5053. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5054. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5055. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5056. else
  5057. Internalerror(2019111201);
  5058. { check if the can insert all data of the lea into the second instruction }
  5059. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5060. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5061. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5062. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5063. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5064. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5065. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5066. {$ifdef x86_64}
  5067. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5068. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5069. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5070. )
  5071. {$endif x86_64}
  5072. then
  5073. begin
  5074. { reg1 might not used by the second instruction after it is remove from the reference }
  5075. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5076. begin
  5077. TransferUsedRegs(TmpUsedRegs);
  5078. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5079. { reg1 is not updated so it might not be used afterwards }
  5080. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5081. begin
  5082. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5083. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5084. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5085. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5086. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5087. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5088. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5089. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5090. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5091. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5092. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5093. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5094. RemoveCurrentP(p, hp1);
  5095. result:=true;
  5096. exit;
  5097. end
  5098. end;
  5099. end;
  5100. { recover }
  5101. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5102. end;
  5103. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5104. if Adjacent or
  5105. { Check further ahead (up to 2 instructions ahead for -O2) }
  5106. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5107. begin
  5108. { Check common LEA/LEA conditions }
  5109. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5110. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5111. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5112. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5113. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5114. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5115. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5116. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5117. (
  5118. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5119. calling it (since it calls GetNextInstruction) }
  5120. Adjacent or
  5121. (
  5122. (
  5123. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5124. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5125. ) and (
  5126. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5127. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5128. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5129. )
  5130. )
  5131. ) then
  5132. begin
  5133. { changes
  5134. lea (regX,scale), reg1
  5135. lea offset(reg1,reg1), reg1
  5136. to
  5137. lea offset(regX,scale*2), reg1
  5138. and
  5139. lea (regX,scale1), reg1
  5140. lea offset(reg1,scale2), reg1
  5141. to
  5142. lea offset(regX,scale1*scale2), reg1
  5143. ... so long as the final scale does not exceed 8
  5144. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5145. }
  5146. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5147. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5148. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5149. (
  5150. (
  5151. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5152. ) or (
  5153. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5154. (
  5155. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5156. (
  5157. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5158. Adjacent or
  5159. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5160. )
  5161. )
  5162. )
  5163. ) and (
  5164. (
  5165. { lea (reg1,scale2), reg1 variant }
  5166. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5167. (
  5168. (
  5169. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5170. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5171. ) or (
  5172. { lea (regX,regX), reg1 variant }
  5173. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5174. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5175. )
  5176. )
  5177. ) or (
  5178. { lea (reg1,reg1), reg1 variant }
  5179. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5180. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5181. )
  5182. ) then
  5183. begin
  5184. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5185. { Make everything homogeneous to make calculations easier }
  5186. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5187. begin
  5188. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5189. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5190. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5191. else
  5192. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5193. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5194. end;
  5195. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5196. begin
  5197. { Just to prevent miscalculations }
  5198. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5199. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5200. else
  5201. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5202. end
  5203. else
  5204. begin
  5205. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5206. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5207. end;
  5208. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5209. RemoveCurrentP(p);
  5210. result:=true;
  5211. exit;
  5212. end
  5213. { changes
  5214. lea offset1(regX), reg1
  5215. lea offset2(reg1), reg1
  5216. to
  5217. lea offset1+offset2(regX), reg1 }
  5218. else if
  5219. (
  5220. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5221. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5222. ) or (
  5223. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5224. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5225. (
  5226. (
  5227. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5228. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5229. ) or (
  5230. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5231. (
  5232. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5233. (
  5234. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5235. (
  5236. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5237. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5238. )
  5239. )
  5240. )
  5241. )
  5242. )
  5243. ) then
  5244. begin
  5245. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5246. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5247. begin
  5248. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5249. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5250. { if the register is used as index and base, we have to increase for base as well
  5251. and adapt base }
  5252. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5253. begin
  5254. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5255. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5256. end;
  5257. end
  5258. else
  5259. begin
  5260. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5261. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5262. end;
  5263. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5264. begin
  5265. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5266. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5267. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5268. end;
  5269. RemoveCurrentP(p);
  5270. result:=true;
  5271. exit;
  5272. end;
  5273. end;
  5274. { Change:
  5275. leal/q $x(%reg1),%reg2
  5276. ...
  5277. shll/q $y,%reg2
  5278. To:
  5279. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5280. }
  5281. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5282. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5283. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5284. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5285. (taicpu(hp1).oper[0]^.val <= 3) then
  5286. begin
  5287. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5288. TransferUsedRegs(TmpUsedRegs);
  5289. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5290. if
  5291. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5292. (this works even if scalefactor is zero) }
  5293. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5294. { Ensure offset doesn't go out of bounds }
  5295. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5296. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5297. (
  5298. (
  5299. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5300. (
  5301. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5302. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5303. (
  5304. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5305. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5306. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5307. )
  5308. )
  5309. ) or (
  5310. (
  5311. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5312. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5313. ) and
  5314. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5315. )
  5316. ) then
  5317. begin
  5318. repeat
  5319. with taicpu(p).oper[0]^.ref^ do
  5320. begin
  5321. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5322. if index = base then
  5323. begin
  5324. if Multiple > 4 then
  5325. { Optimisation will no longer work because resultant
  5326. scale factor will exceed 8 }
  5327. Break;
  5328. base := NR_NO;
  5329. scalefactor := 2;
  5330. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5331. end
  5332. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5333. begin
  5334. { Scale factor only works on the index register }
  5335. index := base;
  5336. base := NR_NO;
  5337. end;
  5338. { For safety }
  5339. if scalefactor <= 1 then
  5340. begin
  5341. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5342. scalefactor := Multiple;
  5343. end
  5344. else
  5345. begin
  5346. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5347. scalefactor := scalefactor * Multiple;
  5348. end;
  5349. offset := offset * Multiple;
  5350. end;
  5351. RemoveInstruction(hp1);
  5352. Result := True;
  5353. Exit;
  5354. { This repeat..until loop exists for the benefit of Break }
  5355. until True;
  5356. end;
  5357. end;
  5358. end;
  5359. end;
  5360. end;
  5361. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5362. var
  5363. hp1 : tai;
  5364. SubInstr: Boolean;
  5365. ThisConst: TCGInt;
  5366. const
  5367. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5368. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5369. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5370. begin
  5371. Result := False;
  5372. if taicpu(p).oper[0]^.typ <> top_const then
  5373. { Should have been confirmed before calling }
  5374. InternalError(2021102601);
  5375. SubInstr := (taicpu(p).opcode = A_SUB);
  5376. if GetLastInstruction(p, hp1) and
  5377. (hp1.typ = ait_instruction) and
  5378. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5379. begin
  5380. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5381. { Bad size }
  5382. InternalError(2022042001);
  5383. case taicpu(hp1).opcode Of
  5384. A_INC:
  5385. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5386. begin
  5387. if SubInstr then
  5388. ThisConst := taicpu(p).oper[0]^.val - 1
  5389. else
  5390. ThisConst := taicpu(p).oper[0]^.val + 1;
  5391. end
  5392. else
  5393. Exit;
  5394. A_DEC:
  5395. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5396. begin
  5397. if SubInstr then
  5398. ThisConst := taicpu(p).oper[0]^.val + 1
  5399. else
  5400. ThisConst := taicpu(p).oper[0]^.val - 1;
  5401. end
  5402. else
  5403. Exit;
  5404. A_SUB:
  5405. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5406. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5407. begin
  5408. if SubInstr then
  5409. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5410. else
  5411. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5412. end
  5413. else
  5414. Exit;
  5415. A_ADD:
  5416. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5417. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5418. begin
  5419. if SubInstr then
  5420. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5421. else
  5422. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5423. end
  5424. else
  5425. Exit;
  5426. else
  5427. Exit;
  5428. end;
  5429. { Check that the values are in range }
  5430. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5431. { Overflow; abort }
  5432. Exit;
  5433. if (ThisConst = 0) then
  5434. begin
  5435. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5436. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5437. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5438. RemoveInstruction(hp1);
  5439. hp1 := tai(p.next);
  5440. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5441. if not GetLastInstruction(hp1, p) then
  5442. p := hp1;
  5443. end
  5444. else
  5445. begin
  5446. if taicpu(hp1).opercnt=1 then
  5447. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5448. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5449. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5450. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5451. else
  5452. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5453. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5454. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5455. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5456. RemoveInstruction(hp1);
  5457. taicpu(p).loadconst(0, ThisConst);
  5458. end;
  5459. Result := True;
  5460. end;
  5461. end;
  5462. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5463. begin
  5464. Result := False;
  5465. if UpdateTmpUsedRegs then
  5466. TransferUsedRegs(TmpUsedRegs);
  5467. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5468. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5469. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5470. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5471. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5472. (
  5473. (
  5474. (taicpu(hp1).opcode = A_TEST)
  5475. ) or (
  5476. (taicpu(hp1).opcode = A_CMP) and
  5477. { A sanity check more than anything }
  5478. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5479. )
  5480. ) then
  5481. begin
  5482. { change
  5483. mov mem, %reg
  5484. cmp/test x, %reg / test %reg,%reg
  5485. (reg deallocated)
  5486. to
  5487. cmp/test x, mem / cmp 0, mem
  5488. }
  5489. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5490. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5491. begin
  5492. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5493. if (taicpu(hp1).opcode = A_TEST) and
  5494. (
  5495. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5496. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5497. ) then
  5498. begin
  5499. taicpu(hp1).opcode := A_CMP;
  5500. taicpu(hp1).loadconst(0, 0);
  5501. end;
  5502. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5503. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5504. RemoveCurrentP(p, hp1);
  5505. Result := True;
  5506. Exit;
  5507. end;
  5508. end;
  5509. end;
  5510. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5511. var
  5512. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5513. ThisReg, SecondReg: TRegister;
  5514. JumpLoc: TAsmLabel;
  5515. NewSize: TOpSize;
  5516. begin
  5517. Result := False;
  5518. {
  5519. Convert:
  5520. j<c> .L1
  5521. .L2:
  5522. mov 1,reg
  5523. jmp .L3 (or ret, although it might not be a RET yet)
  5524. .L1:
  5525. mov 0,reg
  5526. jmp .L3 (or ret)
  5527. ( As long as .L3 <> .L1 or .L2)
  5528. To:
  5529. mov 0,reg
  5530. set<not(c)> reg
  5531. jmp .L3 (or ret)
  5532. .L2:
  5533. mov 1,reg
  5534. jmp .L3 (or ret)
  5535. .L1:
  5536. mov 0,reg
  5537. jmp .L3 (or ret)
  5538. }
  5539. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5540. Exit;
  5541. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5542. if GetNextInstruction(hp_label, hp2) and
  5543. MatchInstruction(hp2,A_MOV,[]) and
  5544. (taicpu(hp2).oper[0]^.typ = top_const) and
  5545. (
  5546. (
  5547. (taicpu(hp2).oper[1]^.typ = top_reg)
  5548. {$ifdef i386}
  5549. { Under i386, ESI, EDI, EBP and ESP
  5550. don't have an 8-bit representation }
  5551. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5552. {$endif i386}
  5553. ) or (
  5554. {$ifdef i386}
  5555. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5556. {$endif i386}
  5557. (taicpu(hp2).opsize = S_B)
  5558. )
  5559. ) and
  5560. GetNextInstruction(hp2, hp3) and
  5561. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5562. (
  5563. (taicpu(hp3).opcode=A_RET) or
  5564. (
  5565. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5566. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5567. )
  5568. ) and
  5569. GetNextInstruction(hp3, hp4) and
  5570. SkipAligns(hp4, hp4) and
  5571. (hp4.typ=ait_label) and
  5572. (tai_label(hp4).labsym=JumpLoc) and
  5573. (
  5574. not (cs_opt_size in current_settings.optimizerswitches) or
  5575. { If the initial jump is the label's only reference, then it will
  5576. become a dead label if the other conditions are met and hence
  5577. remove at least 2 instructions, including a jump }
  5578. (JumpLoc.getrefs = 1)
  5579. ) and
  5580. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5581. that will be optimised out }
  5582. GetNextInstruction(hp4, hp5) and
  5583. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5584. (taicpu(hp5).oper[0]^.typ = top_const) and
  5585. (
  5586. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5587. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5588. ) and
  5589. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5590. GetNextInstruction(hp5,hp6) and
  5591. (
  5592. (hp6.typ<>ait_label) or
  5593. SkipLabels(hp6, hp6)
  5594. ) and
  5595. (hp6.typ=ait_instruction) then
  5596. begin
  5597. { First, let's look at the two jumps that are hp3 and hp6 }
  5598. if not
  5599. (
  5600. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5601. (
  5602. (taicpu(hp6).opcode=A_RET) or
  5603. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5604. )
  5605. ) then
  5606. { If condition is False, then the JMP/RET instructions matched conventionally }
  5607. begin
  5608. { See if one of the jumps can be instantly converted into a RET }
  5609. if (taicpu(hp3).opcode=A_JMP) then
  5610. begin
  5611. { Reuse hp5 }
  5612. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5613. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5614. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5615. Exit;
  5616. if MatchInstruction(hp5, A_RET, []) then
  5617. begin
  5618. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5619. ConvertJumpToRET(hp3, hp5);
  5620. Result := True;
  5621. end
  5622. else
  5623. Exit;
  5624. end;
  5625. if (taicpu(hp6).opcode=A_JMP) then
  5626. begin
  5627. { Reuse hp5 }
  5628. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5629. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5630. Exit;
  5631. if MatchInstruction(hp5, A_RET, []) then
  5632. begin
  5633. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5634. ConvertJumpToRET(hp6, hp5);
  5635. Result := True;
  5636. end
  5637. else
  5638. Exit;
  5639. end;
  5640. if not
  5641. (
  5642. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5643. (
  5644. (taicpu(hp6).opcode=A_RET) or
  5645. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5646. )
  5647. ) then
  5648. { Still doesn't match }
  5649. Exit;
  5650. end;
  5651. if (taicpu(hp2).oper[0]^.val = 1) then
  5652. begin
  5653. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5654. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5655. end
  5656. else
  5657. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5658. if taicpu(hp2).opsize=S_B then
  5659. begin
  5660. if taicpu(hp2).oper[1]^.typ = top_reg then
  5661. begin
  5662. SecondReg := taicpu(hp2).oper[1]^.reg;
  5663. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5664. end
  5665. else
  5666. begin
  5667. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5668. SecondReg := NR_NO;
  5669. end;
  5670. hp_pos := p;
  5671. hp_allocstart := hp4;
  5672. end
  5673. else
  5674. begin
  5675. { Will be a register because the size can't be S_B otherwise }
  5676. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5677. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5678. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5679. if (cs_opt_size in current_settings.optimizerswitches) then
  5680. begin
  5681. { Favour using MOVZX when optimising for size }
  5682. case taicpu(hp2).opsize of
  5683. S_W:
  5684. NewSize := S_BW;
  5685. S_L:
  5686. NewSize := S_BL;
  5687. {$ifdef x86_64}
  5688. S_Q:
  5689. begin
  5690. NewSize := S_BL;
  5691. { Will implicitly zero-extend to 64-bit }
  5692. setsubreg(SecondReg, R_SUBD);
  5693. end;
  5694. {$endif x86_64}
  5695. else
  5696. InternalError(2022101301);
  5697. end;
  5698. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5699. { Inserting it right before p will guarantee that the flags are also tracked }
  5700. Asml.InsertBefore(hp5, p);
  5701. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5702. hp_pos := hp5;
  5703. hp_allocstart := hp4;
  5704. end
  5705. else
  5706. begin
  5707. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5708. { Inserting it right before p will guarantee that the flags are also tracked }
  5709. Asml.InsertBefore(hp5, p);
  5710. hp_pos := p;
  5711. hp_allocstart := hp5;
  5712. end;
  5713. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5714. end;
  5715. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5716. taicpu(hp4).condition := taicpu(p).condition;
  5717. asml.InsertBefore(hp4, hp_pos);
  5718. if taicpu(hp3).is_jmp then
  5719. begin
  5720. JumpLoc.decrefs;
  5721. MakeUnconditional(taicpu(p));
  5722. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5723. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5724. end
  5725. else
  5726. ConvertJumpToRET(p, hp3);
  5727. if SecondReg <> NR_NO then
  5728. { Ensure the destination register is allocated over this region }
  5729. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5730. if (JumpLoc.getrefs = 0) then
  5731. RemoveDeadCodeAfterJump(hp3);
  5732. Result:=true;
  5733. exit;
  5734. end;
  5735. end;
  5736. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5737. var
  5738. hp1, hp2: tai;
  5739. ActiveReg: TRegister;
  5740. OldOffset: asizeint;
  5741. ThisConst: TCGInt;
  5742. function RegDeallocated: Boolean;
  5743. begin
  5744. TransferUsedRegs(TmpUsedRegs);
  5745. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5746. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5747. end;
  5748. begin
  5749. Result:=false;
  5750. hp1 := nil;
  5751. { replace
  5752. subX const,%reg1
  5753. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5754. dealloc %reg1
  5755. by
  5756. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5757. }
  5758. if MatchOpType(taicpu(p),top_const,top_reg) then
  5759. begin
  5760. ActiveReg := taicpu(p).oper[1]^.reg;
  5761. { Ensures the entire register was updated }
  5762. if (taicpu(p).opsize >= S_L) and
  5763. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5764. MatchInstruction(hp1,A_LEA,[]) and
  5765. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5766. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5767. (
  5768. { Cover the case where the register in the reference is also the destination register }
  5769. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5770. (
  5771. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5772. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5773. RegDeallocated
  5774. )
  5775. ) then
  5776. begin
  5777. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5778. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5779. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5780. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5781. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5782. {$ifdef x86_64}
  5783. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5784. begin
  5785. { Overflow; abort }
  5786. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5787. end
  5788. else
  5789. {$endif x86_64}
  5790. begin
  5791. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5792. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5793. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5794. RemoveCurrentP(p, hp1)
  5795. else
  5796. RemoveCurrentP(p);
  5797. result:=true;
  5798. Exit;
  5799. end;
  5800. end;
  5801. if (
  5802. { Save calling GetNextInstructionUsingReg again }
  5803. Assigned(hp1) or
  5804. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5805. ) and
  5806. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5807. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5808. begin
  5809. if taicpu(hp1).oper[0]^.typ = top_const then
  5810. begin
  5811. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5812. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5813. Result := True;
  5814. { Handle any overflows }
  5815. case taicpu(p).opsize of
  5816. S_B:
  5817. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5818. S_W:
  5819. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5820. S_L:
  5821. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5822. {$ifdef x86_64}
  5823. S_Q:
  5824. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5825. { Overflow; abort }
  5826. Result := False
  5827. else
  5828. taicpu(p).oper[0]^.val := ThisConst;
  5829. {$endif x86_64}
  5830. else
  5831. InternalError(2021102611);
  5832. end;
  5833. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5834. if Result then
  5835. begin
  5836. if (taicpu(p).oper[0]^.val < 0) and
  5837. (
  5838. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5839. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5840. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5841. ) then
  5842. begin
  5843. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5844. taicpu(p).opcode := A_SUB;
  5845. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5846. end
  5847. else
  5848. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5849. RemoveInstruction(hp1);
  5850. end;
  5851. end
  5852. else
  5853. begin
  5854. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5855. TransferUsedRegs(TmpUsedRegs);
  5856. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5857. hp2 := p;
  5858. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5859. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5860. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5861. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5862. begin
  5863. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5864. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5865. Asml.Remove(p);
  5866. Asml.InsertAfter(p, hp1);
  5867. p := hp1;
  5868. Result := True;
  5869. Exit;
  5870. end;
  5871. end;
  5872. end;
  5873. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5874. { * change "sub/add const1, reg" or "dec reg" followed by
  5875. "sub const2, reg" to one "sub ..., reg" }
  5876. {$ifdef i386}
  5877. if (taicpu(p).oper[0]^.val = 2) and
  5878. (ActiveReg = NR_ESP) and
  5879. { Don't do the sub/push optimization if the sub }
  5880. { comes from setting up the stack frame (JM) }
  5881. (not(GetLastInstruction(p,hp1)) or
  5882. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5883. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5884. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5885. begin
  5886. hp1 := tai(p.next);
  5887. while Assigned(hp1) and
  5888. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5889. not RegReadByInstruction(NR_ESP,hp1) and
  5890. not RegModifiedByInstruction(NR_ESP,hp1) do
  5891. hp1 := tai(hp1.next);
  5892. if Assigned(hp1) and
  5893. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5894. begin
  5895. taicpu(hp1).changeopsize(S_L);
  5896. if taicpu(hp1).oper[0]^.typ=top_reg then
  5897. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5898. hp1 := tai(p.next);
  5899. RemoveCurrentp(p, hp1);
  5900. Result:=true;
  5901. exit;
  5902. end;
  5903. end;
  5904. {$endif i386}
  5905. if DoArithCombineOpt(p) then
  5906. Result:=true;
  5907. end;
  5908. end;
  5909. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5910. var
  5911. TmpBool1,TmpBool2 : Boolean;
  5912. tmpref : treference;
  5913. hp1,hp2: tai;
  5914. mask: tcgint;
  5915. begin
  5916. Result:=false;
  5917. { All these optimisations work on "shl/sal const,%reg" }
  5918. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5919. Exit;
  5920. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5921. (taicpu(p).oper[0]^.val <= 3) then
  5922. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5923. begin
  5924. { should we check the next instruction? }
  5925. TmpBool1 := True;
  5926. { have we found an add/sub which could be
  5927. integrated in the lea? }
  5928. TmpBool2 := False;
  5929. reference_reset(tmpref,2,[]);
  5930. TmpRef.index := taicpu(p).oper[1]^.reg;
  5931. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5932. while TmpBool1 and
  5933. GetNextInstruction(p, hp1) and
  5934. (tai(hp1).typ = ait_instruction) and
  5935. ((((taicpu(hp1).opcode = A_ADD) or
  5936. (taicpu(hp1).opcode = A_SUB)) and
  5937. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5938. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5939. (((taicpu(hp1).opcode = A_INC) or
  5940. (taicpu(hp1).opcode = A_DEC)) and
  5941. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5942. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5943. ((taicpu(hp1).opcode = A_LEA) and
  5944. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5945. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5946. (not GetNextInstruction(hp1,hp2) or
  5947. not instrReadsFlags(hp2)) Do
  5948. begin
  5949. TmpBool1 := False;
  5950. if taicpu(hp1).opcode=A_LEA then
  5951. begin
  5952. if (TmpRef.base = NR_NO) and
  5953. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5954. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5955. { Segment register isn't a concern here }
  5956. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5957. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5958. begin
  5959. TmpBool1 := True;
  5960. TmpBool2 := True;
  5961. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5962. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5963. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5964. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5965. RemoveInstruction(hp1);
  5966. end
  5967. end
  5968. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5969. begin
  5970. TmpBool1 := True;
  5971. TmpBool2 := True;
  5972. case taicpu(hp1).opcode of
  5973. A_ADD:
  5974. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5975. A_SUB:
  5976. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5977. else
  5978. internalerror(2019050536);
  5979. end;
  5980. RemoveInstruction(hp1);
  5981. end
  5982. else
  5983. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5984. (((taicpu(hp1).opcode = A_ADD) and
  5985. (TmpRef.base = NR_NO)) or
  5986. (taicpu(hp1).opcode = A_INC) or
  5987. (taicpu(hp1).opcode = A_DEC)) then
  5988. begin
  5989. TmpBool1 := True;
  5990. TmpBool2 := True;
  5991. case taicpu(hp1).opcode of
  5992. A_ADD:
  5993. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5994. A_INC:
  5995. inc(TmpRef.offset);
  5996. A_DEC:
  5997. dec(TmpRef.offset);
  5998. else
  5999. internalerror(2019050535);
  6000. end;
  6001. RemoveInstruction(hp1);
  6002. end;
  6003. end;
  6004. if TmpBool2
  6005. {$ifndef x86_64}
  6006. or
  6007. ((current_settings.optimizecputype < cpu_Pentium2) and
  6008. (taicpu(p).oper[0]^.val <= 3) and
  6009. not(cs_opt_size in current_settings.optimizerswitches))
  6010. {$endif x86_64}
  6011. then
  6012. begin
  6013. if not(TmpBool2) and
  6014. (taicpu(p).oper[0]^.val=1) then
  6015. begin
  6016. taicpu(p).opcode := A_ADD;
  6017. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6018. end
  6019. else
  6020. begin
  6021. taicpu(p).opcode := A_LEA;
  6022. taicpu(p).loadref(0, TmpRef);
  6023. end;
  6024. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6025. Result := True;
  6026. end;
  6027. end
  6028. {$ifndef x86_64}
  6029. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6030. begin
  6031. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6032. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6033. (unlike shl, which is only Tairable in the U pipe) }
  6034. if taicpu(p).oper[0]^.val=1 then
  6035. begin
  6036. taicpu(p).opcode := A_ADD;
  6037. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6038. Result := True;
  6039. end
  6040. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6041. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6042. else if (taicpu(p).opsize = S_L) and
  6043. (taicpu(p).oper[0]^.val<= 3) then
  6044. begin
  6045. reference_reset(tmpref,2,[]);
  6046. TmpRef.index := taicpu(p).oper[1]^.reg;
  6047. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6048. taicpu(p).opcode := A_LEA;
  6049. taicpu(p).loadref(0, TmpRef);
  6050. Result := True;
  6051. end;
  6052. end
  6053. {$endif x86_64}
  6054. else if
  6055. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6056. (
  6057. (
  6058. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6059. SetAndTest(hp1, hp2)
  6060. {$ifdef x86_64}
  6061. ) or
  6062. (
  6063. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6064. GetNextInstruction(hp1, hp2) and
  6065. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6066. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6067. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6068. {$endif x86_64}
  6069. )
  6070. ) and
  6071. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6072. begin
  6073. { Change:
  6074. shl x, %reg1
  6075. mov -(1<<x), %reg2
  6076. and %reg2, %reg1
  6077. Or:
  6078. shl x, %reg1
  6079. and -(1<<x), %reg1
  6080. To just:
  6081. shl x, %reg1
  6082. Since the and operation only zeroes bits that are already zero from the shl operation
  6083. }
  6084. case taicpu(p).oper[0]^.val of
  6085. 8:
  6086. mask:=$FFFFFFFFFFFFFF00;
  6087. 16:
  6088. mask:=$FFFFFFFFFFFF0000;
  6089. 32:
  6090. mask:=$FFFFFFFF00000000;
  6091. 63:
  6092. { Constant pre-calculated to prevent overflow errors with Int64 }
  6093. mask:=$8000000000000000;
  6094. else
  6095. begin
  6096. if taicpu(p).oper[0]^.val >= 64 then
  6097. { Shouldn't happen realistically, since the register
  6098. is guaranteed to be set to zero at this point }
  6099. mask := 0
  6100. else
  6101. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6102. end;
  6103. end;
  6104. if taicpu(hp1).oper[0]^.val = mask then
  6105. begin
  6106. { Everything checks out, perform the optimisation, as long as
  6107. the FLAGS register isn't being used}
  6108. TransferUsedRegs(TmpUsedRegs);
  6109. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6110. {$ifdef x86_64}
  6111. if (hp1 <> hp2) then
  6112. begin
  6113. { "shl/mov/and" version }
  6114. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6115. { Don't do the optimisation if the FLAGS register is in use }
  6116. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6117. begin
  6118. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6119. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6120. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6121. begin
  6122. RemoveInstruction(hp1);
  6123. Result := True;
  6124. end;
  6125. { Only set Result to True if the 'mov' instruction was removed }
  6126. RemoveInstruction(hp2);
  6127. end;
  6128. end
  6129. else
  6130. {$endif x86_64}
  6131. begin
  6132. { "shl/and" version }
  6133. { Don't do the optimisation if the FLAGS register is in use }
  6134. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6135. begin
  6136. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6137. RemoveInstruction(hp1);
  6138. Result := True;
  6139. end;
  6140. end;
  6141. Exit;
  6142. end
  6143. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6144. begin
  6145. { Even if the mask doesn't allow for its removal, we might be
  6146. able to optimise the mask for the "shl/and" version, which
  6147. may permit other peephole optimisations }
  6148. {$ifdef DEBUG_AOPTCPU}
  6149. mask := taicpu(hp1).oper[0]^.val and mask;
  6150. if taicpu(hp1).oper[0]^.val <> mask then
  6151. begin
  6152. DebugMsg(
  6153. SPeepholeOptimization +
  6154. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6155. ' to $' + debug_tostr(mask) +
  6156. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6157. taicpu(hp1).oper[0]^.val := mask;
  6158. end;
  6159. {$else DEBUG_AOPTCPU}
  6160. { If debugging is off, just set the operand even if it's the same }
  6161. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6162. {$endif DEBUG_AOPTCPU}
  6163. end;
  6164. end;
  6165. {
  6166. change
  6167. shl/sal const,reg
  6168. <op> ...(...,reg,1),...
  6169. into
  6170. <op> ...(...,reg,1 shl const),...
  6171. if const in 1..3
  6172. }
  6173. if MatchOpType(taicpu(p), top_const, top_reg) and
  6174. (taicpu(p).oper[0]^.val in [1..3]) and
  6175. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6176. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6177. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6178. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6179. MatchOpType(taicpu(hp1),top_ref))
  6180. ) and
  6181. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6182. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6183. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6184. begin
  6185. TransferUsedRegs(TmpUsedRegs);
  6186. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6187. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6188. begin
  6189. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6190. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6191. RemoveCurrentP(p);
  6192. Result:=true;
  6193. end;
  6194. end;
  6195. end;
  6196. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6197. begin
  6198. case shr_size of
  6199. S_B:
  6200. { No valid combinations }
  6201. Result := False;
  6202. S_W:
  6203. Result := (Shift >= 8) and (movz_size = S_BW);
  6204. S_L:
  6205. Result :=
  6206. (Shift >= 24) { Any opsize is valid for this shift } or
  6207. ((Shift >= 16) and (movz_size = S_WL));
  6208. {$ifdef x86_64}
  6209. S_Q:
  6210. Result :=
  6211. (Shift >= 56) { Any opsize is valid for this shift } or
  6212. ((Shift >= 48) and (movz_size = S_WL));
  6213. {$endif x86_64}
  6214. else
  6215. InternalError(2022081510);
  6216. end;
  6217. end;
  6218. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6219. var
  6220. hp1, hp2: tai;
  6221. Shift: TCGInt;
  6222. LimitSize: Topsize;
  6223. DoNotMerge: Boolean;
  6224. begin
  6225. Result := False;
  6226. { All these optimisations work on "shr const,%reg" }
  6227. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6228. Exit;
  6229. DoNotMerge := False;
  6230. Shift := taicpu(p).oper[0]^.val;
  6231. LimitSize := taicpu(p).opsize;
  6232. hp1 := p;
  6233. repeat
  6234. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6235. Exit;
  6236. case taicpu(hp1).opcode of
  6237. A_TEST, A_CMP, A_Jcc:
  6238. { Skip over conditional jumps and relevant comparisons }
  6239. Continue;
  6240. A_MOVZX:
  6241. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6242. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6243. begin
  6244. { Since the original register is being read as is, subsequent
  6245. SHRs must not be merged at this point }
  6246. DoNotMerge := True;
  6247. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6248. begin
  6249. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6250. begin
  6251. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6252. taicpu(hp1).opcode := A_MOV;
  6253. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6254. case taicpu(hp1).opsize of
  6255. S_BW:
  6256. taicpu(hp1).opsize := S_W;
  6257. S_BL, S_WL:
  6258. taicpu(hp1).opsize := S_L;
  6259. else
  6260. InternalError(2022081503);
  6261. end;
  6262. { p itself hasn't changed, so no need to set Result to True }
  6263. Include(OptsToCheck, aoc_ForceNewIteration);
  6264. { See if there's anything afterwards that can be
  6265. optimised, since the input register hasn't changed }
  6266. Continue;
  6267. end;
  6268. { NOTE: If the MOVZX instruction reads and writes the same
  6269. register, defer this to the post-peephole optimisation stage }
  6270. Exit;
  6271. end;
  6272. end;
  6273. A_SHL, A_SAL, A_SHR:
  6274. if (taicpu(hp1).opsize <= LimitSize) and
  6275. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6276. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6277. begin
  6278. { Make sure the sizes don't exceed the register size limit
  6279. (measured by the shift value falling below the limit) }
  6280. if taicpu(hp1).opsize < LimitSize then
  6281. LimitSize := taicpu(hp1).opsize;
  6282. if taicpu(hp1).opcode = A_SHR then
  6283. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6284. else
  6285. begin
  6286. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6287. DoNotMerge := True;
  6288. end;
  6289. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6290. Exit;
  6291. { Since we've established that the combined shift is within
  6292. limits, we can actually combine the adjacent SHR
  6293. instructions even if they're different sizes }
  6294. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6295. begin
  6296. hp2 := tai(hp1.Previous);
  6297. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6298. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6299. RemoveInstruction(hp1);
  6300. hp1 := hp2;
  6301. { Though p has changed, only the constant has, and its
  6302. effects can still be detected on the next iteration of
  6303. the repeat..until loop }
  6304. Include(OptsToCheck, aoc_ForceNewIteration);
  6305. end;
  6306. { Move onto the next instruction }
  6307. Continue;
  6308. end;
  6309. else
  6310. ;
  6311. end;
  6312. Break;
  6313. until False;
  6314. end;
  6315. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6316. var
  6317. CurrentRef: TReference;
  6318. FullReg: TRegister;
  6319. hp1, hp2: tai;
  6320. begin
  6321. Result := False;
  6322. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6323. Exit;
  6324. { We assume you've checked if the operand is actually a reference by
  6325. this point. If it isn't, you'll most likely get an access violation }
  6326. CurrentRef := first_mov.oper[1]^.ref^;
  6327. { Memory must be aligned }
  6328. if (CurrentRef.offset mod 4) <> 0 then
  6329. Exit;
  6330. Inc(CurrentRef.offset);
  6331. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6332. if MatchOperand(second_mov.oper[0]^, 0) and
  6333. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6334. GetNextInstruction(second_mov, hp1) and
  6335. (hp1.typ = ait_instruction) and
  6336. (taicpu(hp1).opcode = A_MOV) and
  6337. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6338. (taicpu(hp1).oper[0]^.val = 0) then
  6339. begin
  6340. Inc(CurrentRef.offset);
  6341. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6342. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6343. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6344. begin
  6345. case taicpu(hp1).opsize of
  6346. S_B:
  6347. if GetNextInstruction(hp1, hp2) and
  6348. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6349. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6350. (taicpu(hp2).oper[0]^.val = 0) then
  6351. begin
  6352. Inc(CurrentRef.offset);
  6353. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6354. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6355. (taicpu(hp2).opsize = S_B) then
  6356. begin
  6357. RemoveInstruction(hp1);
  6358. RemoveInstruction(hp2);
  6359. first_mov.opsize := S_L;
  6360. if first_mov.oper[0]^.typ = top_reg then
  6361. begin
  6362. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6363. { Reuse second_mov as a MOVZX instruction }
  6364. second_mov.opcode := A_MOVZX;
  6365. second_mov.opsize := S_BL;
  6366. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6367. second_mov.loadreg(1, FullReg);
  6368. first_mov.oper[0]^.reg := FullReg;
  6369. asml.Remove(second_mov);
  6370. asml.InsertBefore(second_mov, first_mov);
  6371. end
  6372. else
  6373. { It's a value }
  6374. begin
  6375. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6376. RemoveInstruction(second_mov);
  6377. end;
  6378. Result := True;
  6379. Exit;
  6380. end;
  6381. end;
  6382. S_W:
  6383. begin
  6384. RemoveInstruction(hp1);
  6385. first_mov.opsize := S_L;
  6386. if first_mov.oper[0]^.typ = top_reg then
  6387. begin
  6388. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6389. { Reuse second_mov as a MOVZX instruction }
  6390. second_mov.opcode := A_MOVZX;
  6391. second_mov.opsize := S_BL;
  6392. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6393. second_mov.loadreg(1, FullReg);
  6394. first_mov.oper[0]^.reg := FullReg;
  6395. asml.Remove(second_mov);
  6396. asml.InsertBefore(second_mov, first_mov);
  6397. end
  6398. else
  6399. { It's a value }
  6400. begin
  6401. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6402. RemoveInstruction(second_mov);
  6403. end;
  6404. Result := True;
  6405. Exit;
  6406. end;
  6407. else
  6408. ;
  6409. end;
  6410. end;
  6411. end;
  6412. end;
  6413. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6414. { returns true if a "continue" should be done after this optimization }
  6415. var
  6416. hp1, hp2: tai;
  6417. begin
  6418. Result := false;
  6419. if MatchOpType(taicpu(p),top_ref) and
  6420. GetNextInstruction(p, hp1) and
  6421. (hp1.typ = ait_instruction) and
  6422. (((taicpu(hp1).opcode = A_FLD) and
  6423. (taicpu(p).opcode = A_FSTP)) or
  6424. ((taicpu(p).opcode = A_FISTP) and
  6425. (taicpu(hp1).opcode = A_FILD))) and
  6426. MatchOpType(taicpu(hp1),top_ref) and
  6427. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6428. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6429. begin
  6430. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6431. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6432. GetNextInstruction(hp1, hp2) and
  6433. (((hp2.typ = ait_instruction) and
  6434. IsExitCode(hp2) and
  6435. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6436. not(assigned(current_procinfo.procdef.funcretsym) and
  6437. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6438. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6439. { fstp <temp>
  6440. fld <temp>
  6441. <dealloc> <temp>
  6442. }
  6443. (SetAndTest(tai(hp1.next),hp2) and (hp2.typ = ait_tempalloc) and
  6444. (tai_tempalloc(hp2).allocation=false) and
  6445. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6446. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6447. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6448. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6449. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6450. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6451. )
  6452. )
  6453. ) then
  6454. begin
  6455. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6456. RemoveInstruction(hp1);
  6457. RemoveCurrentP(p, hp2);
  6458. { first case: exit code }
  6459. if hp2.typ = ait_instruction then
  6460. RemoveLastDeallocForFuncRes(p);
  6461. Result := true;
  6462. end
  6463. else
  6464. { we can do this only in fast math mode as fstp is rounding ...
  6465. ... still disabled as it breaks the compiler and/or rtl }
  6466. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6467. { ... or if another fstp equal to the first one follows }
  6468. (GetNextInstruction(hp1,hp2) and
  6469. (hp2.typ = ait_instruction) and
  6470. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6471. (taicpu(p).opsize=taicpu(hp2).opsize))
  6472. ) and
  6473. { fst can't store an extended/comp value }
  6474. (taicpu(p).opsize <> S_FX) and
  6475. (taicpu(p).opsize <> S_IQ) then
  6476. begin
  6477. if (taicpu(p).opcode = A_FSTP) then
  6478. taicpu(p).opcode := A_FST
  6479. else
  6480. taicpu(p).opcode := A_FIST;
  6481. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6482. RemoveInstruction(hp1);
  6483. end;
  6484. end;
  6485. end;
  6486. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6487. var
  6488. hp1, hp2: tai;
  6489. begin
  6490. result:=false;
  6491. if MatchOpType(taicpu(p),top_reg) and
  6492. GetNextInstruction(p, hp1) and
  6493. (hp1.typ = Ait_Instruction) and
  6494. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6495. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6496. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6497. { change to
  6498. fld reg fxxx reg,st
  6499. fxxxp st, st1 (hp1)
  6500. Remark: non commutative operations must be reversed!
  6501. }
  6502. begin
  6503. case taicpu(hp1).opcode Of
  6504. A_FMULP,A_FADDP,
  6505. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6506. begin
  6507. case taicpu(hp1).opcode Of
  6508. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6509. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6510. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6511. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6512. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6513. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6514. else
  6515. internalerror(2019050534);
  6516. end;
  6517. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6518. taicpu(hp1).oper[1]^.reg := NR_ST;
  6519. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6520. RemoveCurrentP(p, hp1);
  6521. Result:=true;
  6522. exit;
  6523. end;
  6524. else
  6525. ;
  6526. end;
  6527. end
  6528. else
  6529. if MatchOpType(taicpu(p),top_ref) and
  6530. GetNextInstruction(p, hp2) and
  6531. (hp2.typ = Ait_Instruction) and
  6532. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6533. (taicpu(p).opsize in [S_FS, S_FL]) and
  6534. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6535. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6536. if GetLastInstruction(p, hp1) and
  6537. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6538. MatchOpType(taicpu(hp1),top_ref) and
  6539. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6540. if ((taicpu(hp2).opcode = A_FMULP) or
  6541. (taicpu(hp2).opcode = A_FADDP)) then
  6542. { change to
  6543. fld/fst mem1 (hp1) fld/fst mem1
  6544. fld mem1 (p) fadd/
  6545. faddp/ fmul st, st
  6546. fmulp st, st1 (hp2) }
  6547. begin
  6548. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6549. RemoveCurrentP(p, hp1);
  6550. if (taicpu(hp2).opcode = A_FADDP) then
  6551. taicpu(hp2).opcode := A_FADD
  6552. else
  6553. taicpu(hp2).opcode := A_FMUL;
  6554. taicpu(hp2).oper[1]^.reg := NR_ST;
  6555. end
  6556. else
  6557. { change to
  6558. fld/fst mem1 (hp1) fld/fst mem1
  6559. fld mem1 (p) fld st
  6560. }
  6561. begin
  6562. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6563. taicpu(p).changeopsize(S_FL);
  6564. taicpu(p).loadreg(0,NR_ST);
  6565. end
  6566. else
  6567. begin
  6568. case taicpu(hp2).opcode Of
  6569. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6570. { change to
  6571. fld/fst mem1 (hp1) fld/fst mem1
  6572. fld mem2 (p) fxxx mem2
  6573. fxxxp st, st1 (hp2) }
  6574. begin
  6575. case taicpu(hp2).opcode Of
  6576. A_FADDP: taicpu(p).opcode := A_FADD;
  6577. A_FMULP: taicpu(p).opcode := A_FMUL;
  6578. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6579. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6580. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6581. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6582. else
  6583. internalerror(2019050533);
  6584. end;
  6585. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6586. RemoveInstruction(hp2);
  6587. end
  6588. else
  6589. ;
  6590. end
  6591. end
  6592. end;
  6593. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6594. begin
  6595. Result := condition_in(cond1, cond2) or
  6596. { Not strictly subsets due to the actual flags checked, but because we're
  6597. comparing integers, E is a subset of AE and GE and their aliases }
  6598. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6599. end;
  6600. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6601. var
  6602. v: TCGInt;
  6603. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6604. FirstMatch: Boolean;
  6605. NewReg: TRegister;
  6606. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6607. begin
  6608. Result:=false;
  6609. { All these optimisations need a next instruction }
  6610. if not GetNextInstruction(p, hp1) then
  6611. Exit;
  6612. { Search for:
  6613. cmp ###,###
  6614. j(c1) @lbl1
  6615. ...
  6616. @lbl:
  6617. cmp ###,### (same comparison as above)
  6618. j(c2) @lbl2
  6619. If c1 is a subset of c2, change to:
  6620. cmp ###,###
  6621. j(c1) @lbl2
  6622. (@lbl1 may become a dead label as a result)
  6623. }
  6624. { Also handle cases where there are multiple jumps in a row }
  6625. p_jump := hp1;
  6626. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6627. begin
  6628. if IsJumpToLabel(taicpu(p_jump)) then
  6629. begin
  6630. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6631. p_label := nil;
  6632. if Assigned(JumpLabel) then
  6633. p_label := getlabelwithsym(JumpLabel);
  6634. if Assigned(p_label) and
  6635. GetNextInstruction(p_label, p_dist) and
  6636. MatchInstruction(p_dist, A_CMP, []) and
  6637. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6638. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6639. GetNextInstruction(p_dist, hp1_dist) and
  6640. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6641. begin
  6642. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6643. if JumpLabel = JumpLabel_dist then
  6644. { This is an infinite loop }
  6645. Exit;
  6646. { Best optimisation when the first condition is a subset (or equal) of the second }
  6647. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6648. begin
  6649. { Any registers used here will already be allocated }
  6650. if Assigned(JumpLabel) then
  6651. JumpLabel.DecRefs;
  6652. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6653. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6654. Result := True;
  6655. { Don't exit yet. Since p and p_jump haven't actually been
  6656. removed, we can check for more on this iteration }
  6657. end
  6658. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6659. GetNextInstruction(hp1_dist, hp1_label) and
  6660. SkipAligns(hp1_label, hp1_label) and
  6661. (hp1_label.typ = ait_label) then
  6662. begin
  6663. JumpLabel_far := tai_label(hp1_label).labsym;
  6664. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6665. { This is an infinite loop }
  6666. Exit;
  6667. if Assigned(JumpLabel_far) then
  6668. begin
  6669. { In this situation, if the first jump branches, the second one will never,
  6670. branch so change the destination label to after the second jump }
  6671. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6672. if Assigned(JumpLabel) then
  6673. JumpLabel.DecRefs;
  6674. JumpLabel_far.IncRefs;
  6675. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6676. Result := True;
  6677. { Don't exit yet. Since p and p_jump haven't actually been
  6678. removed, we can check for more on this iteration }
  6679. Continue;
  6680. end;
  6681. end;
  6682. end;
  6683. end;
  6684. { Search for:
  6685. cmp ###,###
  6686. j(c1) @lbl1
  6687. cmp ###,### (same as first)
  6688. Remove second cmp
  6689. }
  6690. if GetNextInstruction(p_jump, hp2) and
  6691. (
  6692. (
  6693. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6694. (
  6695. (
  6696. MatchOpType(taicpu(p), top_const, top_reg) and
  6697. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6698. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6699. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6700. ) or (
  6701. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6702. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6703. )
  6704. )
  6705. ) or (
  6706. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6707. MatchOperand(taicpu(p).oper[0]^, 0) and
  6708. (taicpu(p).oper[1]^.typ = top_reg) and
  6709. MatchInstruction(hp2, A_TEST, []) and
  6710. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6711. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6712. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6713. )
  6714. ) then
  6715. begin
  6716. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6717. RemoveInstruction(hp2);
  6718. Result := True;
  6719. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6720. end;
  6721. GetNextInstruction(p_jump, p_jump);
  6722. end;
  6723. {
  6724. Try to optimise the following:
  6725. cmp $x,### ($x and $y can be registers or constants)
  6726. je @lbl1 (only reference)
  6727. cmp $y,### (### are identical)
  6728. @Lbl:
  6729. sete %reg1
  6730. Change to:
  6731. cmp $x,###
  6732. sete %reg2 (allocate new %reg2)
  6733. cmp $y,###
  6734. sete %reg1
  6735. orb %reg2,%reg1
  6736. (dealloc %reg2)
  6737. This adds an instruction (so don't perform under -Os), but it removes
  6738. a conditional branch.
  6739. }
  6740. if not (cs_opt_size in current_settings.optimizerswitches) and
  6741. (
  6742. (hp1 = p_jump) or
  6743. GetNextInstruction(p, hp1)
  6744. ) and
  6745. MatchInstruction(hp1, A_Jcc, []) and
  6746. IsJumpToLabel(taicpu(hp1)) and
  6747. (taicpu(hp1).condition in [C_E, C_Z]) and
  6748. GetNextInstruction(hp1, hp2) and
  6749. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6750. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6751. { The first operand of CMP instructions can only be a register or
  6752. immediate anyway, so no need to check }
  6753. GetNextInstruction(hp2, p_label) and
  6754. (
  6755. (p_label.typ = ait_label) or
  6756. (
  6757. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6758. to potentially cut down on the iterations of Pass 1 }
  6759. MatchInstruction(p_label, A_Jcc, []) and
  6760. IsJumpToLabel(taicpu(p_label)) and
  6761. { Use p_dist to hold the jump briefly }
  6762. SetAndTest(p_label, p_dist) and
  6763. GetNextInstruction(p_dist, p_label) and
  6764. (p_label.typ = ait_label) and
  6765. (tai_label(p_label).labsym.getrefs >= 2) and
  6766. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6767. { We might as well collapse the jump now }
  6768. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6769. )
  6770. ) and
  6771. (tai_label(p_label).labsym.getrefs = 1) and
  6772. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6773. GetNextInstruction(p_label, p_dist) and
  6774. MatchInstruction(p_dist, A_SETcc, []) and
  6775. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6776. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6777. { Get the instruction after the SETcc instruction so we can
  6778. allocate a new register over the entire range }
  6779. GetNextInstruction(p_dist, hp1_dist) then
  6780. begin
  6781. TransferUsedRegs(TmpUsedRegs);
  6782. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6783. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6784. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6785. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6786. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6787. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6788. begin
  6789. { Register can appear in p if it's not used afterwards, so only
  6790. allocate between hp1 and hp1_dist }
  6791. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6792. if NewReg <> NR_NO then
  6793. begin
  6794. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6795. { Change the jump instruction into a SETcc instruction }
  6796. taicpu(hp1).opcode := A_SETcc;
  6797. taicpu(hp1).opsize := S_B;
  6798. taicpu(hp1).loadreg(0, NewReg);
  6799. { This is now a dead label }
  6800. tai_label(p_label).labsym.decrefs;
  6801. { Prefer adding before the next instruction so the FLAGS
  6802. register is deallocated first }
  6803. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6804. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6805. AsmL.InsertBefore(
  6806. hp2,
  6807. hp1_dist
  6808. );
  6809. { Make sure the new register is in use over the new instruction
  6810. (long-winded, but things work best when the FLAGS register
  6811. is not allocated here) }
  6812. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6813. Result := True;
  6814. { Don't exit yet, as p wasn't changed and hp1, while
  6815. modified, is still intact and might be optimised by the
  6816. SETcc optimisation below }
  6817. end;
  6818. end;
  6819. end;
  6820. if taicpu(p).oper[0]^.typ = top_const then
  6821. begin
  6822. if (taicpu(p).oper[0]^.val = 0) and
  6823. (taicpu(p).oper[1]^.typ = top_reg) and
  6824. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6825. begin
  6826. hp2 := p;
  6827. FirstMatch := True;
  6828. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6829. anything meaningful once it's converted to "test %reg,%reg";
  6830. additionally, some jumps will always (or never) branch, so
  6831. evaluate every jump immediately following the
  6832. comparison, optimising the conditions if possible.
  6833. Similarly with SETcc... those that are always set to 0 or 1
  6834. are changed to MOV instructions }
  6835. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6836. (
  6837. GetNextInstruction(hp2, hp1) and
  6838. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6839. ) do
  6840. begin
  6841. FirstMatch := False;
  6842. case taicpu(hp1).condition of
  6843. C_B, C_C, C_NAE, C_O:
  6844. { For B/NAE:
  6845. Will never branch since an unsigned integer can never be below zero
  6846. For C/O:
  6847. Result cannot overflow because 0 is being subtracted
  6848. }
  6849. begin
  6850. if taicpu(hp1).opcode = A_Jcc then
  6851. begin
  6852. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6853. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6854. RemoveInstruction(hp1);
  6855. { Since hp1 was deleted, hp2 must not be updated }
  6856. Continue;
  6857. end
  6858. else
  6859. begin
  6860. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6861. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6862. taicpu(hp1).opcode := A_MOV;
  6863. taicpu(hp1).ops := 2;
  6864. taicpu(hp1).condition := C_None;
  6865. taicpu(hp1).opsize := S_B;
  6866. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6867. taicpu(hp1).loadconst(0, 0);
  6868. end;
  6869. end;
  6870. C_BE, C_NA:
  6871. begin
  6872. { Will only branch if equal to zero }
  6873. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6874. taicpu(hp1).condition := C_E;
  6875. end;
  6876. C_A, C_NBE:
  6877. begin
  6878. { Will only branch if not equal to zero }
  6879. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6880. taicpu(hp1).condition := C_NE;
  6881. end;
  6882. C_AE, C_NB, C_NC, C_NO:
  6883. begin
  6884. { Will always branch }
  6885. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6886. if taicpu(hp1).opcode = A_Jcc then
  6887. begin
  6888. MakeUnconditional(taicpu(hp1));
  6889. { Any jumps/set that follow will now be dead code }
  6890. RemoveDeadCodeAfterJump(taicpu(hp1));
  6891. Break;
  6892. end
  6893. else
  6894. begin
  6895. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6896. taicpu(hp1).opcode := A_MOV;
  6897. taicpu(hp1).ops := 2;
  6898. taicpu(hp1).condition := C_None;
  6899. taicpu(hp1).opsize := S_B;
  6900. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6901. taicpu(hp1).loadconst(0, 1);
  6902. end;
  6903. end;
  6904. C_None:
  6905. InternalError(2020012201);
  6906. C_P, C_PE, C_NP, C_PO:
  6907. { We can't handle parity checks and they should never be generated
  6908. after a general-purpose CMP (it's used in some floating-point
  6909. comparisons that don't use CMP) }
  6910. InternalError(2020012202);
  6911. else
  6912. { Zero/Equality, Sign, their complements and all of the
  6913. signed comparisons do not need to be converted };
  6914. end;
  6915. hp2 := hp1;
  6916. end;
  6917. { Convert the instruction to a TEST }
  6918. taicpu(p).opcode := A_TEST;
  6919. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6920. Result := True;
  6921. Exit;
  6922. end
  6923. else if (taicpu(p).oper[0]^.val = 1) and
  6924. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6925. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6926. begin
  6927. { Convert; To:
  6928. cmp $1,r/m cmp $0,r/m
  6929. jl @lbl jle @lbl
  6930. }
  6931. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6932. taicpu(p).oper[0]^.val := 0;
  6933. taicpu(hp1).condition := C_LE;
  6934. { If the instruction is now "cmp $0,%reg", convert it to a
  6935. TEST (and effectively do the work of the "cmp $0,%reg" in
  6936. the block above)
  6937. If it's a reference, we can get away with not setting
  6938. Result to True because he haven't evaluated the jump
  6939. in this pass yet.
  6940. }
  6941. if (taicpu(p).oper[1]^.typ = top_reg) then
  6942. begin
  6943. taicpu(p).opcode := A_TEST;
  6944. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6945. Result := True;
  6946. end;
  6947. Exit;
  6948. end
  6949. else if (taicpu(p).oper[1]^.typ = top_reg)
  6950. {$ifdef x86_64}
  6951. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6952. {$endif x86_64}
  6953. then
  6954. begin
  6955. { cmp register,$8000 neg register
  6956. je target --> jo target
  6957. .... only if register is deallocated before jump.}
  6958. case Taicpu(p).opsize of
  6959. S_B: v:=$80;
  6960. S_W: v:=$8000;
  6961. S_L: v:=qword($80000000);
  6962. else
  6963. internalerror(2013112905);
  6964. end;
  6965. if (taicpu(p).oper[0]^.val=v) and
  6966. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6967. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6968. begin
  6969. TransferUsedRegs(TmpUsedRegs);
  6970. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6971. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6972. begin
  6973. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6974. Taicpu(p).opcode:=A_NEG;
  6975. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6976. Taicpu(p).clearop(1);
  6977. Taicpu(p).ops:=1;
  6978. if Taicpu(hp1).condition=C_E then
  6979. Taicpu(hp1).condition:=C_O
  6980. else
  6981. Taicpu(hp1).condition:=C_NO;
  6982. Result:=true;
  6983. exit;
  6984. end;
  6985. end;
  6986. end;
  6987. end;
  6988. if TrySwapMovCmp(p, hp1) then
  6989. begin
  6990. Result := True;
  6991. Exit;
  6992. end;
  6993. end;
  6994. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6995. var
  6996. hp1: tai;
  6997. begin
  6998. {
  6999. remove the second (v)pxor from
  7000. pxor reg,reg
  7001. ...
  7002. pxor reg,reg
  7003. }
  7004. Result:=false;
  7005. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7006. MatchOpType(taicpu(p),top_reg,top_reg) and
  7007. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7008. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7009. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7010. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7011. begin
  7012. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7013. RemoveInstruction(hp1);
  7014. Result:=true;
  7015. Exit;
  7016. end
  7017. {
  7018. replace
  7019. pxor reg1,reg1
  7020. movapd/s reg1,reg2
  7021. dealloc reg1
  7022. by
  7023. pxor reg2,reg2
  7024. }
  7025. else if GetNextInstruction(p,hp1) and
  7026. { we mix single and double opperations here because we assume that the compiler
  7027. generates vmovapd only after double operations and vmovaps only after single operations }
  7028. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7029. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7030. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7031. (taicpu(p).oper[0]^.typ=top_reg) then
  7032. begin
  7033. TransferUsedRegs(TmpUsedRegs);
  7034. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7035. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7036. begin
  7037. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7038. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7039. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7040. RemoveInstruction(hp1);
  7041. result:=true;
  7042. end;
  7043. end;
  7044. end;
  7045. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7046. var
  7047. hp1: tai;
  7048. begin
  7049. {
  7050. remove the second (v)pxor from
  7051. (v)pxor reg,reg
  7052. ...
  7053. (v)pxor reg,reg
  7054. }
  7055. Result:=false;
  7056. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7057. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7058. begin
  7059. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7060. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7061. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7062. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7063. begin
  7064. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7065. RemoveInstruction(hp1);
  7066. Result:=true;
  7067. Exit;
  7068. end;
  7069. {$ifdef x86_64}
  7070. {
  7071. replace
  7072. vpxor reg1,reg1,reg1
  7073. vmov reg,mem
  7074. by
  7075. movq $0,mem
  7076. }
  7077. if GetNextInstruction(p,hp1) and
  7078. MatchInstruction(hp1,A_VMOVSD,[]) and
  7079. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7080. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7081. begin
  7082. TransferUsedRegs(TmpUsedRegs);
  7083. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7084. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7085. begin
  7086. taicpu(hp1).loadconst(0,0);
  7087. taicpu(hp1).opcode:=A_MOV;
  7088. taicpu(hp1).opsize:=S_Q;
  7089. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7090. RemoveCurrentP(p);
  7091. result:=true;
  7092. Exit;
  7093. end;
  7094. end;
  7095. {$endif x86_64}
  7096. end
  7097. {
  7098. replace
  7099. vpxor reg1,reg1,reg2
  7100. by
  7101. vpxor reg2,reg2,reg2
  7102. to avoid unncessary data dependencies
  7103. }
  7104. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7105. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7106. begin
  7107. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7108. { avoid unncessary data dependency }
  7109. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7110. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7111. result:=true;
  7112. exit;
  7113. end;
  7114. Result:=OptPass1VOP(p);
  7115. end;
  7116. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7117. var
  7118. hp1 : tai;
  7119. begin
  7120. result:=false;
  7121. { replace
  7122. IMul const,%mreg1,%mreg2
  7123. Mov %reg2,%mreg3
  7124. dealloc %mreg3
  7125. by
  7126. Imul const,%mreg1,%mreg23
  7127. }
  7128. if (taicpu(p).ops=3) and
  7129. GetNextInstruction(p,hp1) and
  7130. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7131. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7132. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7133. begin
  7134. TransferUsedRegs(TmpUsedRegs);
  7135. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7136. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7137. begin
  7138. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7139. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7140. RemoveInstruction(hp1);
  7141. result:=true;
  7142. end;
  7143. end;
  7144. end;
  7145. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7146. var
  7147. hp1 : tai;
  7148. begin
  7149. result:=false;
  7150. { replace
  7151. IMul %reg0,%reg1,%reg2
  7152. Mov %reg2,%reg3
  7153. dealloc %reg2
  7154. by
  7155. Imul %reg0,%reg1,%reg3
  7156. }
  7157. if GetNextInstruction(p,hp1) and
  7158. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7159. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7160. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7161. begin
  7162. TransferUsedRegs(TmpUsedRegs);
  7163. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7164. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7165. begin
  7166. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7167. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7168. RemoveInstruction(hp1);
  7169. result:=true;
  7170. end;
  7171. end;
  7172. end;
  7173. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7174. var
  7175. hp1: tai;
  7176. begin
  7177. Result:=false;
  7178. { get rid of
  7179. (v)cvtss2sd reg0,<reg1,>reg2
  7180. (v)cvtss2sd reg2,<reg2,>reg0
  7181. }
  7182. if GetNextInstruction(p,hp1) and
  7183. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7184. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7185. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7186. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7187. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7188. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7189. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7190. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7191. )
  7192. ) then
  7193. begin
  7194. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7195. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7196. begin
  7197. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7198. RemoveCurrentP(p);
  7199. RemoveInstruction(hp1);
  7200. end
  7201. else
  7202. begin
  7203. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7204. if taicpu(hp1).opcode=A_CVTSD2SS then
  7205. begin
  7206. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7207. taicpu(p).opcode:=A_MOVAPS;
  7208. end
  7209. else
  7210. begin
  7211. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7212. taicpu(p).opcode:=A_VMOVAPS;
  7213. end;
  7214. taicpu(p).ops:=2;
  7215. RemoveInstruction(hp1);
  7216. end;
  7217. Result:=true;
  7218. Exit;
  7219. end;
  7220. end;
  7221. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7222. var
  7223. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7224. ThisReg: TRegister;
  7225. begin
  7226. Result := False;
  7227. if not GetNextInstruction(p,hp1) then
  7228. Exit;
  7229. {
  7230. convert
  7231. j<c> .L1
  7232. mov 1,reg
  7233. jmp .L2
  7234. .L1
  7235. mov 0,reg
  7236. .L2
  7237. into
  7238. mov 0,reg
  7239. set<not(c)> reg
  7240. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7241. would destroy the flag contents
  7242. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7243. executed at the same time as a previous comparison.
  7244. set<not(c)> reg
  7245. movzx reg, reg
  7246. }
  7247. if MatchInstruction(hp1,A_MOV,[]) and
  7248. (taicpu(hp1).oper[0]^.typ = top_const) and
  7249. (
  7250. (
  7251. (taicpu(hp1).oper[1]^.typ = top_reg)
  7252. {$ifdef i386}
  7253. { Under i386, ESI, EDI, EBP and ESP
  7254. don't have an 8-bit representation }
  7255. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7256. {$endif i386}
  7257. ) or (
  7258. {$ifdef i386}
  7259. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7260. {$endif i386}
  7261. (taicpu(hp1).opsize = S_B)
  7262. )
  7263. ) and
  7264. GetNextInstruction(hp1,hp2) and
  7265. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7266. GetNextInstruction(hp2,hp3) and
  7267. SkipAligns(hp3, hp3) and
  7268. (hp3.typ=ait_label) and
  7269. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7270. GetNextInstruction(hp3,hp4) and
  7271. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7272. (taicpu(hp4).oper[0]^.typ = top_const) and
  7273. (
  7274. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7275. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7276. ) and
  7277. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7278. GetNextInstruction(hp4,hp5) and
  7279. SkipAligns(hp5, hp5) and
  7280. (hp5.typ=ait_label) and
  7281. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7282. begin
  7283. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7284. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7285. tai_label(hp3).labsym.DecRefs;
  7286. { If this isn't the only reference to the middle label, we can
  7287. still make a saving - only that the first jump and everything
  7288. that follows will remain. }
  7289. if (tai_label(hp3).labsym.getrefs = 0) then
  7290. begin
  7291. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7292. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7293. else
  7294. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7295. { remove jump, first label and second MOV (also catching any aligns) }
  7296. repeat
  7297. if not GetNextInstruction(hp2, hp3) then
  7298. InternalError(2021040810);
  7299. RemoveInstruction(hp2);
  7300. hp2 := hp3;
  7301. until hp2 = hp5;
  7302. { Don't decrement reference count before the removal loop
  7303. above, otherwise GetNextInstruction won't stop on the
  7304. the label }
  7305. tai_label(hp5).labsym.DecRefs;
  7306. end
  7307. else
  7308. begin
  7309. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7310. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7311. else
  7312. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7313. end;
  7314. taicpu(p).opcode:=A_SETcc;
  7315. taicpu(p).opsize:=S_B;
  7316. taicpu(p).is_jmp:=False;
  7317. if taicpu(hp1).opsize=S_B then
  7318. begin
  7319. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7320. if taicpu(hp1).oper[1]^.typ = top_reg then
  7321. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7322. RemoveInstruction(hp1);
  7323. end
  7324. else
  7325. begin
  7326. { Will be a register because the size can't be S_B otherwise }
  7327. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7328. taicpu(p).loadreg(0, ThisReg);
  7329. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7330. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7331. begin
  7332. case taicpu(hp1).opsize of
  7333. S_W:
  7334. taicpu(hp1).opsize := S_BW;
  7335. S_L:
  7336. taicpu(hp1).opsize := S_BL;
  7337. {$ifdef x86_64}
  7338. S_Q:
  7339. begin
  7340. taicpu(hp1).opsize := S_BL;
  7341. { Change the destination register to 32-bit }
  7342. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7343. end;
  7344. {$endif x86_64}
  7345. else
  7346. InternalError(2021040820);
  7347. end;
  7348. taicpu(hp1).opcode := A_MOVZX;
  7349. taicpu(hp1).loadreg(0, ThisReg);
  7350. end
  7351. else
  7352. begin
  7353. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7354. { hp1 is already a MOV instruction with the correct register }
  7355. taicpu(hp1).loadconst(0, 0);
  7356. { Inserting it right before p will guarantee that the flags are also tracked }
  7357. asml.Remove(hp1);
  7358. asml.InsertBefore(hp1, p);
  7359. end;
  7360. end;
  7361. Result:=true;
  7362. exit;
  7363. end
  7364. else if (hp1.typ = ait_label) then
  7365. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7366. end;
  7367. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7368. var
  7369. hp1, hp2, hp3: tai;
  7370. SourceRef, TargetRef: TReference;
  7371. CurrentReg: TRegister;
  7372. begin
  7373. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7374. if not UseAVX then
  7375. InternalError(2021100501);
  7376. Result := False;
  7377. { Look for the following to simplify:
  7378. vmovdqa/u x(mem1), %xmmreg
  7379. vmovdqa/u %xmmreg, y(mem2)
  7380. vmovdqa/u x+16(mem1), %xmmreg
  7381. vmovdqa/u %xmmreg, y+16(mem2)
  7382. Change to:
  7383. vmovdqa/u x(mem1), %ymmreg
  7384. vmovdqa/u %ymmreg, y(mem2)
  7385. vpxor %ymmreg, %ymmreg, %ymmreg
  7386. ( The VPXOR instruction is to zero the upper half, thus removing the
  7387. need to call the potentially expensive VZEROUPPER instruction. Other
  7388. peephole optimisations can remove VPXOR if it's unnecessary )
  7389. }
  7390. TransferUsedRegs(TmpUsedRegs);
  7391. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7392. { NOTE: In the optimisations below, if the references dictate that an
  7393. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7394. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7395. if (taicpu(p).opsize = S_XMM) and
  7396. MatchOpType(taicpu(p), top_ref, top_reg) and
  7397. GetNextInstruction(p, hp1) and
  7398. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7399. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7400. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7401. begin
  7402. SourceRef := taicpu(p).oper[0]^.ref^;
  7403. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7404. if GetNextInstruction(hp1, hp2) and
  7405. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7406. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7407. begin
  7408. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7409. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7410. Inc(SourceRef.offset, 16);
  7411. { Reuse the register in the first block move }
  7412. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7413. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7414. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7415. begin
  7416. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7417. Inc(TargetRef.offset, 16);
  7418. if GetNextInstruction(hp2, hp3) and
  7419. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7420. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7421. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7422. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7423. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7424. begin
  7425. { Update the register tracking to the new size }
  7426. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7427. { Remember that the offsets are 16 ahead }
  7428. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7429. if not (
  7430. ((SourceRef.offset mod 32) = 16) and
  7431. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7432. ) then
  7433. taicpu(p).opcode := A_VMOVDQU;
  7434. taicpu(p).opsize := S_YMM;
  7435. taicpu(p).oper[1]^.reg := CurrentReg;
  7436. if not (
  7437. ((TargetRef.offset mod 32) = 16) and
  7438. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7439. ) then
  7440. taicpu(hp1).opcode := A_VMOVDQU;
  7441. taicpu(hp1).opsize := S_YMM;
  7442. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7443. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7444. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7445. if (pi_uses_ymm in current_procinfo.flags) then
  7446. RemoveInstruction(hp2)
  7447. else
  7448. begin
  7449. taicpu(hp2).opcode := A_VPXOR;
  7450. taicpu(hp2).opsize := S_YMM;
  7451. taicpu(hp2).loadreg(0, CurrentReg);
  7452. taicpu(hp2).loadreg(1, CurrentReg);
  7453. taicpu(hp2).loadreg(2, CurrentReg);
  7454. taicpu(hp2).ops := 3;
  7455. end;
  7456. RemoveInstruction(hp3);
  7457. Result := True;
  7458. Exit;
  7459. end;
  7460. end
  7461. else
  7462. begin
  7463. { See if the next references are 16 less rather than 16 greater }
  7464. Dec(SourceRef.offset, 32); { -16 the other way }
  7465. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7466. begin
  7467. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7468. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7469. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7470. GetNextInstruction(hp2, hp3) and
  7471. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7472. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7473. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7474. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7475. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7476. begin
  7477. { Update the register tracking to the new size }
  7478. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7479. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7480. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7481. if not(
  7482. ((SourceRef.offset mod 32) = 0) and
  7483. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7484. ) then
  7485. taicpu(hp2).opcode := A_VMOVDQU;
  7486. taicpu(hp2).opsize := S_YMM;
  7487. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7488. if not (
  7489. ((TargetRef.offset mod 32) = 0) and
  7490. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7491. ) then
  7492. taicpu(hp3).opcode := A_VMOVDQU;
  7493. taicpu(hp3).opsize := S_YMM;
  7494. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7495. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7496. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7497. if (pi_uses_ymm in current_procinfo.flags) then
  7498. RemoveInstruction(hp1)
  7499. else
  7500. begin
  7501. taicpu(hp1).opcode := A_VPXOR;
  7502. taicpu(hp1).opsize := S_YMM;
  7503. taicpu(hp1).loadreg(0, CurrentReg);
  7504. taicpu(hp1).loadreg(1, CurrentReg);
  7505. taicpu(hp1).loadreg(2, CurrentReg);
  7506. taicpu(hp1).ops := 3;
  7507. Asml.Remove(hp1);
  7508. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7509. end;
  7510. RemoveCurrentP(p, hp2);
  7511. Result := True;
  7512. Exit;
  7513. end;
  7514. end;
  7515. end;
  7516. end;
  7517. end;
  7518. end;
  7519. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7520. var
  7521. hp2, hp3, first_assignment: tai;
  7522. IncCount, OperIdx: Integer;
  7523. OrigLabel: TAsmLabel;
  7524. begin
  7525. Count := 0;
  7526. Result := False;
  7527. first_assignment := nil;
  7528. if (LoopCount >= 20) then
  7529. begin
  7530. { Guard against infinite loops }
  7531. Exit;
  7532. end;
  7533. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7534. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7535. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7536. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7537. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7538. Exit;
  7539. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7540. {
  7541. change
  7542. jmp .L1
  7543. ...
  7544. .L1:
  7545. mov ##, ## ( multiple movs possible )
  7546. jmp/ret
  7547. into
  7548. mov ##, ##
  7549. jmp/ret
  7550. }
  7551. if not Assigned(hp1) then
  7552. begin
  7553. hp1 := GetLabelWithSym(OrigLabel);
  7554. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7555. Exit;
  7556. end;
  7557. hp2 := hp1;
  7558. while Assigned(hp2) do
  7559. begin
  7560. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7561. SkipLabels(hp2,hp2);
  7562. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7563. Break;
  7564. case taicpu(hp2).opcode of
  7565. A_MOVSS:
  7566. begin
  7567. if taicpu(hp2).ops = 0 then
  7568. { Wrong MOVSS }
  7569. Break;
  7570. Inc(Count);
  7571. if Count >= 5 then
  7572. { Too many to be worthwhile }
  7573. Break;
  7574. GetNextInstruction(hp2, hp2);
  7575. Continue;
  7576. end;
  7577. A_MOV,
  7578. A_MOVD,
  7579. A_MOVQ,
  7580. A_MOVSX,
  7581. {$ifdef x86_64}
  7582. A_MOVSXD,
  7583. {$endif x86_64}
  7584. A_MOVZX,
  7585. A_MOVAPS,
  7586. A_MOVUPS,
  7587. A_MOVSD,
  7588. A_MOVAPD,
  7589. A_MOVUPD,
  7590. A_MOVDQA,
  7591. A_MOVDQU,
  7592. A_VMOVSS,
  7593. A_VMOVAPS,
  7594. A_VMOVUPS,
  7595. A_VMOVSD,
  7596. A_VMOVAPD,
  7597. A_VMOVUPD,
  7598. A_VMOVDQA,
  7599. A_VMOVDQU:
  7600. begin
  7601. Inc(Count);
  7602. if Count >= 5 then
  7603. { Too many to be worthwhile }
  7604. Break;
  7605. GetNextInstruction(hp2, hp2);
  7606. Continue;
  7607. end;
  7608. A_JMP:
  7609. begin
  7610. { Guard against infinite loops }
  7611. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7612. Exit;
  7613. { Analyse this jump first in case it also duplicates assignments }
  7614. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7615. begin
  7616. { Something did change! }
  7617. Result := True;
  7618. Inc(Count, IncCount);
  7619. if Count >= 5 then
  7620. begin
  7621. { Too many to be worthwhile }
  7622. Exit;
  7623. end;
  7624. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7625. Break;
  7626. end;
  7627. Result := True;
  7628. Break;
  7629. end;
  7630. A_RET:
  7631. begin
  7632. Result := True;
  7633. Break;
  7634. end;
  7635. else
  7636. Break;
  7637. end;
  7638. end;
  7639. if Result then
  7640. begin
  7641. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7642. if Count = 0 then
  7643. begin
  7644. Result := False;
  7645. Exit;
  7646. end;
  7647. hp3 := p;
  7648. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7649. while True do
  7650. begin
  7651. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7652. SkipLabels(hp1,hp1);
  7653. if (hp1.typ <> ait_instruction) then
  7654. InternalError(2021040720);
  7655. case taicpu(hp1).opcode of
  7656. A_JMP:
  7657. begin
  7658. { Change the original jump to the new destination }
  7659. OrigLabel.decrefs;
  7660. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7661. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7662. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7663. if not Assigned(first_assignment) then
  7664. InternalError(2021040810)
  7665. else
  7666. p := first_assignment;
  7667. Exit;
  7668. end;
  7669. A_RET:
  7670. begin
  7671. { Now change the jump into a RET instruction }
  7672. ConvertJumpToRET(p, hp1);
  7673. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7674. if not Assigned(first_assignment) then
  7675. InternalError(2021040811)
  7676. else
  7677. p := first_assignment;
  7678. Exit;
  7679. end;
  7680. else
  7681. begin
  7682. { Duplicate the MOV instruction }
  7683. hp3:=tai(hp1.getcopy);
  7684. if first_assignment = nil then
  7685. first_assignment := hp3;
  7686. asml.InsertBefore(hp3, p);
  7687. { Make sure the compiler knows about any final registers written here }
  7688. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7689. with taicpu(hp3).oper[OperIdx]^ do
  7690. begin
  7691. case typ of
  7692. top_ref:
  7693. begin
  7694. if (ref^.base <> NR_NO) and
  7695. (getsupreg(ref^.base) <> RS_ESP) and
  7696. (getsupreg(ref^.base) <> RS_EBP)
  7697. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7698. then
  7699. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7700. if (ref^.index <> NR_NO) and
  7701. (getsupreg(ref^.index) <> RS_ESP) and
  7702. (getsupreg(ref^.index) <> RS_EBP)
  7703. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7704. (ref^.index <> ref^.base) then
  7705. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7706. end;
  7707. top_reg:
  7708. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7709. else
  7710. ;
  7711. end;
  7712. end;
  7713. end;
  7714. end;
  7715. if not GetNextInstruction(hp1, hp1) then
  7716. { Should have dropped out earlier }
  7717. InternalError(2021040710);
  7718. end;
  7719. end;
  7720. end;
  7721. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7722. var
  7723. hp2: tai;
  7724. X: Integer;
  7725. const
  7726. WriteOp: array[0..3] of set of TInsChange = (
  7727. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7728. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7729. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7730. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7731. RegWriteFlags: array[0..7] of set of TInsChange = (
  7732. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7733. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7734. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7735. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7736. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7737. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7738. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7739. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7740. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7741. begin
  7742. { If we have something like:
  7743. cmp ###,%reg1
  7744. mov 0,%reg2
  7745. And no modified registers are shared, move the instruction to before
  7746. the comparison as this means it can be optimised without worrying
  7747. about the FLAGS register. (CMP/MOV is generated by
  7748. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7749. As long as the second instruction doesn't use the flags or one of the
  7750. registers used by CMP or TEST (also check any references that use the
  7751. registers), then it can be moved prior to the comparison.
  7752. }
  7753. Result := False;
  7754. if (hp1.typ <> ait_instruction) or
  7755. taicpu(hp1).is_jmp or
  7756. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7757. Exit;
  7758. { NOP is a pipeline fence, likely marking the beginning of the function
  7759. epilogue, so drop out. Similarly, drop out if POP or RET are
  7760. encountered }
  7761. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7762. Exit;
  7763. if (taicpu(hp1).opcode = A_MOVSS) and
  7764. (taicpu(hp1).ops = 0) then
  7765. { Wrong MOVSS }
  7766. Exit;
  7767. { Check for writes to specific registers first }
  7768. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7769. for X := 0 to 7 do
  7770. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7771. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7772. Exit;
  7773. for X := 0 to taicpu(hp1).ops - 1 do
  7774. begin
  7775. { Check to see if this operand writes to something }
  7776. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7777. { And matches something in the CMP/TEST instruction }
  7778. (
  7779. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7780. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7781. (
  7782. { If it's a register, make sure the register written to doesn't
  7783. appear in the cmp instruction as part of a reference }
  7784. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7785. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7786. )
  7787. ) then
  7788. Exit;
  7789. end;
  7790. { The instruction can be safely moved }
  7791. asml.Remove(hp1);
  7792. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7793. can be optimised into "xor %reg,%reg" later }
  7794. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7795. asml.InsertBefore(hp1, hp2)
  7796. else
  7797. { Note, if p.Previous is nil (even if it should logically never be the
  7798. case), FindRegAllocBackward immediately exits with False and so we
  7799. safely land here (we can't just pass p because FindRegAllocBackward
  7800. immediately exits on an instruction). [Kit] }
  7801. asml.InsertBefore(hp1, p);
  7802. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7803. for X := 0 to taicpu(hp1).ops - 1 do
  7804. case taicpu(hp1).oper[X]^.typ of
  7805. top_reg:
  7806. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7807. top_ref:
  7808. begin
  7809. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7810. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7811. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7812. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7813. end;
  7814. else
  7815. ;
  7816. end;
  7817. if taicpu(hp1).opcode = A_LEA then
  7818. { The flags will be overwritten by the CMP/TEST instruction }
  7819. ConvertLEA(taicpu(hp1));
  7820. Result := True;
  7821. end;
  7822. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7823. function IsXCHGAcceptable: Boolean; inline;
  7824. begin
  7825. { Always accept if optimising for size }
  7826. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7827. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7828. than 3, so it becomes a saving compared to three MOVs with two of
  7829. them able to execute simultaneously. [Kit] }
  7830. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  7831. end;
  7832. var
  7833. NewRef: TReference;
  7834. hp1, hp2, hp3, hp4: Tai;
  7835. {$ifndef x86_64}
  7836. OperIdx: Integer;
  7837. {$endif x86_64}
  7838. NewInstr : Taicpu;
  7839. NewAligh : Tai_align;
  7840. DestLabel: TAsmLabel;
  7841. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7842. var
  7843. NextInstr: tai;
  7844. begin
  7845. Result := False;
  7846. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7847. if not GetNextInstruction(InputInstr, NextInstr) or
  7848. (
  7849. { The FLAGS register isn't always tracked properly, so do not
  7850. perform this optimisation if a conditional statement follows }
  7851. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7852. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7853. ) then
  7854. begin
  7855. reference_reset(NewRef, 1, []);
  7856. NewRef.base := taicpu(p).oper[0]^.reg;
  7857. NewRef.scalefactor := 1;
  7858. if taicpu(InputInstr).opcode = A_ADD then
  7859. begin
  7860. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7861. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7862. end
  7863. else
  7864. begin
  7865. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7866. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7867. end;
  7868. taicpu(p).opcode := A_LEA;
  7869. taicpu(p).loadref(0, NewRef);
  7870. RemoveInstruction(InputInstr);
  7871. Result := True;
  7872. end;
  7873. end;
  7874. begin
  7875. Result:=false;
  7876. { This optimisation adds an instruction, so only do it for speed }
  7877. if not (cs_opt_size in current_settings.optimizerswitches) and
  7878. MatchOpType(taicpu(p), top_const, top_reg) and
  7879. (taicpu(p).oper[0]^.val = 0) then
  7880. begin
  7881. { To avoid compiler warning }
  7882. DestLabel := nil;
  7883. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7884. InternalError(2021040750);
  7885. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7886. Exit;
  7887. case hp1.typ of
  7888. ait_align,
  7889. ait_label:
  7890. begin
  7891. { Change:
  7892. mov $0,%reg mov $0,%reg
  7893. @Lbl1: @Lbl1:
  7894. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7895. je @Lbl2 jne @Lbl2
  7896. To: To:
  7897. mov $0,%reg mov $0,%reg
  7898. jmp @Lbl2 jmp @Lbl3
  7899. (align) (align)
  7900. @Lbl1: @Lbl1:
  7901. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7902. je @Lbl2 je @Lbl2
  7903. @Lbl3: <-- Only if label exists
  7904. (Not if it's optimised for size)
  7905. }
  7906. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  7907. Exit;
  7908. if (hp2.typ = ait_instruction) and
  7909. (
  7910. { Register sizes must exactly match }
  7911. (
  7912. (taicpu(hp2).opcode = A_CMP) and
  7913. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7914. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7915. ) or (
  7916. (taicpu(hp2).opcode = A_TEST) and
  7917. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7918. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7919. )
  7920. ) and GetNextInstruction(hp2, hp3) and
  7921. (hp3.typ = ait_instruction) and
  7922. (taicpu(hp3).opcode = A_JCC) and
  7923. (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
  7924. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7925. begin
  7926. { Check condition of jump }
  7927. { Always true? }
  7928. if condition_in(C_E, taicpu(hp3).condition) then
  7929. begin
  7930. { Copy label symbol and obtain matching label entry for the
  7931. conditional jump, as this will be our destination}
  7932. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7933. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7934. Result := True;
  7935. end
  7936. { Always false? }
  7937. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7938. begin
  7939. { This is only worth it if there's a jump to take }
  7940. case hp2.typ of
  7941. ait_instruction:
  7942. begin
  7943. if taicpu(hp2).opcode = A_JMP then
  7944. begin
  7945. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7946. { An unconditional jump follows the conditional jump which will always be false,
  7947. so use this jump's destination for the new jump }
  7948. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7949. Result := True;
  7950. end
  7951. else if taicpu(hp2).opcode = A_JCC then
  7952. begin
  7953. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7954. if condition_in(C_E, taicpu(hp2).condition) then
  7955. begin
  7956. { A second conditional jump follows the conditional jump which will always be false,
  7957. while the second jump is always True, so use this jump's destination for the new jump }
  7958. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7959. Result := True;
  7960. end;
  7961. { Don't risk it if the jump isn't always true (Result remains False) }
  7962. end;
  7963. end;
  7964. else
  7965. { If anything else don't optimise };
  7966. end;
  7967. end;
  7968. if Result then
  7969. begin
  7970. { Just so we have something to insert as a paremeter}
  7971. reference_reset(NewRef, 1, []);
  7972. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7973. { Now actually load the correct parameter (this also
  7974. increases the reference count) }
  7975. NewInstr.loadsymbol(0, DestLabel, 0);
  7976. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7977. begin
  7978. { Get instruction before original label (may not be p under -O3) }
  7979. if not GetLastInstruction(hp1, hp2) then
  7980. { Shouldn't fail here }
  7981. InternalError(2021040701);
  7982. { Before the aligns too }
  7983. while (hp2.typ = ait_align) do
  7984. if not GetLastInstruction(hp2, hp2) then
  7985. { Shouldn't fail here }
  7986. InternalError(2021040702);
  7987. end
  7988. else
  7989. hp2 := p;
  7990. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  7991. AsmL.InsertAfter(NewInstr, hp2);
  7992. { Add new alignment field }
  7993. (* AsmL.InsertAfter(
  7994. cai_align.create_max(
  7995. current_settings.alignment.jumpalign,
  7996. current_settings.alignment.jumpalignskipmax
  7997. ),
  7998. NewInstr
  7999. ); *)
  8000. end;
  8001. Exit;
  8002. end;
  8003. end;
  8004. else
  8005. ;
  8006. end;
  8007. end;
  8008. if not GetNextInstruction(p, hp1) then
  8009. Exit;
  8010. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8011. and DoMovCmpMemOpt(p, hp1, True) then
  8012. begin
  8013. Result := True;
  8014. Exit;
  8015. end
  8016. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8017. begin
  8018. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8019. further, but we can't just put this jump optimisation in pass 1
  8020. because it tends to perform worse when conditional jumps are
  8021. nearby (e.g. when converting CMOV instructions). [Kit] }
  8022. if OptPass2JMP(hp1) then
  8023. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8024. Result := OptPass1MOV(p)
  8025. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8026. returned True and the instruction is still a MOV, thus checking
  8027. the optimisations below }
  8028. { If OptPass2JMP returned False, no optimisations were done to
  8029. the jump and there are no further optimisations that can be done
  8030. to the MOV instruction on this pass }
  8031. end
  8032. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8033. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8034. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8035. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8036. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8037. begin
  8038. { Change:
  8039. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8040. addl/q $x,%reg2 subl/q $x,%reg2
  8041. To:
  8042. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8043. }
  8044. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8045. { be lazy, checking separately for sub would be slightly better }
  8046. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8047. begin
  8048. TransferUsedRegs(TmpUsedRegs);
  8049. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8050. if TryMovArith2Lea(hp1) then
  8051. begin
  8052. Result := True;
  8053. Exit;
  8054. end
  8055. end
  8056. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8057. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8058. { Same as above, but also adds or subtracts to %reg2 in between.
  8059. It's still valid as long as the flags aren't in use }
  8060. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8061. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8062. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8063. { be lazy, checking separately for sub would be slightly better }
  8064. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8065. begin
  8066. TransferUsedRegs(TmpUsedRegs);
  8067. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8068. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8069. if TryMovArith2Lea(hp2) then
  8070. begin
  8071. Result := True;
  8072. Exit;
  8073. end;
  8074. end;
  8075. end
  8076. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8077. {$ifdef x86_64}
  8078. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8079. {$else x86_64}
  8080. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8081. {$endif x86_64}
  8082. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8083. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8084. { mov reg1, reg2 mov reg1, reg2
  8085. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8086. begin
  8087. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8088. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8089. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8090. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8091. TransferUsedRegs(TmpUsedRegs);
  8092. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8093. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8094. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8095. then
  8096. begin
  8097. RemoveCurrentP(p, hp1);
  8098. Result:=true;
  8099. end;
  8100. exit;
  8101. end
  8102. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8103. IsXCHGAcceptable and
  8104. { XCHG doesn't support 8-byte registers }
  8105. (taicpu(p).opsize <> S_B) and
  8106. MatchInstruction(hp1, A_MOV, []) and
  8107. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8108. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8109. GetNextInstruction(hp1, hp2) and
  8110. MatchInstruction(hp2, A_MOV, []) and
  8111. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8112. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8113. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8114. begin
  8115. { mov %reg1,%reg2
  8116. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8117. mov %reg2,%reg3
  8118. (%reg2 not used afterwards)
  8119. Note that xchg takes 3 cycles to execute, and generally mov's take
  8120. only one cycle apiece, but the first two mov's can be executed in
  8121. parallel, only taking 2 cycles overall. Older processors should
  8122. therefore only optimise for size. [Kit]
  8123. }
  8124. TransferUsedRegs(TmpUsedRegs);
  8125. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8126. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8127. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8128. begin
  8129. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8130. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8131. taicpu(hp1).opcode := A_XCHG;
  8132. RemoveCurrentP(p, hp1);
  8133. RemoveInstruction(hp2);
  8134. Result := True;
  8135. Exit;
  8136. end;
  8137. end
  8138. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8139. MatchInstruction(hp1, A_SAR, []) then
  8140. begin
  8141. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8142. begin
  8143. { the use of %edx also covers the opsize being S_L }
  8144. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8145. begin
  8146. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8147. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8148. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8149. begin
  8150. { Change:
  8151. movl %eax,%edx
  8152. sarl $31,%edx
  8153. To:
  8154. cltd
  8155. }
  8156. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8157. RemoveInstruction(hp1);
  8158. taicpu(p).opcode := A_CDQ;
  8159. taicpu(p).opsize := S_NO;
  8160. taicpu(p).clearop(1);
  8161. taicpu(p).clearop(0);
  8162. taicpu(p).ops:=0;
  8163. Result := True;
  8164. end
  8165. else if (cs_opt_size in current_settings.optimizerswitches) and
  8166. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8167. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8168. begin
  8169. { Change:
  8170. movl %edx,%eax
  8171. sarl $31,%edx
  8172. To:
  8173. movl %edx,%eax
  8174. cltd
  8175. Note that this creates a dependency between the two instructions,
  8176. so only perform if optimising for size.
  8177. }
  8178. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8179. taicpu(hp1).opcode := A_CDQ;
  8180. taicpu(hp1).opsize := S_NO;
  8181. taicpu(hp1).clearop(1);
  8182. taicpu(hp1).clearop(0);
  8183. taicpu(hp1).ops:=0;
  8184. end;
  8185. {$ifndef x86_64}
  8186. end
  8187. { Don't bother if CMOV is supported, because a more optimal
  8188. sequence would have been generated for the Abs() intrinsic }
  8189. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8190. { the use of %eax also covers the opsize being S_L }
  8191. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8192. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8193. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8194. GetNextInstruction(hp1, hp2) and
  8195. MatchInstruction(hp2, A_XOR, [S_L]) and
  8196. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8197. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8198. GetNextInstruction(hp2, hp3) and
  8199. MatchInstruction(hp3, A_SUB, [S_L]) and
  8200. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8201. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8202. begin
  8203. { Change:
  8204. movl %eax,%edx
  8205. sarl $31,%eax
  8206. xorl %eax,%edx
  8207. subl %eax,%edx
  8208. (Instruction that uses %edx)
  8209. (%eax deallocated)
  8210. (%edx deallocated)
  8211. To:
  8212. cltd
  8213. xorl %edx,%eax <-- Note the registers have swapped
  8214. subl %edx,%eax
  8215. (Instruction that uses %eax) <-- %eax rather than %edx
  8216. }
  8217. TransferUsedRegs(TmpUsedRegs);
  8218. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8219. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8220. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8221. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8222. begin
  8223. if GetNextInstruction(hp3, hp4) and
  8224. not RegModifiedByInstruction(NR_EDX, hp4) and
  8225. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8226. begin
  8227. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8228. taicpu(p).opcode := A_CDQ;
  8229. taicpu(p).clearop(1);
  8230. taicpu(p).clearop(0);
  8231. taicpu(p).ops:=0;
  8232. RemoveInstruction(hp1);
  8233. taicpu(hp2).loadreg(0, NR_EDX);
  8234. taicpu(hp2).loadreg(1, NR_EAX);
  8235. taicpu(hp3).loadreg(0, NR_EDX);
  8236. taicpu(hp3).loadreg(1, NR_EAX);
  8237. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8238. { Convert references in the following instruction (hp4) from %edx to %eax }
  8239. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8240. with taicpu(hp4).oper[OperIdx]^ do
  8241. case typ of
  8242. top_reg:
  8243. if getsupreg(reg) = RS_EDX then
  8244. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8245. top_ref:
  8246. begin
  8247. if getsupreg(reg) = RS_EDX then
  8248. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8249. if getsupreg(reg) = RS_EDX then
  8250. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8251. end;
  8252. else
  8253. ;
  8254. end;
  8255. end;
  8256. end;
  8257. {$else x86_64}
  8258. end;
  8259. end
  8260. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8261. { the use of %rdx also covers the opsize being S_Q }
  8262. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8263. begin
  8264. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8265. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8266. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8267. begin
  8268. { Change:
  8269. movq %rax,%rdx
  8270. sarq $63,%rdx
  8271. To:
  8272. cqto
  8273. }
  8274. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8275. RemoveInstruction(hp1);
  8276. taicpu(p).opcode := A_CQO;
  8277. taicpu(p).opsize := S_NO;
  8278. taicpu(p).clearop(1);
  8279. taicpu(p).clearop(0);
  8280. taicpu(p).ops:=0;
  8281. Result := True;
  8282. end
  8283. else if (cs_opt_size in current_settings.optimizerswitches) and
  8284. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8285. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8286. begin
  8287. { Change:
  8288. movq %rdx,%rax
  8289. sarq $63,%rdx
  8290. To:
  8291. movq %rdx,%rax
  8292. cqto
  8293. Note that this creates a dependency between the two instructions,
  8294. so only perform if optimising for size.
  8295. }
  8296. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8297. taicpu(hp1).opcode := A_CQO;
  8298. taicpu(hp1).opsize := S_NO;
  8299. taicpu(hp1).clearop(1);
  8300. taicpu(hp1).clearop(0);
  8301. taicpu(hp1).ops:=0;
  8302. {$endif x86_64}
  8303. end;
  8304. end;
  8305. end
  8306. else if MatchInstruction(hp1, A_MOV, []) and
  8307. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8308. { Though "GetNextInstruction" could be factored out, along with
  8309. the instructions that depend on hp2, it is an expensive call that
  8310. should be delayed for as long as possible, hence we do cheaper
  8311. checks first that are likely to be False. [Kit] }
  8312. begin
  8313. if (
  8314. (
  8315. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8316. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8317. (
  8318. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8319. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8320. )
  8321. ) or
  8322. (
  8323. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8324. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8325. (
  8326. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8327. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8328. )
  8329. )
  8330. ) and
  8331. GetNextInstruction(hp1, hp2) and
  8332. MatchInstruction(hp2, A_SAR, []) and
  8333. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8334. begin
  8335. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8336. begin
  8337. { Change:
  8338. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8339. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8340. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8341. To:
  8342. movl r/m,%eax <- Note the change in register
  8343. cltd
  8344. }
  8345. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8346. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8347. taicpu(p).loadreg(1, NR_EAX);
  8348. taicpu(hp1).opcode := A_CDQ;
  8349. taicpu(hp1).clearop(1);
  8350. taicpu(hp1).clearop(0);
  8351. taicpu(hp1).ops:=0;
  8352. RemoveInstruction(hp2);
  8353. (*
  8354. {$ifdef x86_64}
  8355. end
  8356. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8357. { This code sequence does not get generated - however it might become useful
  8358. if and when 128-bit signed integer types make an appearance, so the code
  8359. is kept here for when it is eventually needed. [Kit] }
  8360. (
  8361. (
  8362. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8363. (
  8364. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8365. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8366. )
  8367. ) or
  8368. (
  8369. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8370. (
  8371. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8372. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8373. )
  8374. )
  8375. ) and
  8376. GetNextInstruction(hp1, hp2) and
  8377. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8378. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8379. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8380. begin
  8381. { Change:
  8382. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8383. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8384. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8385. To:
  8386. movq r/m,%rax <- Note the change in register
  8387. cqto
  8388. }
  8389. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8390. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8391. taicpu(p).loadreg(1, NR_RAX);
  8392. taicpu(hp1).opcode := A_CQO;
  8393. taicpu(hp1).clearop(1);
  8394. taicpu(hp1).clearop(0);
  8395. taicpu(hp1).ops:=0;
  8396. RemoveInstruction(hp2);
  8397. {$endif x86_64}
  8398. *)
  8399. end;
  8400. end;
  8401. {$ifdef x86_64}
  8402. end
  8403. else if (taicpu(p).opsize = S_L) and
  8404. (taicpu(p).oper[1]^.typ = top_reg) and
  8405. (
  8406. MatchInstruction(hp1, A_MOV,[]) and
  8407. (taicpu(hp1).opsize = S_L) and
  8408. (taicpu(hp1).oper[1]^.typ = top_reg)
  8409. ) and (
  8410. GetNextInstruction(hp1, hp2) and
  8411. (tai(hp2).typ=ait_instruction) and
  8412. (taicpu(hp2).opsize = S_Q) and
  8413. (
  8414. (
  8415. MatchInstruction(hp2, A_ADD,[]) and
  8416. (taicpu(hp2).opsize = S_Q) and
  8417. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8418. (
  8419. (
  8420. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8421. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8422. ) or (
  8423. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8424. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8425. )
  8426. )
  8427. ) or (
  8428. MatchInstruction(hp2, A_LEA,[]) and
  8429. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8430. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8431. (
  8432. (
  8433. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8434. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8435. ) or (
  8436. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8437. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8438. )
  8439. ) and (
  8440. (
  8441. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8442. ) or (
  8443. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8444. )
  8445. )
  8446. )
  8447. )
  8448. ) and (
  8449. GetNextInstruction(hp2, hp3) and
  8450. MatchInstruction(hp3, A_SHR,[]) and
  8451. (taicpu(hp3).opsize = S_Q) and
  8452. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8453. (taicpu(hp3).oper[0]^.val = 1) and
  8454. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8455. ) then
  8456. begin
  8457. { Change movl x, reg1d movl x, reg1d
  8458. movl y, reg2d movl y, reg2d
  8459. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8460. shrq $1, reg1q shrq $1, reg1q
  8461. ( reg1d and reg2d can be switched around in the first two instructions )
  8462. To movl x, reg1d
  8463. addl y, reg1d
  8464. rcrl $1, reg1d
  8465. This corresponds to the common expression (x + y) shr 1, where
  8466. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8467. smaller code, but won't account for x + y causing an overflow). [Kit]
  8468. }
  8469. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8470. { Change first MOV command to have the same register as the final output }
  8471. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8472. else
  8473. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8474. { Change second MOV command to an ADD command. This is easier than
  8475. converting the existing command because it means we don't have to
  8476. touch 'y', which might be a complicated reference, and also the
  8477. fact that the third command might either be ADD or LEA. [Kit] }
  8478. taicpu(hp1).opcode := A_ADD;
  8479. { Delete old ADD/LEA instruction }
  8480. RemoveInstruction(hp2);
  8481. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8482. taicpu(hp3).opcode := A_RCR;
  8483. taicpu(hp3).changeopsize(S_L);
  8484. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8485. {$endif x86_64}
  8486. end;
  8487. if FuncMov2Func(p, hp1) then
  8488. begin
  8489. Result := True;
  8490. Exit;
  8491. end;
  8492. end;
  8493. {$push}
  8494. {$q-}{$r-}
  8495. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8496. var
  8497. ThisReg: TRegister;
  8498. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8499. TargetSubReg: TSubRegister;
  8500. hp1, hp2: tai;
  8501. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8502. { Store list of found instructions so we don't have to call
  8503. GetNextInstructionUsingReg multiple times }
  8504. InstrList: array of taicpu;
  8505. InstrMax, Index: Integer;
  8506. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8507. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8508. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8509. WorkingValue: TCgInt;
  8510. PreMessage: string;
  8511. { Data flow analysis }
  8512. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8513. BitwiseOnly, OrXorUsed,
  8514. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8515. function CheckOverflowConditions: Boolean;
  8516. begin
  8517. Result := True;
  8518. if (TestValSignedMax > SignedUpperLimit) then
  8519. UpperSignedOverflow := True;
  8520. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8521. LowerSignedOverflow := True;
  8522. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8523. LowerUnsignedOverflow := True;
  8524. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8525. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8526. begin
  8527. { Absolute overflow }
  8528. Result := False;
  8529. Exit;
  8530. end;
  8531. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8532. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8533. ShiftDownOverflow := True;
  8534. if (TestValMin < 0) or (TestValMax < 0) then
  8535. begin
  8536. LowerUnsignedOverflow := True;
  8537. UpperUnsignedOverflow := True;
  8538. end;
  8539. end;
  8540. function AdjustInitialLoadAndSize: Boolean;
  8541. begin
  8542. Result := False;
  8543. if not p_removed then
  8544. begin
  8545. if TargetSize = MinSize then
  8546. begin
  8547. { Convert the input MOVZX to a MOV }
  8548. if (taicpu(p).oper[0]^.typ = top_reg) and
  8549. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8550. begin
  8551. { Or remove it completely! }
  8552. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8553. RemoveCurrentP(p);
  8554. p_removed := True;
  8555. end
  8556. else
  8557. begin
  8558. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8559. taicpu(p).opcode := A_MOV;
  8560. taicpu(p).oper[1]^.reg := ThisReg;
  8561. taicpu(p).opsize := TargetSize;
  8562. end;
  8563. Result := True;
  8564. end
  8565. else if TargetSize <> MaxSize then
  8566. begin
  8567. case MaxSize of
  8568. S_L:
  8569. if TargetSize = S_W then
  8570. begin
  8571. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8572. taicpu(p).opsize := S_BW;
  8573. taicpu(p).oper[1]^.reg := ThisReg;
  8574. Result := True;
  8575. end
  8576. else
  8577. InternalError(2020112341);
  8578. S_W:
  8579. if TargetSize = S_L then
  8580. begin
  8581. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8582. taicpu(p).opsize := S_BL;
  8583. taicpu(p).oper[1]^.reg := ThisReg;
  8584. Result := True;
  8585. end
  8586. else
  8587. InternalError(2020112342);
  8588. else
  8589. ;
  8590. end;
  8591. end
  8592. else if not hp1_removed and not RegInUse then
  8593. begin
  8594. { If we have something like:
  8595. movzbl (oper),%regd
  8596. add x, %regd
  8597. movzbl %regb, %regd
  8598. We can reduce the register size to the input of the final
  8599. movzbl instruction. Overflows won't have any effect.
  8600. }
  8601. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8602. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8603. begin
  8604. TargetSize := S_B;
  8605. setsubreg(ThisReg, R_SUBL);
  8606. Result := True;
  8607. end
  8608. else if (taicpu(p).opsize = S_WL) and
  8609. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8610. begin
  8611. TargetSize := S_W;
  8612. setsubreg(ThisReg, R_SUBW);
  8613. Result := True;
  8614. end;
  8615. if Result then
  8616. begin
  8617. { Convert the input MOVZX to a MOV }
  8618. if (taicpu(p).oper[0]^.typ = top_reg) and
  8619. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8620. begin
  8621. { Or remove it completely! }
  8622. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8623. RemoveCurrentP(p);
  8624. p_removed := True;
  8625. end
  8626. else
  8627. begin
  8628. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8629. taicpu(p).opcode := A_MOV;
  8630. taicpu(p).oper[1]^.reg := ThisReg;
  8631. taicpu(p).opsize := TargetSize;
  8632. end;
  8633. end;
  8634. end;
  8635. end;
  8636. end;
  8637. procedure AdjustFinalLoad;
  8638. begin
  8639. if not LowerUnsignedOverflow then
  8640. begin
  8641. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8642. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8643. begin
  8644. { Convert the output MOVZX to a MOV }
  8645. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8646. begin
  8647. { Or remove it completely! }
  8648. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8649. { Be careful; if p = hp1 and p was also removed, p
  8650. will become a dangling pointer }
  8651. if p = hp1 then
  8652. begin
  8653. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8654. p_removed := True;
  8655. end
  8656. else
  8657. RemoveInstruction(hp1);
  8658. hp1_removed := True;
  8659. end
  8660. else
  8661. begin
  8662. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8663. taicpu(hp1).opcode := A_MOV;
  8664. taicpu(hp1).oper[0]^.reg := ThisReg;
  8665. taicpu(hp1).opsize := TargetSize;
  8666. end;
  8667. end
  8668. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8669. begin
  8670. { Need to change the size of the output }
  8671. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8672. taicpu(hp1).oper[0]^.reg := ThisReg;
  8673. taicpu(hp1).opsize := S_BL;
  8674. end;
  8675. end;
  8676. end;
  8677. function CompressInstructions: Boolean;
  8678. var
  8679. LocalIndex: Integer;
  8680. begin
  8681. Result := False;
  8682. { The objective here is to try to find a combination that
  8683. removes one of the MOV/Z instructions. }
  8684. if (
  8685. (taicpu(p).oper[0]^.typ <> top_reg) or
  8686. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8687. ) and
  8688. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8689. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8690. begin
  8691. { Make a preference to remove the second MOVZX instruction }
  8692. case taicpu(hp1).opsize of
  8693. S_BL, S_WL:
  8694. begin
  8695. TargetSize := S_L;
  8696. TargetSubReg := R_SUBD;
  8697. end;
  8698. S_BW:
  8699. begin
  8700. TargetSize := S_W;
  8701. TargetSubReg := R_SUBW;
  8702. end;
  8703. else
  8704. InternalError(2020112302);
  8705. end;
  8706. end
  8707. else
  8708. begin
  8709. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8710. begin
  8711. { Exceeded lower bound but not upper bound }
  8712. TargetSize := MaxSize;
  8713. end
  8714. else if not LowerUnsignedOverflow then
  8715. begin
  8716. { Size didn't exceed lower bound }
  8717. TargetSize := MinSize;
  8718. end
  8719. else
  8720. Exit;
  8721. end;
  8722. case TargetSize of
  8723. S_B:
  8724. TargetSubReg := R_SUBL;
  8725. S_W:
  8726. TargetSubReg := R_SUBW;
  8727. S_L:
  8728. TargetSubReg := R_SUBD;
  8729. else
  8730. InternalError(2020112350);
  8731. end;
  8732. { Update the register to its new size }
  8733. setsubreg(ThisReg, TargetSubReg);
  8734. RegInUse := False;
  8735. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8736. begin
  8737. { Check to see if the active register is used afterwards;
  8738. if not, we can change it and make a saving. }
  8739. TransferUsedRegs(TmpUsedRegs);
  8740. { The target register may be marked as in use to cross
  8741. a jump to a distant label, so exclude it }
  8742. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8743. hp2 := p;
  8744. repeat
  8745. { Explicitly check for the excluded register (don't include the first
  8746. instruction as it may be reading from here }
  8747. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8748. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8749. begin
  8750. RegInUse := True;
  8751. Break;
  8752. end;
  8753. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8754. if not GetNextInstruction(hp2, hp2) then
  8755. InternalError(2020112340);
  8756. until (hp2 = hp1);
  8757. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8758. { We might still be able to get away with this }
  8759. RegInUse := not
  8760. (
  8761. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8762. (hp2.typ = ait_instruction) and
  8763. (
  8764. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8765. instruction that doesn't actually contain ThisReg }
  8766. (cs_opt_level3 in current_settings.optimizerswitches) or
  8767. RegInInstruction(ThisReg, hp2)
  8768. ) and
  8769. RegLoadedWithNewValue(ThisReg, hp2)
  8770. );
  8771. if not RegInUse then
  8772. begin
  8773. { Force the register size to the same as this instruction so it can be removed}
  8774. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8775. begin
  8776. TargetSize := S_L;
  8777. TargetSubReg := R_SUBD;
  8778. end
  8779. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8780. begin
  8781. TargetSize := S_W;
  8782. TargetSubReg := R_SUBW;
  8783. end;
  8784. ThisReg := taicpu(hp1).oper[1]^.reg;
  8785. setsubreg(ThisReg, TargetSubReg);
  8786. RegChanged := True;
  8787. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8788. TransferUsedRegs(TmpUsedRegs);
  8789. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8790. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8791. if p = hp1 then
  8792. begin
  8793. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8794. p_removed := True;
  8795. end
  8796. else
  8797. RemoveInstruction(hp1);
  8798. hp1_removed := True;
  8799. { Instruction will become "mov %reg,%reg" }
  8800. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8801. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8802. begin
  8803. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8804. RemoveCurrentP(p);
  8805. p_removed := True;
  8806. end
  8807. else
  8808. taicpu(p).oper[1]^.reg := ThisReg;
  8809. Result := True;
  8810. end
  8811. else
  8812. begin
  8813. if TargetSize <> MaxSize then
  8814. begin
  8815. { Since the register is in use, we have to force it to
  8816. MaxSize otherwise part of it may become undefined later on }
  8817. TargetSize := MaxSize;
  8818. case TargetSize of
  8819. S_B:
  8820. TargetSubReg := R_SUBL;
  8821. S_W:
  8822. TargetSubReg := R_SUBW;
  8823. S_L:
  8824. TargetSubReg := R_SUBD;
  8825. else
  8826. InternalError(2020112351);
  8827. end;
  8828. setsubreg(ThisReg, TargetSubReg);
  8829. end;
  8830. AdjustFinalLoad;
  8831. end;
  8832. end
  8833. else
  8834. AdjustFinalLoad;
  8835. Result := AdjustInitialLoadAndSize or Result;
  8836. { Now go through every instruction we found and change the
  8837. size. If TargetSize = MaxSize, then almost no changes are
  8838. needed and Result can remain False if it hasn't been set
  8839. yet.
  8840. If RegChanged is True, then the register requires changing
  8841. and so the point about TargetSize = MaxSize doesn't apply. }
  8842. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8843. begin
  8844. for LocalIndex := 0 to InstrMax do
  8845. begin
  8846. { If p_removed is true, then the original MOV/Z was removed
  8847. and removing the AND instruction may not be safe if it
  8848. appears first }
  8849. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8850. InternalError(2020112310);
  8851. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8852. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8853. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8854. InstrList[LocalIndex].opsize := TargetSize;
  8855. end;
  8856. Result := True;
  8857. end;
  8858. end;
  8859. begin
  8860. Result := False;
  8861. p_removed := False;
  8862. hp1_removed := False;
  8863. ThisReg := taicpu(p).oper[1]^.reg;
  8864. { Check for:
  8865. movs/z ###,%ecx (or %cx or %rcx)
  8866. ...
  8867. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8868. (dealloc %ecx)
  8869. Change to:
  8870. mov ###,%cl (if ### = %cl, then remove completely)
  8871. ...
  8872. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8873. }
  8874. if (getsupreg(ThisReg) = RS_ECX) and
  8875. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8876. (hp1.typ = ait_instruction) and
  8877. (
  8878. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8879. instruction that doesn't actually contain ECX }
  8880. (cs_opt_level3 in current_settings.optimizerswitches) or
  8881. RegInInstruction(NR_ECX, hp1) or
  8882. (
  8883. { It's common for the shift/rotate's read/write register to be
  8884. initialised in between, so under -O2 and under, search ahead
  8885. one more instruction
  8886. }
  8887. GetNextInstruction(hp1, hp1) and
  8888. (hp1.typ = ait_instruction) and
  8889. RegInInstruction(NR_ECX, hp1)
  8890. )
  8891. ) and
  8892. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8893. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8894. begin
  8895. TransferUsedRegs(TmpUsedRegs);
  8896. hp2 := p;
  8897. repeat
  8898. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8899. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8900. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8901. begin
  8902. case taicpu(p).opsize of
  8903. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8904. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8905. begin
  8906. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8907. RemoveCurrentP(p);
  8908. end
  8909. else
  8910. begin
  8911. taicpu(p).opcode := A_MOV;
  8912. taicpu(p).opsize := S_B;
  8913. taicpu(p).oper[1]^.reg := NR_CL;
  8914. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8915. end;
  8916. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8917. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8918. begin
  8919. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8920. RemoveCurrentP(p);
  8921. end
  8922. else
  8923. begin
  8924. taicpu(p).opcode := A_MOV;
  8925. taicpu(p).opsize := S_W;
  8926. taicpu(p).oper[1]^.reg := NR_CX;
  8927. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8928. end;
  8929. {$ifdef x86_64}
  8930. S_LQ:
  8931. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8932. begin
  8933. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8934. RemoveCurrentP(p);
  8935. end
  8936. else
  8937. begin
  8938. taicpu(p).opcode := A_MOV;
  8939. taicpu(p).opsize := S_L;
  8940. taicpu(p).oper[1]^.reg := NR_ECX;
  8941. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8942. end;
  8943. {$endif x86_64}
  8944. else
  8945. InternalError(2021120401);
  8946. end;
  8947. Result := True;
  8948. Exit;
  8949. end;
  8950. end;
  8951. { This is anything but quick! }
  8952. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8953. Exit;
  8954. SetLength(InstrList, 0);
  8955. InstrMax := -1;
  8956. case taicpu(p).opsize of
  8957. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8958. begin
  8959. {$if defined(i386) or defined(i8086)}
  8960. { If the target size is 8-bit, make sure we can actually encode it }
  8961. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8962. Exit;
  8963. {$endif i386 or i8086}
  8964. LowerLimit := $FF;
  8965. SignedLowerLimit := $7F;
  8966. SignedLowerLimitBottom := -128;
  8967. MinSize := S_B;
  8968. if taicpu(p).opsize = S_BW then
  8969. begin
  8970. MaxSize := S_W;
  8971. UpperLimit := $FFFF;
  8972. SignedUpperLimit := $7FFF;
  8973. SignedUpperLimitBottom := -32768;
  8974. end
  8975. else
  8976. begin
  8977. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8978. MaxSize := S_L;
  8979. UpperLimit := $FFFFFFFF;
  8980. SignedUpperLimit := $7FFFFFFF;
  8981. SignedUpperLimitBottom := -2147483648;
  8982. end;
  8983. end;
  8984. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8985. begin
  8986. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8987. LowerLimit := $FFFF;
  8988. SignedLowerLimit := $7FFF;
  8989. SignedLowerLimitBottom := -32768;
  8990. UpperLimit := $FFFFFFFF;
  8991. SignedUpperLimit := $7FFFFFFF;
  8992. SignedUpperLimitBottom := -2147483648;
  8993. MinSize := S_W;
  8994. MaxSize := S_L;
  8995. end;
  8996. {$ifdef x86_64}
  8997. S_LQ:
  8998. begin
  8999. { Both the lower and upper limits are set to 32-bit. If a limit
  9000. is breached, then optimisation is impossible }
  9001. LowerLimit := $FFFFFFFF;
  9002. SignedLowerLimit := $7FFFFFFF;
  9003. SignedLowerLimitBottom := -2147483648;
  9004. UpperLimit := $FFFFFFFF;
  9005. SignedUpperLimit := $7FFFFFFF;
  9006. SignedUpperLimitBottom := -2147483648;
  9007. MinSize := S_L;
  9008. MaxSize := S_L;
  9009. end;
  9010. {$endif x86_64}
  9011. else
  9012. InternalError(2020112301);
  9013. end;
  9014. TestValMin := 0;
  9015. TestValMax := LowerLimit;
  9016. TestValSignedMax := SignedLowerLimit;
  9017. TryShiftDownLimit := LowerLimit;
  9018. TryShiftDown := S_NO;
  9019. ShiftDownOverflow := False;
  9020. RegChanged := False;
  9021. BitwiseOnly := True;
  9022. OrXorUsed := False;
  9023. UpperSignedOverflow := False;
  9024. LowerSignedOverflow := False;
  9025. UpperUnsignedOverflow := False;
  9026. LowerUnsignedOverflow := False;
  9027. hp1 := p;
  9028. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9029. (hp1.typ = ait_instruction) and
  9030. (
  9031. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9032. instruction that doesn't actually contain ThisReg }
  9033. (cs_opt_level3 in current_settings.optimizerswitches) or
  9034. { This allows this Movx optimisation to work through the SETcc instructions
  9035. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9036. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9037. skip over these SETcc instructions). }
  9038. (taicpu(hp1).opcode = A_SETcc) or
  9039. RegInInstruction(ThisReg, hp1)
  9040. ) do
  9041. begin
  9042. case taicpu(hp1).opcode of
  9043. A_INC,A_DEC:
  9044. begin
  9045. { Has to be an exact match on the register }
  9046. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9047. Break;
  9048. if taicpu(hp1).opcode = A_INC then
  9049. begin
  9050. Inc(TestValMin);
  9051. Inc(TestValMax);
  9052. Inc(TestValSignedMax);
  9053. end
  9054. else
  9055. begin
  9056. Dec(TestValMin);
  9057. Dec(TestValMax);
  9058. Dec(TestValSignedMax);
  9059. end;
  9060. end;
  9061. A_TEST, A_CMP:
  9062. begin
  9063. if (
  9064. { Too high a risk of non-linear behaviour that breaks DFA
  9065. here, unless it's cmp $0,%reg, which is equivalent to
  9066. test %reg,%reg }
  9067. OrXorUsed and
  9068. (taicpu(hp1).opcode = A_CMP) and
  9069. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9070. ) or
  9071. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9072. { Has to be an exact match on the register }
  9073. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9074. (
  9075. { Permit "test %reg,%reg" }
  9076. (taicpu(hp1).opcode = A_TEST) and
  9077. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9078. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9079. ) or
  9080. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9081. { Make sure the comparison value is not smaller than the
  9082. smallest allowed signed value for the minimum size (e.g.
  9083. -128 for 8-bit) }
  9084. not (
  9085. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9086. { Is it in the negative range? }
  9087. (
  9088. (taicpu(hp1).oper[0]^.val < 0) and
  9089. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9090. )
  9091. ) then
  9092. Break;
  9093. { Check to see if the active register is used afterwards }
  9094. TransferUsedRegs(TmpUsedRegs);
  9095. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9096. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9097. begin
  9098. { Make sure the comparison or any previous instructions
  9099. hasn't pushed the test values outside of the range of
  9100. MinSize }
  9101. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9102. begin
  9103. { Exceeded lower bound but not upper bound }
  9104. Exit;
  9105. end
  9106. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9107. begin
  9108. { Size didn't exceed lower bound }
  9109. TargetSize := MinSize;
  9110. end
  9111. else
  9112. Break;
  9113. case TargetSize of
  9114. S_B:
  9115. TargetSubReg := R_SUBL;
  9116. S_W:
  9117. TargetSubReg := R_SUBW;
  9118. S_L:
  9119. TargetSubReg := R_SUBD;
  9120. else
  9121. InternalError(2021051002);
  9122. end;
  9123. if TargetSize <> MaxSize then
  9124. begin
  9125. { Update the register to its new size }
  9126. setsubreg(ThisReg, TargetSubReg);
  9127. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9128. taicpu(hp1).oper[1]^.reg := ThisReg;
  9129. taicpu(hp1).opsize := TargetSize;
  9130. { Convert the input MOVZX to a MOV if necessary }
  9131. AdjustInitialLoadAndSize;
  9132. if (InstrMax >= 0) then
  9133. begin
  9134. for Index := 0 to InstrMax do
  9135. begin
  9136. { If p_removed is true, then the original MOV/Z was removed
  9137. and removing the AND instruction may not be safe if it
  9138. appears first }
  9139. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9140. InternalError(2020112311);
  9141. if InstrList[Index].oper[0]^.typ = top_reg then
  9142. InstrList[Index].oper[0]^.reg := ThisReg;
  9143. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9144. InstrList[Index].opsize := MinSize;
  9145. end;
  9146. end;
  9147. Result := True;
  9148. end;
  9149. Exit;
  9150. end;
  9151. end;
  9152. A_SETcc:
  9153. begin
  9154. { This allows this Movx optimisation to work through the SETcc instructions
  9155. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9156. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9157. skip over these SETcc instructions). }
  9158. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9159. { Of course, break out if the current register is used }
  9160. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9161. Break
  9162. else
  9163. { We must use Continue so the instruction doesn't get added
  9164. to InstrList }
  9165. Continue;
  9166. end;
  9167. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9168. begin
  9169. if
  9170. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9171. { Has to be an exact match on the register }
  9172. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9173. (
  9174. (
  9175. (taicpu(hp1).oper[0]^.typ = top_const) and
  9176. (
  9177. (
  9178. (taicpu(hp1).opcode = A_SHL) and
  9179. (
  9180. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9181. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9182. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9183. )
  9184. ) or (
  9185. (taicpu(hp1).opcode <> A_SHL) and
  9186. (
  9187. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9188. { Is it in the negative range? }
  9189. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9190. )
  9191. )
  9192. )
  9193. ) or (
  9194. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9195. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9196. )
  9197. ) then
  9198. Break;
  9199. { Only process OR and XOR if there are only bitwise operations,
  9200. since otherwise they can too easily fool the data flow
  9201. analysis (they can cause non-linear behaviour) }
  9202. case taicpu(hp1).opcode of
  9203. A_ADD:
  9204. begin
  9205. if OrXorUsed then
  9206. { Too high a risk of non-linear behaviour that breaks DFA here }
  9207. Break
  9208. else
  9209. BitwiseOnly := False;
  9210. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9211. begin
  9212. TestValMin := TestValMin * 2;
  9213. TestValMax := TestValMax * 2;
  9214. TestValSignedMax := TestValSignedMax * 2;
  9215. end
  9216. else
  9217. begin
  9218. WorkingValue := taicpu(hp1).oper[0]^.val;
  9219. TestValMin := TestValMin + WorkingValue;
  9220. TestValMax := TestValMax + WorkingValue;
  9221. TestValSignedMax := TestValSignedMax + WorkingValue;
  9222. end;
  9223. end;
  9224. A_SUB:
  9225. begin
  9226. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9227. begin
  9228. TestValMin := 0;
  9229. TestValMax := 0;
  9230. TestValSignedMax := 0;
  9231. end
  9232. else
  9233. begin
  9234. if OrXorUsed then
  9235. { Too high a risk of non-linear behaviour that breaks DFA here }
  9236. Break
  9237. else
  9238. BitwiseOnly := False;
  9239. WorkingValue := taicpu(hp1).oper[0]^.val;
  9240. TestValMin := TestValMin - WorkingValue;
  9241. TestValMax := TestValMax - WorkingValue;
  9242. TestValSignedMax := TestValSignedMax - WorkingValue;
  9243. end;
  9244. end;
  9245. A_AND:
  9246. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9247. begin
  9248. { we might be able to go smaller if AND appears first }
  9249. if InstrMax = -1 then
  9250. case MinSize of
  9251. S_B:
  9252. ;
  9253. S_W:
  9254. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9255. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9256. begin
  9257. TryShiftDown := S_B;
  9258. TryShiftDownLimit := $FF;
  9259. end;
  9260. S_L:
  9261. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9262. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9263. begin
  9264. TryShiftDown := S_B;
  9265. TryShiftDownLimit := $FF;
  9266. end
  9267. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9268. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9269. begin
  9270. TryShiftDown := S_W;
  9271. TryShiftDownLimit := $FFFF;
  9272. end;
  9273. else
  9274. InternalError(2020112320);
  9275. end;
  9276. WorkingValue := taicpu(hp1).oper[0]^.val;
  9277. TestValMin := TestValMin and WorkingValue;
  9278. TestValMax := TestValMax and WorkingValue;
  9279. TestValSignedMax := TestValSignedMax and WorkingValue;
  9280. end;
  9281. A_OR:
  9282. begin
  9283. if not BitwiseOnly then
  9284. Break;
  9285. OrXorUsed := True;
  9286. WorkingValue := taicpu(hp1).oper[0]^.val;
  9287. TestValMin := TestValMin or WorkingValue;
  9288. TestValMax := TestValMax or WorkingValue;
  9289. TestValSignedMax := TestValSignedMax or WorkingValue;
  9290. end;
  9291. A_XOR:
  9292. begin
  9293. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9294. begin
  9295. TestValMin := 0;
  9296. TestValMax := 0;
  9297. TestValSignedMax := 0;
  9298. end
  9299. else
  9300. begin
  9301. if not BitwiseOnly then
  9302. Break;
  9303. OrXorUsed := True;
  9304. WorkingValue := taicpu(hp1).oper[0]^.val;
  9305. TestValMin := TestValMin xor WorkingValue;
  9306. TestValMax := TestValMax xor WorkingValue;
  9307. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9308. end;
  9309. end;
  9310. A_SHL:
  9311. begin
  9312. BitwiseOnly := False;
  9313. WorkingValue := taicpu(hp1).oper[0]^.val;
  9314. TestValMin := TestValMin shl WorkingValue;
  9315. TestValMax := TestValMax shl WorkingValue;
  9316. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9317. end;
  9318. A_SHR,
  9319. { The first instruction was MOVZX, so the value won't be negative }
  9320. A_SAR:
  9321. begin
  9322. if InstrMax <> -1 then
  9323. BitwiseOnly := False
  9324. else
  9325. { we might be able to go smaller if SHR appears first }
  9326. case MinSize of
  9327. S_B:
  9328. ;
  9329. S_W:
  9330. if (taicpu(hp1).oper[0]^.val >= 8) then
  9331. begin
  9332. TryShiftDown := S_B;
  9333. TryShiftDownLimit := $FF;
  9334. TryShiftDownSignedLimit := $7F;
  9335. TryShiftDownSignedLimitLower := -128;
  9336. end;
  9337. S_L:
  9338. if (taicpu(hp1).oper[0]^.val >= 24) then
  9339. begin
  9340. TryShiftDown := S_B;
  9341. TryShiftDownLimit := $FF;
  9342. TryShiftDownSignedLimit := $7F;
  9343. TryShiftDownSignedLimitLower := -128;
  9344. end
  9345. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9346. begin
  9347. TryShiftDown := S_W;
  9348. TryShiftDownLimit := $FFFF;
  9349. TryShiftDownSignedLimit := $7FFF;
  9350. TryShiftDownSignedLimitLower := -32768;
  9351. end;
  9352. else
  9353. InternalError(2020112321);
  9354. end;
  9355. WorkingValue := taicpu(hp1).oper[0]^.val;
  9356. if taicpu(hp1).opcode = A_SAR then
  9357. begin
  9358. TestValMin := SarInt64(TestValMin, WorkingValue);
  9359. TestValMax := SarInt64(TestValMax, WorkingValue);
  9360. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9361. end
  9362. else
  9363. begin
  9364. TestValMin := TestValMin shr WorkingValue;
  9365. TestValMax := TestValMax shr WorkingValue;
  9366. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9367. end;
  9368. end;
  9369. else
  9370. InternalError(2020112303);
  9371. end;
  9372. end;
  9373. (*
  9374. A_IMUL:
  9375. case taicpu(hp1).ops of
  9376. 2:
  9377. begin
  9378. if not MatchOpType(hp1, top_reg, top_reg) or
  9379. { Has to be an exact match on the register }
  9380. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9381. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9382. Break;
  9383. TestValMin := TestValMin * TestValMin;
  9384. TestValMax := TestValMax * TestValMax;
  9385. TestValSignedMax := TestValSignedMax * TestValMax;
  9386. end;
  9387. 3:
  9388. begin
  9389. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9390. { Has to be an exact match on the register }
  9391. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9392. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9393. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9394. { Is it in the negative range? }
  9395. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9396. Break;
  9397. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9398. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9399. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9400. end;
  9401. else
  9402. Break;
  9403. end;
  9404. A_IDIV:
  9405. case taicpu(hp1).ops of
  9406. 3:
  9407. begin
  9408. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9409. { Has to be an exact match on the register }
  9410. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9411. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9412. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9413. { Is it in the negative range? }
  9414. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9415. Break;
  9416. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9417. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9418. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9419. end;
  9420. else
  9421. Break;
  9422. end;
  9423. *)
  9424. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9425. begin
  9426. { If there are no instructions in between, then we might be able to make a saving }
  9427. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9428. Break;
  9429. { We have something like:
  9430. movzbw %dl,%dx
  9431. ...
  9432. movswl %dx,%edx
  9433. Change the latter to a zero-extension then enter the
  9434. A_MOVZX case branch.
  9435. }
  9436. {$ifdef x86_64}
  9437. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9438. begin
  9439. { this becomes a zero extension from 32-bit to 64-bit, but
  9440. the upper 32 bits are already zero, so just delete the
  9441. instruction }
  9442. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9443. RemoveInstruction(hp1);
  9444. Result := True;
  9445. Exit;
  9446. end
  9447. else
  9448. {$endif x86_64}
  9449. begin
  9450. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9451. taicpu(hp1).opcode := A_MOVZX;
  9452. {$ifdef x86_64}
  9453. case taicpu(hp1).opsize of
  9454. S_BQ:
  9455. begin
  9456. taicpu(hp1).opsize := S_BL;
  9457. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9458. end;
  9459. S_WQ:
  9460. begin
  9461. taicpu(hp1).opsize := S_WL;
  9462. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9463. end;
  9464. S_LQ:
  9465. begin
  9466. taicpu(hp1).opcode := A_MOV;
  9467. taicpu(hp1).opsize := S_L;
  9468. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9469. { In this instance, we need to break out because the
  9470. instruction is no longer MOVZX or MOVSXD }
  9471. Result := True;
  9472. Exit;
  9473. end;
  9474. else
  9475. ;
  9476. end;
  9477. {$endif x86_64}
  9478. Result := CompressInstructions;
  9479. Exit;
  9480. end;
  9481. end;
  9482. A_MOVZX:
  9483. begin
  9484. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9485. Break;
  9486. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9487. begin
  9488. if (InstrMax = -1) and
  9489. { Will return false if the second parameter isn't ThisReg
  9490. (can happen on -O2 and under) }
  9491. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9492. begin
  9493. { The two MOVZX instructions are adjacent, so remove the first one }
  9494. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9495. RemoveCurrentP(p);
  9496. Result := True;
  9497. Exit;
  9498. end;
  9499. Break;
  9500. end;
  9501. Result := CompressInstructions;
  9502. Exit;
  9503. end;
  9504. else
  9505. { This includes ADC, SBB and IDIV }
  9506. Break;
  9507. end;
  9508. if not CheckOverflowConditions then
  9509. Break;
  9510. { Contains highest index (so instruction count - 1) }
  9511. Inc(InstrMax);
  9512. if InstrMax > High(InstrList) then
  9513. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9514. InstrList[InstrMax] := taicpu(hp1);
  9515. end;
  9516. end;
  9517. {$pop}
  9518. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9519. var
  9520. hp1 : tai;
  9521. begin
  9522. Result:=false;
  9523. if (taicpu(p).ops >= 2) and
  9524. ((taicpu(p).oper[0]^.typ = top_const) or
  9525. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9526. (taicpu(p).oper[1]^.typ = top_reg) and
  9527. ((taicpu(p).ops = 2) or
  9528. ((taicpu(p).oper[2]^.typ = top_reg) and
  9529. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9530. GetLastInstruction(p,hp1) and
  9531. MatchInstruction(hp1,A_MOV,[]) and
  9532. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9533. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9534. begin
  9535. TransferUsedRegs(TmpUsedRegs);
  9536. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9537. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9538. { change
  9539. mov reg1,reg2
  9540. imul y,reg2 to imul y,reg1,reg2 }
  9541. begin
  9542. taicpu(p).ops := 3;
  9543. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9544. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9545. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9546. RemoveInstruction(hp1);
  9547. result:=true;
  9548. end;
  9549. end;
  9550. end;
  9551. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9552. var
  9553. ThisLabel: TAsmLabel;
  9554. begin
  9555. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9556. ThisLabel.decrefs;
  9557. taicpu(p).condition := C_None;
  9558. taicpu(p).opcode := A_RET;
  9559. taicpu(p).is_jmp := false;
  9560. taicpu(p).ops := taicpu(ret_p).ops;
  9561. case taicpu(ret_p).ops of
  9562. 0:
  9563. taicpu(p).clearop(0);
  9564. 1:
  9565. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9566. else
  9567. internalerror(2016041301);
  9568. end;
  9569. { If the original label is now dead, it might turn out that the label
  9570. immediately follows p. As a result, everything beyond it, which will
  9571. be just some final register configuration and a RET instruction, is
  9572. now dead code. [Kit] }
  9573. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9574. running RemoveDeadCodeAfterJump for each RET instruction, because
  9575. this optimisation rarely happens and most RETs appear at the end of
  9576. routines where there is nothing that can be stripped. [Kit] }
  9577. if not ThisLabel.is_used then
  9578. RemoveDeadCodeAfterJump(p);
  9579. end;
  9580. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9581. var
  9582. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9583. Unconditional, PotentialModified: Boolean;
  9584. OperPtr: POper;
  9585. NewRef: TReference;
  9586. InstrList: array of taicpu;
  9587. InstrMax, Index: Integer;
  9588. const
  9589. {$ifdef DEBUG_AOPTCPU}
  9590. SNoFlags: shortstring = ' so the flags aren''t modified';
  9591. {$else DEBUG_AOPTCPU}
  9592. SNoFlags = '';
  9593. {$endif DEBUG_AOPTCPU}
  9594. begin
  9595. Result:=false;
  9596. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9597. begin
  9598. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9599. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9600. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9601. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9602. GetNextInstruction(hp1, hp2) and
  9603. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9604. { Change from: To:
  9605. set(C) %reg j(~C) label
  9606. test %reg,%reg/cmp $0,%reg
  9607. je label
  9608. set(C) %reg j(C) label
  9609. test %reg,%reg/cmp $0,%reg
  9610. jne label
  9611. (Also do something similar with sete/setne instead of je/jne)
  9612. }
  9613. begin
  9614. { Before we do anything else, we need to check the instructions
  9615. in between SETcc and TEST to make sure they don't modify the
  9616. FLAGS register - if -O2 or under, there won't be any
  9617. instructions between SET and TEST }
  9618. TransferUsedRegs(TmpUsedRegs);
  9619. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9620. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9621. begin
  9622. next := p;
  9623. SetLength(InstrList, 0);
  9624. InstrMax := -1;
  9625. PotentialModified := False;
  9626. { Make a note of every instruction that modifies the FLAGS
  9627. register }
  9628. while GetNextInstruction(next, next) and (next <> hp1) do
  9629. begin
  9630. if next.typ <> ait_instruction then
  9631. { GetNextInstructionUsingReg should have returned False }
  9632. InternalError(2021051701);
  9633. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9634. begin
  9635. case taicpu(next).opcode of
  9636. A_SETcc,
  9637. A_CMOVcc,
  9638. A_Jcc:
  9639. begin
  9640. if PotentialModified then
  9641. { Not safe because the flags were modified earlier }
  9642. Exit
  9643. else
  9644. { Condition is the same as the initial SETcc, so this is safe
  9645. (don't add to instruction list though) }
  9646. Continue;
  9647. end;
  9648. A_ADD:
  9649. begin
  9650. if (taicpu(next).opsize = S_B) or
  9651. { LEA doesn't support 8-bit operands }
  9652. (taicpu(next).oper[1]^.typ <> top_reg) or
  9653. { Must write to a register }
  9654. (taicpu(next).oper[0]^.typ = top_ref) then
  9655. { Require a constant or a register }
  9656. Exit;
  9657. PotentialModified := True;
  9658. end;
  9659. A_SUB:
  9660. begin
  9661. if (taicpu(next).opsize = S_B) or
  9662. { LEA doesn't support 8-bit operands }
  9663. (taicpu(next).oper[1]^.typ <> top_reg) or
  9664. { Must write to a register }
  9665. (taicpu(next).oper[0]^.typ <> top_const) or
  9666. (taicpu(next).oper[0]^.val = $80000000) then
  9667. { Can't subtract a register with LEA - also
  9668. check that the value isn't -2^31, as this
  9669. can't be negated }
  9670. Exit;
  9671. PotentialModified := True;
  9672. end;
  9673. A_SAL,
  9674. A_SHL:
  9675. begin
  9676. if (taicpu(next).opsize = S_B) or
  9677. { LEA doesn't support 8-bit operands }
  9678. (taicpu(next).oper[1]^.typ <> top_reg) or
  9679. { Must write to a register }
  9680. (taicpu(next).oper[0]^.typ <> top_const) or
  9681. (taicpu(next).oper[0]^.val < 0) or
  9682. (taicpu(next).oper[0]^.val > 3) then
  9683. Exit;
  9684. PotentialModified := True;
  9685. end;
  9686. A_IMUL:
  9687. begin
  9688. if (taicpu(next).ops <> 3) or
  9689. (taicpu(next).oper[1]^.typ <> top_reg) or
  9690. { Must write to a register }
  9691. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9692. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9693. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9694. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9695. Exit
  9696. else
  9697. PotentialModified := True;
  9698. end;
  9699. else
  9700. { Don't know how to change this, so abort }
  9701. Exit;
  9702. end;
  9703. { Contains highest index (so instruction count - 1) }
  9704. Inc(InstrMax);
  9705. if InstrMax > High(InstrList) then
  9706. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9707. InstrList[InstrMax] := taicpu(next);
  9708. end;
  9709. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9710. end;
  9711. if not Assigned(next) or (next <> hp1) then
  9712. { It should be equal to hp1 }
  9713. InternalError(2021051702);
  9714. { Cycle through each instruction and check to see if we can
  9715. change them to versions that don't modify the flags }
  9716. if (InstrMax >= 0) then
  9717. begin
  9718. for Index := 0 to InstrMax do
  9719. case InstrList[Index].opcode of
  9720. A_ADD:
  9721. begin
  9722. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9723. InstrList[Index].opcode := A_LEA;
  9724. reference_reset(NewRef, 1, []);
  9725. NewRef.base := InstrList[Index].oper[1]^.reg;
  9726. if InstrList[Index].oper[0]^.typ = top_reg then
  9727. begin
  9728. NewRef.index := InstrList[Index].oper[0]^.reg;
  9729. NewRef.scalefactor := 1;
  9730. end
  9731. else
  9732. NewRef.offset := InstrList[Index].oper[0]^.val;
  9733. InstrList[Index].loadref(0, NewRef);
  9734. end;
  9735. A_SUB:
  9736. begin
  9737. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9738. InstrList[Index].opcode := A_LEA;
  9739. reference_reset(NewRef, 1, []);
  9740. NewRef.base := InstrList[Index].oper[1]^.reg;
  9741. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9742. InstrList[Index].loadref(0, NewRef);
  9743. end;
  9744. A_SHL,
  9745. A_SAL:
  9746. begin
  9747. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9748. InstrList[Index].opcode := A_LEA;
  9749. reference_reset(NewRef, 1, []);
  9750. NewRef.index := InstrList[Index].oper[1]^.reg;
  9751. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9752. InstrList[Index].loadref(0, NewRef);
  9753. end;
  9754. A_IMUL:
  9755. begin
  9756. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9757. InstrList[Index].opcode := A_LEA;
  9758. reference_reset(NewRef, 1, []);
  9759. NewRef.index := InstrList[Index].oper[1]^.reg;
  9760. case InstrList[Index].oper[0]^.val of
  9761. 2, 4, 8:
  9762. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9763. else {3, 5 and 9}
  9764. begin
  9765. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9766. NewRef.base := InstrList[Index].oper[1]^.reg;
  9767. end;
  9768. end;
  9769. InstrList[Index].loadref(0, NewRef);
  9770. end;
  9771. else
  9772. InternalError(2021051710);
  9773. end;
  9774. end;
  9775. { Mark the FLAGS register as used across this whole block }
  9776. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9777. end;
  9778. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9779. JumpC := taicpu(hp2).condition;
  9780. Unconditional := False;
  9781. if conditions_equal(JumpC, C_E) then
  9782. SetC := inverse_cond(taicpu(p).condition)
  9783. else if conditions_equal(JumpC, C_NE) then
  9784. SetC := taicpu(p).condition
  9785. else
  9786. { We've got something weird here (and inefficent) }
  9787. begin
  9788. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9789. SetC := C_NONE;
  9790. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9791. if condition_in(C_AE, JumpC) then
  9792. Unconditional := True
  9793. else
  9794. { Not sure what to do with this jump - drop out }
  9795. Exit;
  9796. end;
  9797. RemoveInstruction(hp1);
  9798. if Unconditional then
  9799. MakeUnconditional(taicpu(hp2))
  9800. else
  9801. begin
  9802. if SetC = C_NONE then
  9803. InternalError(2018061402);
  9804. taicpu(hp2).SetCondition(SetC);
  9805. end;
  9806. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9807. TmpUsedRegs }
  9808. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9809. begin
  9810. RemoveCurrentp(p, hp2);
  9811. if taicpu(hp2).opcode = A_SETcc then
  9812. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9813. else
  9814. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9815. end
  9816. else
  9817. if taicpu(hp2).opcode = A_SETcc then
  9818. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9819. else
  9820. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9821. Result := True;
  9822. end
  9823. else if
  9824. { Make sure the instructions are adjacent }
  9825. (
  9826. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9827. GetNextInstruction(p, hp1)
  9828. ) and
  9829. MatchInstruction(hp1, A_MOV, [S_B]) and
  9830. { Writing to memory is allowed }
  9831. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9832. begin
  9833. {
  9834. Watch out for sequences such as:
  9835. set(c)b %regb
  9836. movb %regb,(ref)
  9837. movb $0,1(ref)
  9838. movb $0,2(ref)
  9839. movb $0,3(ref)
  9840. Much more efficient to turn it into:
  9841. movl $0,%regl
  9842. set(c)b %regb
  9843. movl %regl,(ref)
  9844. Or:
  9845. set(c)b %regb
  9846. movzbl %regb,%regl
  9847. movl %regl,(ref)
  9848. }
  9849. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9850. GetNextInstruction(hp1, hp2) and
  9851. MatchInstruction(hp2, A_MOV, [S_B]) and
  9852. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9853. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9854. begin
  9855. { Don't do anything else except set Result to True }
  9856. end
  9857. else
  9858. begin
  9859. if taicpu(p).oper[0]^.typ = top_reg then
  9860. begin
  9861. TransferUsedRegs(TmpUsedRegs);
  9862. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9863. end;
  9864. { If it's not a register, it's a memory address }
  9865. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9866. begin
  9867. { Even if the register is still in use, we can minimise the
  9868. pipeline stall by changing the MOV into another SETcc. }
  9869. taicpu(hp1).opcode := A_SETcc;
  9870. taicpu(hp1).condition := taicpu(p).condition;
  9871. if taicpu(hp1).oper[1]^.typ = top_ref then
  9872. begin
  9873. { Swapping the operand pointers like this is probably a
  9874. bit naughty, but it is far faster than using loadoper
  9875. to transfer the reference from oper[1] to oper[0] if
  9876. you take into account the extra procedure calls and
  9877. the memory allocation and deallocation required }
  9878. OperPtr := taicpu(hp1).oper[1];
  9879. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9880. taicpu(hp1).oper[0] := OperPtr;
  9881. end
  9882. else
  9883. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9884. taicpu(hp1).clearop(1);
  9885. taicpu(hp1).ops := 1;
  9886. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9887. end
  9888. else
  9889. begin
  9890. if taicpu(hp1).oper[1]^.typ = top_reg then
  9891. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9892. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9893. RemoveInstruction(hp1);
  9894. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9895. end
  9896. end;
  9897. Result := True;
  9898. end;
  9899. end;
  9900. end;
  9901. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9902. var
  9903. hp1: tai;
  9904. Count: Integer;
  9905. OrigLabel: TAsmLabel;
  9906. begin
  9907. result := False;
  9908. { Sometimes, the optimisations below can permit this }
  9909. RemoveDeadCodeAfterJump(p);
  9910. 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
  9911. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9912. begin
  9913. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9914. { Also a side-effect of optimisations }
  9915. if CollapseZeroDistJump(p, OrigLabel) then
  9916. begin
  9917. Result := True;
  9918. Exit;
  9919. end;
  9920. hp1 := GetLabelWithSym(OrigLabel);
  9921. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9922. begin
  9923. if taicpu(hp1).opcode = A_RET then
  9924. begin
  9925. {
  9926. change
  9927. jmp .L1
  9928. ...
  9929. .L1:
  9930. ret
  9931. into
  9932. ret
  9933. }
  9934. begin
  9935. ConvertJumpToRET(p, hp1);
  9936. result:=true;
  9937. end;
  9938. end
  9939. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9940. not (cs_opt_size in current_settings.optimizerswitches) and
  9941. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9942. begin
  9943. Result := True;
  9944. Exit;
  9945. end;
  9946. end;
  9947. end;
  9948. end;
  9949. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9950. begin
  9951. CanBeCMOV:=assigned(p) and
  9952. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9953. { we can't use cmov ref,reg because
  9954. ref could be nil and cmov still throws an exception
  9955. if ref=nil but the mov isn't done (FK)
  9956. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9957. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9958. }
  9959. (taicpu(p).oper[1]^.typ = top_reg) and
  9960. (
  9961. (taicpu(p).oper[0]^.typ = top_reg) or
  9962. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9963. it is not expected that this can cause a seg. violation }
  9964. (
  9965. (taicpu(p).oper[0]^.typ = top_ref) and
  9966. IsRefSafe(taicpu(p).oper[0]^.ref)
  9967. )
  9968. );
  9969. end;
  9970. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9971. var
  9972. hp1,hp2: tai;
  9973. {$ifndef i8086}
  9974. hp3,hp4,hpmov2, hp5: tai;
  9975. l : Longint;
  9976. condition : TAsmCond;
  9977. {$endif i8086}
  9978. carryadd_opcode : TAsmOp;
  9979. symbol: TAsmSymbol;
  9980. increg, tmpreg: TRegister;
  9981. begin
  9982. result:=false;
  9983. if GetNextInstruction(p,hp1) then
  9984. begin
  9985. if (hp1.typ=ait_label) then
  9986. begin
  9987. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9988. Exit;
  9989. end
  9990. else if (hp1.typ<>ait_instruction) then
  9991. Exit;
  9992. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9993. if (
  9994. (
  9995. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9996. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9997. (Taicpu(hp1).oper[0]^.val=1)
  9998. ) or
  9999. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10000. ) and
  10001. GetNextInstruction(hp1,hp2) and
  10002. SkipAligns(hp2, hp2) and
  10003. (hp2.typ = ait_label) and
  10004. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10005. { jb @@1 cmc
  10006. inc/dec operand --> adc/sbb operand,0
  10007. @@1:
  10008. ... and ...
  10009. jnb @@1
  10010. inc/dec operand --> adc/sbb operand,0
  10011. @@1: }
  10012. begin
  10013. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10014. begin
  10015. case taicpu(hp1).opcode of
  10016. A_INC,
  10017. A_ADD:
  10018. carryadd_opcode:=A_ADC;
  10019. A_DEC,
  10020. A_SUB:
  10021. carryadd_opcode:=A_SBB;
  10022. else
  10023. InternalError(2021011001);
  10024. end;
  10025. Taicpu(p).clearop(0);
  10026. Taicpu(p).ops:=0;
  10027. Taicpu(p).is_jmp:=false;
  10028. Taicpu(p).opcode:=A_CMC;
  10029. Taicpu(p).condition:=C_NONE;
  10030. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10031. Taicpu(hp1).ops:=2;
  10032. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10033. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10034. else
  10035. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10036. Taicpu(hp1).loadconst(0,0);
  10037. Taicpu(hp1).opcode:=carryadd_opcode;
  10038. result:=true;
  10039. exit;
  10040. end
  10041. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10042. begin
  10043. case taicpu(hp1).opcode of
  10044. A_INC,
  10045. A_ADD:
  10046. carryadd_opcode:=A_ADC;
  10047. A_DEC,
  10048. A_SUB:
  10049. carryadd_opcode:=A_SBB;
  10050. else
  10051. InternalError(2021011002);
  10052. end;
  10053. Taicpu(hp1).ops:=2;
  10054. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10055. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10056. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10057. else
  10058. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10059. Taicpu(hp1).loadconst(0,0);
  10060. Taicpu(hp1).opcode:=carryadd_opcode;
  10061. RemoveCurrentP(p, hp1);
  10062. result:=true;
  10063. exit;
  10064. end
  10065. {
  10066. jcc @@1 setcc tmpreg
  10067. inc/dec/add/sub operand -> (movzx tmpreg)
  10068. @@1: add/sub tmpreg,operand
  10069. While this increases code size slightly, it makes the code much faster if the
  10070. jump is unpredictable
  10071. }
  10072. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10073. begin
  10074. { search for an available register which is volatile }
  10075. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10076. if increg <> NR_NO then
  10077. begin
  10078. { We don't need to check if tmpreg is in hp1 or not, because
  10079. it will be marked as in use at p (if not, this is
  10080. indictive of a compiler bug). }
  10081. TAsmLabel(symbol).decrefs;
  10082. Taicpu(p).clearop(0);
  10083. Taicpu(p).ops:=1;
  10084. Taicpu(p).is_jmp:=false;
  10085. Taicpu(p).opcode:=A_SETcc;
  10086. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10087. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10088. Taicpu(p).loadreg(0,increg);
  10089. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10090. begin
  10091. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10092. R_SUBW:
  10093. begin
  10094. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10095. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10096. end;
  10097. R_SUBD:
  10098. begin
  10099. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10100. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10101. end;
  10102. {$ifdef x86_64}
  10103. R_SUBQ:
  10104. begin
  10105. { MOVZX doesn't have a 64-bit variant, because
  10106. the 32-bit version implicitly zeroes the
  10107. upper 32-bits of the destination register }
  10108. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10109. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10110. setsubreg(tmpreg, R_SUBQ);
  10111. end;
  10112. {$endif x86_64}
  10113. else
  10114. Internalerror(2020030601);
  10115. end;
  10116. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10117. asml.InsertAfter(hp2,p);
  10118. end
  10119. else
  10120. tmpreg := increg;
  10121. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10122. begin
  10123. Taicpu(hp1).ops:=2;
  10124. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10125. end;
  10126. Taicpu(hp1).loadreg(0,tmpreg);
  10127. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10128. Result := True;
  10129. { p is no longer a Jcc instruction, so exit }
  10130. Exit;
  10131. end;
  10132. end;
  10133. end;
  10134. { Detect the following:
  10135. jmp<cond> @Lbl1
  10136. jmp @Lbl2
  10137. ...
  10138. @Lbl1:
  10139. ret
  10140. Change to:
  10141. jmp<inv_cond> @Lbl2
  10142. ret
  10143. }
  10144. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10145. begin
  10146. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10147. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10148. MatchInstruction(hp2,A_RET,[S_NO]) then
  10149. begin
  10150. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10151. { Change label address to that of the unconditional jump }
  10152. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10153. TAsmLabel(symbol).DecRefs;
  10154. taicpu(hp1).opcode := A_RET;
  10155. taicpu(hp1).is_jmp := false;
  10156. taicpu(hp1).ops := taicpu(hp2).ops;
  10157. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10158. case taicpu(hp2).ops of
  10159. 0:
  10160. taicpu(hp1).clearop(0);
  10161. 1:
  10162. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10163. else
  10164. internalerror(2016041302);
  10165. end;
  10166. end;
  10167. {$ifndef i8086}
  10168. end
  10169. {
  10170. convert
  10171. j<c> .L1
  10172. mov 1,reg
  10173. jmp .L2
  10174. .L1
  10175. mov 0,reg
  10176. .L2
  10177. into
  10178. mov 0,reg
  10179. set<not(c)> reg
  10180. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10181. would destroy the flag contents
  10182. }
  10183. else if MatchInstruction(hp1,A_MOV,[]) and
  10184. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10185. {$ifdef i386}
  10186. (
  10187. { Under i386, ESI, EDI, EBP and ESP
  10188. don't have an 8-bit representation }
  10189. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10190. ) and
  10191. {$endif i386}
  10192. (taicpu(hp1).oper[0]^.val=1) and
  10193. GetNextInstruction(hp1,hp2) and
  10194. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10195. GetNextInstruction(hp2,hp3) and
  10196. { skip align }
  10197. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10198. (hp3.typ=ait_label) and
  10199. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10200. (tai_label(hp3).labsym.getrefs=1) and
  10201. GetNextInstruction(hp3,hp4) and
  10202. MatchInstruction(hp4,A_MOV,[]) and
  10203. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10204. (taicpu(hp4).oper[0]^.val=0) and
  10205. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10206. GetNextInstruction(hp4,hp5) and
  10207. (hp5.typ=ait_label) and
  10208. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10209. (tai_label(hp5).labsym.getrefs=1) then
  10210. begin
  10211. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10212. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10213. { remove last label }
  10214. RemoveInstruction(hp5);
  10215. { remove second label }
  10216. RemoveInstruction(hp3);
  10217. { if align is present remove it }
  10218. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10219. RemoveInstruction(hp3);
  10220. { remove jmp }
  10221. RemoveInstruction(hp2);
  10222. if taicpu(hp1).opsize=S_B then
  10223. RemoveInstruction(hp1)
  10224. else
  10225. taicpu(hp1).loadconst(0,0);
  10226. taicpu(hp4).opcode:=A_SETcc;
  10227. taicpu(hp4).opsize:=S_B;
  10228. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10229. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10230. taicpu(hp4).opercnt:=1;
  10231. taicpu(hp4).ops:=1;
  10232. taicpu(hp4).freeop(1);
  10233. RemoveCurrentP(p);
  10234. Result:=true;
  10235. exit;
  10236. end
  10237. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  10238. begin
  10239. { check for
  10240. jCC xxx
  10241. <several movs>
  10242. xxx:
  10243. Also spot:
  10244. Jcc xxx
  10245. <several movs>
  10246. jmp xxx
  10247. Change to:
  10248. <several cmovs with inverted condition>
  10249. jmp xxx
  10250. }
  10251. l:=0;
  10252. while assigned(hp1) and
  10253. CanBeCMOV(hp1) and
  10254. { stop on labels }
  10255. not(hp1.typ=ait_label) do
  10256. begin
  10257. inc(l);
  10258. hp5 := hp1;
  10259. GetNextInstruction(hp1,hp1);
  10260. end;
  10261. if assigned(hp1) then
  10262. begin
  10263. TransferUsedRegs(TmpUsedRegs);
  10264. if (
  10265. MatchInstruction(hp1, A_JMP, []) and
  10266. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  10267. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  10268. ) or
  10269. FindLabel(tasmlabel(symbol),hp1) then
  10270. begin
  10271. if (l<=4) and (l>0) then
  10272. begin
  10273. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10274. condition:=inverse_cond(taicpu(p).condition);
  10275. UpdateUsedRegs(tai(p.next));
  10276. GetNextInstruction(p,hp1);
  10277. repeat
  10278. if not Assigned(hp1) then
  10279. InternalError(2018062900);
  10280. taicpu(hp1).opcode:=A_CMOVcc;
  10281. taicpu(hp1).condition:=condition;
  10282. UpdateUsedRegs(tai(hp1.next));
  10283. GetNextInstruction(hp1,hp1);
  10284. until not(CanBeCMOV(hp1));
  10285. { Remember what hp1 is in case there's multiple aligns to get rid of }
  10286. hp2 := hp1;
  10287. repeat
  10288. if not Assigned(hp2) then
  10289. InternalError(2018062910);
  10290. case hp2.typ of
  10291. ait_label:
  10292. { What we expected - break out of the loop (it won't be a dead label at the top of
  10293. a cluster because that was optimised at an earlier stage) }
  10294. Break;
  10295. ait_align:
  10296. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10297. begin
  10298. hp2 := tai(hp2.Next);
  10299. Continue;
  10300. end;
  10301. ait_instruction:
  10302. begin
  10303. if taicpu(hp2).opcode<>A_JMP then
  10304. InternalError(2018062912);
  10305. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10306. Break;
  10307. end
  10308. else
  10309. begin
  10310. { Might be a comment or temporary allocation entry }
  10311. if not (hp2.typ in SkipInstr) then
  10312. InternalError(2018062911);
  10313. hp2 := tai(hp2.Next);
  10314. Continue;
  10315. end;
  10316. end;
  10317. until False;
  10318. { Now we can safely decrement the reference count }
  10319. tasmlabel(symbol).decrefs;
  10320. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10321. { Remove the original jump }
  10322. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10323. if hp2.typ=ait_instruction then
  10324. begin
  10325. p:=hp2;
  10326. Result:=True;
  10327. end
  10328. else
  10329. begin
  10330. UpdateUsedRegs(tai(hp2.next));
  10331. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  10332. { Remove the label if this is its final reference }
  10333. if (tasmlabel(symbol).getrefs=0) then
  10334. StripLabelFast(hp1);
  10335. end;
  10336. exit;
  10337. end;
  10338. end
  10339. else
  10340. begin
  10341. { check further for
  10342. jCC xxx
  10343. <several movs 1>
  10344. jmp yyy
  10345. xxx:
  10346. <several movs 2>
  10347. yyy:
  10348. }
  10349. { hp2 points to jmp yyy }
  10350. hp2:=hp1;
  10351. { skip hp1 to xxx (or an align right before it) }
  10352. GetNextInstruction(hp1, hp1);
  10353. if assigned(hp2) and
  10354. assigned(hp1) and
  10355. (l<=3) and
  10356. (hp2.typ=ait_instruction) and
  10357. (taicpu(hp2).is_jmp) and
  10358. (taicpu(hp2).condition=C_None) and
  10359. { real label and jump, no further references to the
  10360. label are allowed }
  10361. (tasmlabel(symbol).getrefs=1) and
  10362. FindLabel(tasmlabel(symbol),hp1) then
  10363. begin
  10364. l:=0;
  10365. { skip hp1 to <several moves 2> }
  10366. if (hp1.typ = ait_align) then
  10367. GetNextInstruction(hp1, hp1);
  10368. GetNextInstruction(hp1, hpmov2);
  10369. hp1 := hpmov2;
  10370. while assigned(hp1) and
  10371. CanBeCMOV(hp1) do
  10372. begin
  10373. inc(l);
  10374. hp5 := hp1;
  10375. GetNextInstruction(hp1, hp1);
  10376. end;
  10377. { hp1 points to yyy (or an align right before it) }
  10378. hp3 := hp1;
  10379. if assigned(hp1) and
  10380. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  10381. begin
  10382. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10383. condition:=inverse_cond(taicpu(p).condition);
  10384. UpdateUsedRegs(tai(p.next));
  10385. GetNextInstruction(p,hp1);
  10386. repeat
  10387. taicpu(hp1).opcode:=A_CMOVcc;
  10388. taicpu(hp1).condition:=condition;
  10389. UpdateUsedRegs(tai(hp1.next));
  10390. GetNextInstruction(hp1,hp1);
  10391. until not(assigned(hp1)) or
  10392. not(CanBeCMOV(hp1));
  10393. condition:=inverse_cond(condition);
  10394. if GetLastInstruction(hpmov2,hp1) then
  10395. UpdateUsedRegs(tai(hp1.next));
  10396. hp1 := hpmov2;
  10397. { hp1 is now at <several movs 2> }
  10398. while Assigned(hp1) and CanBeCMOV(hp1) do
  10399. begin
  10400. taicpu(hp1).opcode:=A_CMOVcc;
  10401. taicpu(hp1).condition:=condition;
  10402. UpdateUsedRegs(tai(hp1.next));
  10403. GetNextInstruction(hp1,hp1);
  10404. end;
  10405. hp1 := p;
  10406. { Get first instruction after label }
  10407. UpdateUsedRegs(tai(hp3.next));
  10408. GetNextInstruction(hp3, p);
  10409. if assigned(p) and (hp3.typ = ait_align) then
  10410. GetNextInstruction(p, p);
  10411. { Don't dereference yet, as doing so will cause
  10412. GetNextInstruction to skip the label and
  10413. optional align marker. [Kit] }
  10414. GetNextInstruction(hp2, hp4);
  10415. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10416. { remove jCC }
  10417. RemoveInstruction(hp1);
  10418. { Now we can safely decrement it }
  10419. tasmlabel(symbol).decrefs;
  10420. { Remove label xxx (it will have a ref of zero due to the initial check }
  10421. StripLabelFast(hp4);
  10422. { remove jmp }
  10423. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10424. RemoveInstruction(hp2);
  10425. { As before, now we can safely decrement it }
  10426. tasmlabel(symbol).decrefs;
  10427. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10428. if tasmlabel(symbol).getrefs = 0 then
  10429. StripLabelFast(hp3);
  10430. if Assigned(p) then
  10431. result:=true;
  10432. exit;
  10433. end;
  10434. end;
  10435. end;
  10436. end;
  10437. {$endif i8086}
  10438. end;
  10439. end;
  10440. end;
  10441. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10442. var
  10443. hp1,hp2,hp3: tai;
  10444. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10445. NewSize: TOpSize;
  10446. NewRegSize: TSubRegister;
  10447. Limit: TCgInt;
  10448. SwapOper: POper;
  10449. begin
  10450. result:=false;
  10451. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10452. GetNextInstruction(p,hp1) and
  10453. (hp1.typ = ait_instruction);
  10454. if reg_and_hp1_is_instr and
  10455. (
  10456. (taicpu(hp1).opcode <> A_LEA) or
  10457. { If the LEA instruction can be converted into an arithmetic instruction,
  10458. it may be possible to then fold it. }
  10459. (
  10460. { If the flags register is in use, don't change the instruction
  10461. to an ADD otherwise this will scramble the flags. [Kit] }
  10462. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10463. ConvertLEA(taicpu(hp1))
  10464. )
  10465. ) and
  10466. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10467. GetNextInstruction(hp1,hp2) and
  10468. MatchInstruction(hp2,A_MOV,[]) and
  10469. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10470. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10471. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10472. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10473. {$ifdef i386}
  10474. { not all registers have byte size sub registers on i386 }
  10475. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10476. {$endif i386}
  10477. (((taicpu(hp1).ops=2) and
  10478. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10479. ((taicpu(hp1).ops=1) and
  10480. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10481. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10482. begin
  10483. { change movsX/movzX reg/ref, reg2
  10484. add/sub/or/... reg3/$const, reg2
  10485. mov reg2 reg/ref
  10486. to add/sub/or/... reg3/$const, reg/ref }
  10487. { by example:
  10488. movswl %si,%eax movswl %si,%eax p
  10489. decl %eax addl %edx,%eax hp1
  10490. movw %ax,%si movw %ax,%si hp2
  10491. ->
  10492. movswl %si,%eax movswl %si,%eax p
  10493. decw %eax addw %edx,%eax hp1
  10494. movw %ax,%si movw %ax,%si hp2
  10495. }
  10496. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10497. {
  10498. ->
  10499. movswl %si,%eax movswl %si,%eax p
  10500. decw %si addw %dx,%si hp1
  10501. movw %ax,%si movw %ax,%si hp2
  10502. }
  10503. case taicpu(hp1).ops of
  10504. 1:
  10505. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10506. 2:
  10507. begin
  10508. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10509. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10510. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10511. end;
  10512. else
  10513. internalerror(2008042702);
  10514. end;
  10515. {
  10516. ->
  10517. decw %si addw %dx,%si p
  10518. }
  10519. DebugMsg(SPeepholeOptimization + 'var3',p);
  10520. RemoveCurrentP(p, hp1);
  10521. RemoveInstruction(hp2);
  10522. Result := True;
  10523. Exit;
  10524. end;
  10525. if reg_and_hp1_is_instr and
  10526. (taicpu(hp1).opcode = A_MOV) and
  10527. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10528. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10529. {$ifdef x86_64}
  10530. { check for implicit extension to 64 bit }
  10531. or
  10532. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10533. (taicpu(hp1).opsize=S_Q) and
  10534. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10535. )
  10536. {$endif x86_64}
  10537. )
  10538. then
  10539. begin
  10540. { change
  10541. movx %reg1,%reg2
  10542. mov %reg2,%reg3
  10543. dealloc %reg2
  10544. into
  10545. movx %reg,%reg3
  10546. }
  10547. TransferUsedRegs(TmpUsedRegs);
  10548. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10549. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10550. begin
  10551. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10552. {$ifdef x86_64}
  10553. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10554. (taicpu(hp1).opsize=S_Q) then
  10555. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10556. else
  10557. {$endif x86_64}
  10558. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10559. RemoveInstruction(hp1);
  10560. Result := True;
  10561. Exit;
  10562. end;
  10563. end;
  10564. if reg_and_hp1_is_instr and
  10565. ((taicpu(hp1).opcode=A_MOV) or
  10566. (taicpu(hp1).opcode=A_ADD) or
  10567. (taicpu(hp1).opcode=A_SUB) or
  10568. (taicpu(hp1).opcode=A_CMP) or
  10569. (taicpu(hp1).opcode=A_OR) or
  10570. (taicpu(hp1).opcode=A_XOR) or
  10571. (taicpu(hp1).opcode=A_AND)
  10572. ) and
  10573. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10574. begin
  10575. AndTest := (taicpu(hp1).opcode=A_AND) and
  10576. GetNextInstruction(hp1, hp2) and
  10577. (hp2.typ = ait_instruction) and
  10578. (
  10579. (
  10580. (taicpu(hp2).opcode=A_TEST) and
  10581. (
  10582. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10583. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10584. (
  10585. { If the AND and TEST instructions share a constant, this is also valid }
  10586. (taicpu(hp1).oper[0]^.typ = top_const) and
  10587. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10588. )
  10589. ) and
  10590. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10591. ) or
  10592. (
  10593. (taicpu(hp2).opcode=A_CMP) and
  10594. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10595. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10596. )
  10597. );
  10598. { change
  10599. movx (oper),%reg2
  10600. and $x,%reg2
  10601. test %reg2,%reg2
  10602. dealloc %reg2
  10603. into
  10604. op %reg1,%reg3
  10605. if the second op accesses only the bits stored in reg1
  10606. }
  10607. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10608. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10609. (taicpu(hp1).oper[0]^.typ = top_const) and
  10610. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10611. AndTest then
  10612. begin
  10613. { Check if the AND constant is in range }
  10614. case taicpu(p).opsize of
  10615. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10616. begin
  10617. NewSize := S_B;
  10618. Limit := $FF;
  10619. end;
  10620. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10621. begin
  10622. NewSize := S_W;
  10623. Limit := $FFFF;
  10624. end;
  10625. {$ifdef x86_64}
  10626. S_LQ:
  10627. begin
  10628. NewSize := S_L;
  10629. Limit := $FFFFFFFF;
  10630. end;
  10631. {$endif x86_64}
  10632. else
  10633. InternalError(2021120303);
  10634. end;
  10635. if (
  10636. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10637. { Check for negative operands }
  10638. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10639. ) and
  10640. GetNextInstruction(hp2,hp3) and
  10641. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10642. (taicpu(hp3).condition in [C_E,C_NE]) then
  10643. begin
  10644. TransferUsedRegs(TmpUsedRegs);
  10645. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10646. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10647. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10648. begin
  10649. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10650. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10651. taicpu(hp1).opcode := A_TEST;
  10652. taicpu(hp1).opsize := NewSize;
  10653. RemoveInstruction(hp2);
  10654. RemoveCurrentP(p, hp1);
  10655. Result:=true;
  10656. exit;
  10657. end;
  10658. end;
  10659. end;
  10660. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10661. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10662. (taicpu(hp1).opsize=S_B)) or
  10663. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10664. (taicpu(hp1).opsize=S_W))
  10665. {$ifdef x86_64}
  10666. or ((taicpu(p).opsize=S_LQ) and
  10667. (taicpu(hp1).opsize=S_L))
  10668. {$endif x86_64}
  10669. ) and
  10670. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10671. begin
  10672. { change
  10673. movx %reg1,%reg2
  10674. op %reg2,%reg3
  10675. dealloc %reg2
  10676. into
  10677. op %reg1,%reg3
  10678. if the second op accesses only the bits stored in reg1
  10679. }
  10680. TransferUsedRegs(TmpUsedRegs);
  10681. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10682. if AndTest then
  10683. begin
  10684. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10685. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10686. end
  10687. else
  10688. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10689. if not RegUsed then
  10690. begin
  10691. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10692. if taicpu(p).oper[0]^.typ=top_reg then
  10693. begin
  10694. case taicpu(hp1).opsize of
  10695. S_B:
  10696. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10697. S_W:
  10698. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10699. S_L:
  10700. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10701. else
  10702. Internalerror(2020102301);
  10703. end;
  10704. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10705. end
  10706. else
  10707. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10708. RemoveCurrentP(p);
  10709. if AndTest then
  10710. RemoveInstruction(hp2);
  10711. result:=true;
  10712. exit;
  10713. end;
  10714. end
  10715. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10716. (
  10717. { Bitwise operations only }
  10718. (taicpu(hp1).opcode=A_AND) or
  10719. (taicpu(hp1).opcode=A_TEST) or
  10720. (
  10721. (taicpu(hp1).oper[0]^.typ = top_const) and
  10722. (
  10723. (taicpu(hp1).opcode=A_OR) or
  10724. (taicpu(hp1).opcode=A_XOR)
  10725. )
  10726. )
  10727. ) and
  10728. (
  10729. (taicpu(hp1).oper[0]^.typ = top_const) or
  10730. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10731. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10732. ) then
  10733. begin
  10734. { change
  10735. movx %reg2,%reg2
  10736. op const,%reg2
  10737. into
  10738. op const,%reg2 (smaller version)
  10739. movx %reg2,%reg2
  10740. also change
  10741. movx %reg1,%reg2
  10742. and/test (oper),%reg2
  10743. dealloc %reg2
  10744. into
  10745. and/test (oper),%reg1
  10746. }
  10747. case taicpu(p).opsize of
  10748. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10749. begin
  10750. NewSize := S_B;
  10751. NewRegSize := R_SUBL;
  10752. Limit := $FF;
  10753. end;
  10754. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10755. begin
  10756. NewSize := S_W;
  10757. NewRegSize := R_SUBW;
  10758. Limit := $FFFF;
  10759. end;
  10760. {$ifdef x86_64}
  10761. S_LQ:
  10762. begin
  10763. NewSize := S_L;
  10764. NewRegSize := R_SUBD;
  10765. Limit := $FFFFFFFF;
  10766. end;
  10767. {$endif x86_64}
  10768. else
  10769. Internalerror(2021120302);
  10770. end;
  10771. TransferUsedRegs(TmpUsedRegs);
  10772. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10773. if AndTest then
  10774. begin
  10775. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10776. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10777. end
  10778. else
  10779. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10780. if
  10781. (
  10782. (taicpu(p).opcode = A_MOVZX) and
  10783. (
  10784. (taicpu(hp1).opcode=A_AND) or
  10785. (taicpu(hp1).opcode=A_TEST)
  10786. ) and
  10787. not (
  10788. { If both are references, then the final instruction will have
  10789. both operands as references, which is not allowed }
  10790. (taicpu(p).oper[0]^.typ = top_ref) and
  10791. (taicpu(hp1).oper[0]^.typ = top_ref)
  10792. ) and
  10793. not RegUsed
  10794. ) or
  10795. (
  10796. (
  10797. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10798. not RegUsed
  10799. ) and
  10800. (taicpu(p).oper[0]^.typ = top_reg) and
  10801. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10802. (taicpu(hp1).oper[0]^.typ = top_const) and
  10803. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10804. ) then
  10805. begin
  10806. {$if defined(i386) or defined(i8086)}
  10807. { If the target size is 8-bit, make sure we can actually encode it }
  10808. 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
  10809. Exit;
  10810. {$endif i386 or i8086}
  10811. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10812. taicpu(hp1).opsize := NewSize;
  10813. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10814. if AndTest then
  10815. begin
  10816. RemoveInstruction(hp2);
  10817. if not RegUsed then
  10818. begin
  10819. taicpu(hp1).opcode := A_TEST;
  10820. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10821. begin
  10822. { Make sure the reference is the second operand }
  10823. SwapOper := taicpu(hp1).oper[0];
  10824. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10825. taicpu(hp1).oper[1] := SwapOper;
  10826. end;
  10827. end;
  10828. end;
  10829. case taicpu(hp1).oper[0]^.typ of
  10830. top_reg:
  10831. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10832. top_const:
  10833. { For the AND/TEST case }
  10834. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10835. else
  10836. ;
  10837. end;
  10838. if RegUsed then
  10839. begin
  10840. AsmL.Remove(p);
  10841. AsmL.InsertAfter(p, hp1);
  10842. p := hp1;
  10843. end
  10844. else
  10845. RemoveCurrentP(p, hp1);
  10846. result:=true;
  10847. exit;
  10848. end;
  10849. end;
  10850. end;
  10851. if reg_and_hp1_is_instr and
  10852. (taicpu(p).oper[0]^.typ = top_reg) and
  10853. (
  10854. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10855. ) and
  10856. (taicpu(hp1).oper[0]^.typ = top_const) and
  10857. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10858. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10859. { Minimum shift value allowed is the bit difference between the sizes }
  10860. (taicpu(hp1).oper[0]^.val >=
  10861. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10862. 8 * (
  10863. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10864. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10865. )
  10866. ) then
  10867. begin
  10868. { For:
  10869. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10870. shl/sal ##, %reg1
  10871. Remove the movsx/movzx instruction if the shift overwrites the
  10872. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10873. }
  10874. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10875. RemoveCurrentP(p, hp1);
  10876. Result := True;
  10877. Exit;
  10878. end
  10879. else if reg_and_hp1_is_instr and
  10880. (taicpu(p).oper[0]^.typ = top_reg) and
  10881. (
  10882. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10883. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10884. ) and
  10885. (taicpu(hp1).oper[0]^.typ = top_const) and
  10886. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10887. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10888. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10889. (taicpu(hp1).oper[0]^.val <
  10890. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10891. 8 * (
  10892. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10893. )
  10894. ) then
  10895. begin
  10896. { For:
  10897. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10898. sar ##, %reg1 shr ##, %reg1
  10899. Move the shift to before the movx instruction if the shift value
  10900. is not too large.
  10901. }
  10902. asml.Remove(hp1);
  10903. asml.InsertBefore(hp1, p);
  10904. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10905. case taicpu(p).opsize of
  10906. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10907. taicpu(hp1).opsize := S_B;
  10908. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10909. taicpu(hp1).opsize := S_W;
  10910. {$ifdef x86_64}
  10911. S_LQ:
  10912. taicpu(hp1).opsize := S_L;
  10913. {$endif}
  10914. else
  10915. InternalError(2020112401);
  10916. end;
  10917. if (taicpu(hp1).opcode = A_SHR) then
  10918. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10919. else
  10920. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10921. Result := True;
  10922. end;
  10923. if reg_and_hp1_is_instr and
  10924. (taicpu(p).oper[0]^.typ = top_reg) and
  10925. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10926. (
  10927. (taicpu(hp1).opcode = taicpu(p).opcode)
  10928. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10929. {$ifdef x86_64}
  10930. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10931. {$endif x86_64}
  10932. ) then
  10933. begin
  10934. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10935. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10936. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10937. begin
  10938. {
  10939. For example:
  10940. movzbw %al,%ax
  10941. movzwl %ax,%eax
  10942. Compress into:
  10943. movzbl %al,%eax
  10944. }
  10945. RegUsed := False;
  10946. case taicpu(p).opsize of
  10947. S_BW:
  10948. case taicpu(hp1).opsize of
  10949. S_WL:
  10950. begin
  10951. taicpu(p).opsize := S_BL;
  10952. RegUsed := True;
  10953. end;
  10954. {$ifdef x86_64}
  10955. S_WQ:
  10956. begin
  10957. if taicpu(p).opcode = A_MOVZX then
  10958. begin
  10959. taicpu(p).opsize := S_BL;
  10960. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10961. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10962. end
  10963. else
  10964. taicpu(p).opsize := S_BQ;
  10965. RegUsed := True;
  10966. end;
  10967. {$endif x86_64}
  10968. else
  10969. ;
  10970. end;
  10971. {$ifdef x86_64}
  10972. S_BL:
  10973. case taicpu(hp1).opsize of
  10974. S_LQ:
  10975. begin
  10976. if taicpu(p).opcode = A_MOVZX then
  10977. begin
  10978. taicpu(p).opsize := S_BL;
  10979. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10980. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10981. end
  10982. else
  10983. taicpu(p).opsize := S_BQ;
  10984. RegUsed := True;
  10985. end;
  10986. else
  10987. ;
  10988. end;
  10989. S_WL:
  10990. case taicpu(hp1).opsize of
  10991. S_LQ:
  10992. begin
  10993. if taicpu(p).opcode = A_MOVZX then
  10994. begin
  10995. taicpu(p).opsize := S_WL;
  10996. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10997. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10998. end
  10999. else
  11000. taicpu(p).opsize := S_WQ;
  11001. RegUsed := True;
  11002. end;
  11003. else
  11004. ;
  11005. end;
  11006. {$endif x86_64}
  11007. else
  11008. ;
  11009. end;
  11010. if RegUsed then
  11011. begin
  11012. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11013. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11014. RemoveInstruction(hp1);
  11015. Result := True;
  11016. Exit;
  11017. end;
  11018. end;
  11019. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11020. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11021. GetNextInstruction(hp1, hp2) and
  11022. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11023. (
  11024. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11025. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11026. {$ifdef x86_64}
  11027. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11028. {$endif x86_64}
  11029. ) and
  11030. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11031. (
  11032. (
  11033. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11034. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11035. ) or
  11036. (
  11037. { Only allow the operands in reverse order for TEST instructions }
  11038. (taicpu(hp2).opcode = A_TEST) and
  11039. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11040. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11041. )
  11042. ) then
  11043. begin
  11044. {
  11045. For example:
  11046. movzbl %al,%eax
  11047. movzbl (ref),%edx
  11048. andl %edx,%eax
  11049. (%edx deallocated)
  11050. Change to:
  11051. andb (ref),%al
  11052. movzbl %al,%eax
  11053. Rules are:
  11054. - First two instructions have the same opcode and opsize
  11055. - First instruction's operands are the same super-register
  11056. - Second instruction operates on a different register
  11057. - Third instruction is AND, OR, XOR or TEST
  11058. - Third instruction's operands are the destination registers of the first two instructions
  11059. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11060. - Second instruction's destination register is deallocated afterwards
  11061. }
  11062. TransferUsedRegs(TmpUsedRegs);
  11063. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11065. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11066. begin
  11067. case taicpu(p).opsize of
  11068. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11069. NewSize := S_B;
  11070. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11071. NewSize := S_W;
  11072. {$ifdef x86_64}
  11073. S_LQ:
  11074. NewSize := S_L;
  11075. {$endif x86_64}
  11076. else
  11077. InternalError(2021120301);
  11078. end;
  11079. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11080. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11081. taicpu(hp2).opsize := NewSize;
  11082. RemoveInstruction(hp1);
  11083. { With TEST, it's best to keep the MOVX instruction at the top }
  11084. if (taicpu(hp2).opcode <> A_TEST) then
  11085. begin
  11086. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11087. asml.Remove(p);
  11088. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11089. asml.InsertAfter(p, hp2);
  11090. p := hp2;
  11091. end
  11092. else
  11093. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11094. Result := True;
  11095. Exit;
  11096. end;
  11097. end;
  11098. end;
  11099. if taicpu(p).opcode=A_MOVZX then
  11100. begin
  11101. { removes superfluous And's after movzx's }
  11102. if reg_and_hp1_is_instr and
  11103. (taicpu(hp1).opcode = A_AND) and
  11104. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11105. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11106. {$ifdef x86_64}
  11107. { check for implicit extension to 64 bit }
  11108. or
  11109. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11110. (taicpu(hp1).opsize=S_Q) and
  11111. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  11112. )
  11113. {$endif x86_64}
  11114. )
  11115. then
  11116. begin
  11117. case taicpu(p).opsize Of
  11118. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11119. if (taicpu(hp1).oper[0]^.val = $ff) then
  11120. begin
  11121. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  11122. RemoveInstruction(hp1);
  11123. Result:=true;
  11124. exit;
  11125. end;
  11126. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11127. if (taicpu(hp1).oper[0]^.val = $ffff) then
  11128. begin
  11129. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  11130. RemoveInstruction(hp1);
  11131. Result:=true;
  11132. exit;
  11133. end;
  11134. {$ifdef x86_64}
  11135. S_LQ:
  11136. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  11137. begin
  11138. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  11139. RemoveInstruction(hp1);
  11140. Result:=true;
  11141. exit;
  11142. end;
  11143. {$endif x86_64}
  11144. else
  11145. ;
  11146. end;
  11147. { we cannot get rid of the and, but can we get rid of the movz ?}
  11148. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  11149. begin
  11150. case taicpu(p).opsize Of
  11151. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11152. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  11153. begin
  11154. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  11155. RemoveCurrentP(p,hp1);
  11156. Result:=true;
  11157. exit;
  11158. end;
  11159. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11160. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  11161. begin
  11162. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  11163. RemoveCurrentP(p,hp1);
  11164. Result:=true;
  11165. exit;
  11166. end;
  11167. {$ifdef x86_64}
  11168. S_LQ:
  11169. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  11170. begin
  11171. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  11172. RemoveCurrentP(p,hp1);
  11173. Result:=true;
  11174. exit;
  11175. end;
  11176. {$endif x86_64}
  11177. else
  11178. ;
  11179. end;
  11180. end;
  11181. end;
  11182. { changes some movzx constructs to faster synonyms (all examples
  11183. are given with eax/ax, but are also valid for other registers)}
  11184. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11185. begin
  11186. case taicpu(p).opsize of
  11187. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11188. (the machine code is equivalent to movzbl %al,%eax), but the
  11189. code generator still generates that assembler instruction and
  11190. it is silently converted. This should probably be checked.
  11191. [Kit] }
  11192. S_BW:
  11193. begin
  11194. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11195. (
  11196. not IsMOVZXAcceptable
  11197. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11198. or (
  11199. (cs_opt_size in current_settings.optimizerswitches) and
  11200. (taicpu(p).oper[1]^.reg = NR_AX)
  11201. )
  11202. ) then
  11203. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11204. begin
  11205. DebugMsg(SPeepholeOptimization + 'var7',p);
  11206. taicpu(p).opcode := A_AND;
  11207. taicpu(p).changeopsize(S_W);
  11208. taicpu(p).loadConst(0,$ff);
  11209. Result := True;
  11210. end
  11211. else if not IsMOVZXAcceptable and
  11212. GetNextInstruction(p, hp1) and
  11213. (tai(hp1).typ = ait_instruction) and
  11214. (taicpu(hp1).opcode = A_AND) and
  11215. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11216. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11217. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11218. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11219. begin
  11220. DebugMsg(SPeepholeOptimization + 'var8',p);
  11221. taicpu(p).opcode := A_MOV;
  11222. taicpu(p).changeopsize(S_W);
  11223. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11224. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11225. Result := True;
  11226. end;
  11227. end;
  11228. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11229. S_BL:
  11230. if not IsMOVZXAcceptable then
  11231. begin
  11232. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11233. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11234. begin
  11235. DebugMsg(SPeepholeOptimization + 'var9',p);
  11236. taicpu(p).opcode := A_AND;
  11237. taicpu(p).changeopsize(S_L);
  11238. taicpu(p).loadConst(0,$ff);
  11239. Result := True;
  11240. end
  11241. else if GetNextInstruction(p, hp1) and
  11242. (tai(hp1).typ = ait_instruction) and
  11243. (taicpu(hp1).opcode = A_AND) and
  11244. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11245. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11246. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11247. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11248. begin
  11249. DebugMsg(SPeepholeOptimization + 'var10',p);
  11250. taicpu(p).opcode := A_MOV;
  11251. taicpu(p).changeopsize(S_L);
  11252. { do not use R_SUBWHOLE
  11253. as movl %rdx,%eax
  11254. is invalid in assembler PM }
  11255. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11256. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11257. Result := True;
  11258. end;
  11259. end;
  11260. {$endif i8086}
  11261. S_WL:
  11262. if not IsMOVZXAcceptable then
  11263. begin
  11264. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11265. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11266. begin
  11267. DebugMsg(SPeepholeOptimization + 'var11',p);
  11268. taicpu(p).opcode := A_AND;
  11269. taicpu(p).changeopsize(S_L);
  11270. taicpu(p).loadConst(0,$ffff);
  11271. Result := True;
  11272. end
  11273. else if GetNextInstruction(p, hp1) and
  11274. (tai(hp1).typ = ait_instruction) and
  11275. (taicpu(hp1).opcode = A_AND) and
  11276. (taicpu(hp1).oper[0]^.typ = top_const) and
  11277. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11278. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11279. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  11280. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  11281. begin
  11282. DebugMsg(SPeepholeOptimization + 'var12',p);
  11283. taicpu(p).opcode := A_MOV;
  11284. taicpu(p).changeopsize(S_L);
  11285. { do not use R_SUBWHOLE
  11286. as movl %rdx,%eax
  11287. is invalid in assembler PM }
  11288. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11289. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11290. Result := True;
  11291. end;
  11292. end;
  11293. else
  11294. InternalError(2017050705);
  11295. end;
  11296. end
  11297. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  11298. begin
  11299. if GetNextInstruction(p, hp1) and
  11300. (tai(hp1).typ = ait_instruction) and
  11301. (taicpu(hp1).opcode = A_AND) and
  11302. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11303. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11304. begin
  11305. //taicpu(p).opcode := A_MOV;
  11306. case taicpu(p).opsize Of
  11307. S_BL:
  11308. begin
  11309. DebugMsg(SPeepholeOptimization + 'var13',p);
  11310. taicpu(hp1).changeopsize(S_L);
  11311. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11312. end;
  11313. S_WL:
  11314. begin
  11315. DebugMsg(SPeepholeOptimization + 'var14',p);
  11316. taicpu(hp1).changeopsize(S_L);
  11317. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11318. end;
  11319. S_BW:
  11320. begin
  11321. DebugMsg(SPeepholeOptimization + 'var15',p);
  11322. taicpu(hp1).changeopsize(S_W);
  11323. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11324. end;
  11325. else
  11326. Internalerror(2017050704)
  11327. end;
  11328. Result := True;
  11329. end;
  11330. end;
  11331. end;
  11332. end;
  11333. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  11334. var
  11335. hp1, hp2 : tai;
  11336. MaskLength : Cardinal;
  11337. MaskedBits : TCgInt;
  11338. ActiveReg : TRegister;
  11339. begin
  11340. Result:=false;
  11341. { There are no optimisations for reference targets }
  11342. if (taicpu(p).oper[1]^.typ <> top_reg) then
  11343. Exit;
  11344. while GetNextInstruction(p, hp1) and
  11345. (hp1.typ = ait_instruction) do
  11346. begin
  11347. if (taicpu(p).oper[0]^.typ = top_const) then
  11348. begin
  11349. case taicpu(hp1).opcode of
  11350. A_AND:
  11351. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11352. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11353. { the second register must contain the first one, so compare their subreg types }
  11354. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  11355. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  11356. { change
  11357. and const1, reg
  11358. and const2, reg
  11359. to
  11360. and (const1 and const2), reg
  11361. }
  11362. begin
  11363. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  11364. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  11365. RemoveCurrentP(p, hp1);
  11366. Result:=true;
  11367. exit;
  11368. end;
  11369. A_CMP:
  11370. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  11371. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  11372. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11373. { Just check that the condition on the next instruction is compatible }
  11374. GetNextInstruction(hp1, hp2) and
  11375. (hp2.typ = ait_instruction) and
  11376. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  11377. then
  11378. { change
  11379. and 2^n, reg
  11380. cmp 2^n, reg
  11381. j(c) / set(c) / cmov(c) (c is equal or not equal)
  11382. to
  11383. and 2^n, reg
  11384. test reg, reg
  11385. j(~c) / set(~c) / cmov(~c)
  11386. }
  11387. begin
  11388. { Keep TEST instruction in, rather than remove it, because
  11389. it may trigger other optimisations such as MovAndTest2Test }
  11390. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  11391. taicpu(hp1).opcode := A_TEST;
  11392. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  11393. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  11394. Result := True;
  11395. Exit;
  11396. end;
  11397. A_MOVZX:
  11398. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11399. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  11400. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11401. (
  11402. (
  11403. (taicpu(p).opsize=S_W) and
  11404. (taicpu(hp1).opsize=S_BW)
  11405. ) or
  11406. (
  11407. (taicpu(p).opsize=S_L) and
  11408. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11409. )
  11410. {$ifdef x86_64}
  11411. or
  11412. (
  11413. (taicpu(p).opsize=S_Q) and
  11414. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11415. )
  11416. {$endif x86_64}
  11417. ) then
  11418. begin
  11419. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11420. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11421. ) or
  11422. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11423. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11424. then
  11425. begin
  11426. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11427. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11428. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11429. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11430. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11431. }
  11432. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11433. RemoveInstruction(hp1);
  11434. { See if there are other optimisations possible }
  11435. Continue;
  11436. end;
  11437. end;
  11438. A_SHL:
  11439. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11440. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11441. begin
  11442. {$ifopt R+}
  11443. {$define RANGE_WAS_ON}
  11444. {$R-}
  11445. {$endif}
  11446. { get length of potential and mask }
  11447. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11448. { really a mask? }
  11449. {$ifdef RANGE_WAS_ON}
  11450. {$R+}
  11451. {$endif}
  11452. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11453. { unmasked part shifted out? }
  11454. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11455. begin
  11456. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11457. RemoveCurrentP(p, hp1);
  11458. Result:=true;
  11459. exit;
  11460. end;
  11461. end;
  11462. A_SHR:
  11463. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11464. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11465. (taicpu(hp1).oper[0]^.val <= 63) then
  11466. begin
  11467. { Does SHR combined with the AND cover all the bits?
  11468. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11469. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11470. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11471. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11472. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11473. begin
  11474. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11475. RemoveCurrentP(p, hp1);
  11476. Result := True;
  11477. Exit;
  11478. end;
  11479. end;
  11480. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11481. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11482. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11483. begin
  11484. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11485. (
  11486. (
  11487. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11488. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11489. ) or (
  11490. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11491. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11492. {$ifdef x86_64}
  11493. ) or (
  11494. (taicpu(hp1).opsize = S_LQ) and
  11495. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11496. {$endif x86_64}
  11497. )
  11498. ) then
  11499. begin
  11500. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11501. begin
  11502. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11503. RemoveInstruction(hp1);
  11504. { See if there are other optimisations possible }
  11505. Continue;
  11506. end;
  11507. { The super-registers are the same though.
  11508. Note that this change by itself doesn't improve
  11509. code speed, but it opens up other optimisations. }
  11510. {$ifdef x86_64}
  11511. { Convert 64-bit register to 32-bit }
  11512. case taicpu(hp1).opsize of
  11513. S_BQ:
  11514. begin
  11515. taicpu(hp1).opsize := S_BL;
  11516. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11517. end;
  11518. S_WQ:
  11519. begin
  11520. taicpu(hp1).opsize := S_WL;
  11521. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11522. end
  11523. else
  11524. ;
  11525. end;
  11526. {$endif x86_64}
  11527. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11528. taicpu(hp1).opcode := A_MOVZX;
  11529. { See if there are other optimisations possible }
  11530. Continue;
  11531. end;
  11532. end;
  11533. else
  11534. ;
  11535. end;
  11536. end
  11537. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11538. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11539. begin
  11540. {$ifdef x86_64}
  11541. if (taicpu(p).opsize = S_Q) then
  11542. begin
  11543. { Never necessary }
  11544. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11545. RemoveCurrentP(p, hp1);
  11546. Result := True;
  11547. Exit;
  11548. end;
  11549. {$endif x86_64}
  11550. { Forward check to determine necessity of and %reg,%reg }
  11551. TransferUsedRegs(TmpUsedRegs);
  11552. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11553. { Saves on a bunch of dereferences }
  11554. ActiveReg := taicpu(p).oper[1]^.reg;
  11555. case taicpu(hp1).opcode of
  11556. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11557. if (
  11558. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11559. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11560. ) and
  11561. (
  11562. (taicpu(hp1).opcode <> A_MOV) or
  11563. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11564. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11565. ) and
  11566. not (
  11567. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11568. (taicpu(hp1).opcode = A_MOV) and
  11569. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11570. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11571. ) and
  11572. (
  11573. (
  11574. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11575. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11576. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11577. ) or
  11578. (
  11579. {$ifdef x86_64}
  11580. (
  11581. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11582. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11583. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11584. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11585. ) and
  11586. {$endif x86_64}
  11587. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11588. )
  11589. ) then
  11590. begin
  11591. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11592. RemoveCurrentP(p, hp1);
  11593. Result := True;
  11594. Exit;
  11595. end;
  11596. A_ADD,
  11597. A_AND,
  11598. A_BSF,
  11599. A_BSR,
  11600. A_BTC,
  11601. A_BTR,
  11602. A_BTS,
  11603. A_OR,
  11604. A_SUB,
  11605. A_XOR:
  11606. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11607. if (
  11608. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11609. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11610. ) and
  11611. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11612. begin
  11613. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11614. RemoveCurrentP(p, hp1);
  11615. Result := True;
  11616. Exit;
  11617. end;
  11618. A_CMP,
  11619. A_TEST:
  11620. if (
  11621. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11622. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11623. ) and
  11624. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11625. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11626. begin
  11627. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11628. RemoveCurrentP(p, hp1);
  11629. Result := True;
  11630. Exit;
  11631. end;
  11632. A_BSWAP,
  11633. A_NEG,
  11634. A_NOT:
  11635. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11636. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11637. begin
  11638. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11639. RemoveCurrentP(p, hp1);
  11640. Result := True;
  11641. Exit;
  11642. end;
  11643. else
  11644. ;
  11645. end;
  11646. end;
  11647. if (taicpu(hp1).is_jmp) and
  11648. (taicpu(hp1).opcode<>A_JMP) and
  11649. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11650. begin
  11651. { change
  11652. and x, reg
  11653. jxx
  11654. to
  11655. test x, reg
  11656. jxx
  11657. if reg is deallocated before the
  11658. jump, but only if it's a conditional jump (PFV)
  11659. }
  11660. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  11661. taicpu(p).opcode := A_TEST;
  11662. Exit;
  11663. end;
  11664. Break;
  11665. end;
  11666. { Lone AND tests }
  11667. if (taicpu(p).oper[0]^.typ = top_const) then
  11668. begin
  11669. {
  11670. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11671. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11672. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11673. }
  11674. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11675. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11676. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11677. begin
  11678. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11679. if taicpu(p).opsize = S_L then
  11680. begin
  11681. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11682. Result := True;
  11683. end;
  11684. end;
  11685. end;
  11686. { Backward check to determine necessity of and %reg,%reg }
  11687. if (taicpu(p).oper[0]^.typ = top_reg) and
  11688. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11689. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11690. GetLastInstruction(p, hp2) and
  11691. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11692. { Check size of adjacent instruction to determine if the AND is
  11693. effectively a null operation }
  11694. (
  11695. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11696. { Note: Don't include S_Q }
  11697. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11698. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11699. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11700. ) then
  11701. begin
  11702. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11703. { If GetNextInstruction returned False, hp1 will be nil }
  11704. RemoveCurrentP(p, hp1);
  11705. Result := True;
  11706. Exit;
  11707. end;
  11708. end;
  11709. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11710. var
  11711. hp1, hp2: tai;
  11712. NewRef: TReference;
  11713. Distance: Cardinal;
  11714. TempTracking: TAllUsedRegs;
  11715. { This entire nested function is used in an if-statement below, but we
  11716. want to avoid all the used reg transfers and GetNextInstruction calls
  11717. until we really have to check }
  11718. function MemRegisterNotUsedLater: Boolean; inline;
  11719. var
  11720. hp2: tai;
  11721. begin
  11722. TransferUsedRegs(TmpUsedRegs);
  11723. hp2 := p;
  11724. repeat
  11725. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11726. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11727. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11728. end;
  11729. begin
  11730. Result := False;
  11731. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11732. (taicpu(p).oper[1]^.typ = top_reg) then
  11733. begin
  11734. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11735. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11736. (hp1.typ <> ait_instruction) or
  11737. not
  11738. (
  11739. (cs_opt_level3 in current_settings.optimizerswitches) or
  11740. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11741. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11742. ) then
  11743. Exit;
  11744. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11745. addq $x, %rax
  11746. movq %rax, %rdx
  11747. sarq $63, %rdx
  11748. (%rax still in use)
  11749. ...letting OptPass2ADD run its course (and without -Os) will produce:
  11750. leaq $x(%rax),%rdx
  11751. addq $x, %rax
  11752. sarq $63, %rdx
  11753. ...which is okay since it breaks the dependency chain between
  11754. addq and movq, but if OptPass2MOV is called first:
  11755. addq $x, %rax
  11756. cqto
  11757. ...which is better in all ways, taking only 2 cycles to execute
  11758. and much smaller in code size.
  11759. }
  11760. { The extra register tracking is quite strenuous }
  11761. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11762. MatchInstruction(hp1, A_MOV, []) then
  11763. begin
  11764. { Update the register tracking to the MOV instruction }
  11765. CopyUsedRegs(TempTracking);
  11766. hp2 := p;
  11767. repeat
  11768. UpdateUsedRegs(tai(hp2.Next));
  11769. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11770. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11771. OptPass2ADD get called again }
  11772. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11773. begin
  11774. { Reset the tracking to the current instruction }
  11775. RestoreUsedRegs(TempTracking);
  11776. ReleaseUsedRegs(TempTracking);
  11777. Result := True;
  11778. Exit;
  11779. end;
  11780. { Reset the tracking to the current instruction }
  11781. RestoreUsedRegs(TempTracking);
  11782. ReleaseUsedRegs(TempTracking);
  11783. { If OptPass2MOV returned True, we don't need to set Result to
  11784. True if hp1 didn't change because the ADD instruction didn't
  11785. get modified and we'll be evaluating hp1 again when the
  11786. peephole optimizer reaches it }
  11787. end;
  11788. { Change:
  11789. add %reg2,%reg1
  11790. (%reg2 not modified in between)
  11791. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11792. To:
  11793. mov/s/z #(%reg1,%reg2),%reg1
  11794. }
  11795. if (taicpu(p).oper[0]^.typ = top_reg) and
  11796. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11797. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11798. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11799. (
  11800. (
  11801. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11802. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11803. { r/esp cannot be an index }
  11804. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11805. ) or (
  11806. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11807. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11808. )
  11809. ) and (
  11810. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11811. (
  11812. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11813. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11814. MemRegisterNotUsedLater
  11815. )
  11816. ) then
  11817. begin
  11818. if (
  11819. { Instructions are guaranteed to be adjacent on -O2 and under }
  11820. (cs_opt_level3 in current_settings.optimizerswitches) and
  11821. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  11822. ) then
  11823. begin
  11824. { If the other register is used in between, move the MOV
  11825. instruction to right after the ADD instruction so a
  11826. saving can still be made }
  11827. Asml.Remove(hp1);
  11828. Asml.InsertAfter(hp1, p);
  11829. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11830. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11831. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  11832. RemoveCurrentp(p, hp1);
  11833. end
  11834. else
  11835. begin
  11836. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  11837. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11838. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11839. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11840. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11841. { hp1 may not be the immediate next instruction under -O3 }
  11842. RemoveCurrentp(p)
  11843. else
  11844. RemoveCurrentp(p, hp1);
  11845. end;
  11846. Result := True;
  11847. Exit;
  11848. end;
  11849. { Change:
  11850. addl/q $x,%reg1
  11851. movl/q %reg1,%reg2
  11852. To:
  11853. leal/q $x(%reg1),%reg2
  11854. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11855. Breaks the dependency chain.
  11856. }
  11857. if (taicpu(p).oper[0]^.typ = top_const) and
  11858. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11859. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11860. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11861. (
  11862. { Instructions are guaranteed to be adjacent on -O2 and under }
  11863. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11864. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11865. ) then
  11866. begin
  11867. TransferUsedRegs(TmpUsedRegs);
  11868. hp2 := p;
  11869. repeat
  11870. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11871. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11872. if (
  11873. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11874. not (cs_opt_size in current_settings.optimizerswitches) or
  11875. (
  11876. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11877. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11878. )
  11879. ) then
  11880. begin
  11881. { Change the MOV instruction to a LEA instruction, and update the
  11882. first operand }
  11883. reference_reset(NewRef, 1, []);
  11884. NewRef.base := taicpu(p).oper[1]^.reg;
  11885. NewRef.scalefactor := 1;
  11886. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11887. taicpu(hp1).opcode := A_LEA;
  11888. taicpu(hp1).loadref(0, NewRef);
  11889. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11890. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11891. begin
  11892. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11893. { Move what is now the LEA instruction to before the ADD instruction }
  11894. Asml.Remove(hp1);
  11895. Asml.InsertBefore(hp1, p);
  11896. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11897. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11898. p := hp1;
  11899. end
  11900. else
  11901. begin
  11902. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11903. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  11904. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11905. { hp1 may not be the immediate next instruction under -O3 }
  11906. RemoveCurrentp(p)
  11907. else
  11908. RemoveCurrentp(p, hp1);
  11909. end;
  11910. Result := True;
  11911. end;
  11912. end;
  11913. end;
  11914. end;
  11915. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11916. var
  11917. SubReg: TSubRegister;
  11918. begin
  11919. Result:=false;
  11920. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11921. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11922. with taicpu(p).oper[0]^.ref^ do
  11923. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11924. begin
  11925. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11926. begin
  11927. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11928. taicpu(p).opcode := A_ADD;
  11929. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11930. Result := True;
  11931. end
  11932. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11933. begin
  11934. if (base <> NR_NO) then
  11935. begin
  11936. if (scalefactor <= 1) then
  11937. begin
  11938. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11939. taicpu(p).opcode := A_ADD;
  11940. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11941. Result := True;
  11942. end;
  11943. end
  11944. else
  11945. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11946. if (scalefactor in [2, 4, 8]) then
  11947. begin
  11948. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11949. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11950. taicpu(p).opcode := A_SHL;
  11951. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11952. Result := True;
  11953. end;
  11954. end;
  11955. end;
  11956. end;
  11957. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11958. var
  11959. hp1, hp2: tai;
  11960. NewRef: TReference;
  11961. Distance: Cardinal;
  11962. TempTracking: TAllUsedRegs;
  11963. begin
  11964. Result := False;
  11965. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11966. MatchOpType(taicpu(p),top_const,top_reg) then
  11967. begin
  11968. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11969. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11970. (hp1.typ <> ait_instruction) or
  11971. not
  11972. (
  11973. (cs_opt_level3 in current_settings.optimizerswitches) or
  11974. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11975. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11976. ) then
  11977. Exit;
  11978. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11979. subq $x, %rax
  11980. movq %rax, %rdx
  11981. sarq $63, %rdx
  11982. (%rax still in use)
  11983. ...letting OptPass2SUB run its course (and without -Os) will produce:
  11984. leaq $-x(%rax),%rdx
  11985. movq $x, %rax
  11986. sarq $63, %rdx
  11987. ...which is okay since it breaks the dependency chain between
  11988. subq and movq, but if OptPass2MOV is called first:
  11989. subq $x, %rax
  11990. cqto
  11991. ...which is better in all ways, taking only 2 cycles to execute
  11992. and much smaller in code size.
  11993. }
  11994. { The extra register tracking is quite strenuous }
  11995. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11996. MatchInstruction(hp1, A_MOV, []) then
  11997. begin
  11998. { Update the register tracking to the MOV instruction }
  11999. CopyUsedRegs(TempTracking);
  12000. hp2 := p;
  12001. repeat
  12002. UpdateUsedRegs(tai(hp2.Next));
  12003. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12004. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12005. OptPass2SUB get called again }
  12006. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12007. begin
  12008. { Reset the tracking to the current instruction }
  12009. RestoreUsedRegs(TempTracking);
  12010. ReleaseUsedRegs(TempTracking);
  12011. Result := True;
  12012. Exit;
  12013. end;
  12014. { Reset the tracking to the current instruction }
  12015. RestoreUsedRegs(TempTracking);
  12016. ReleaseUsedRegs(TempTracking);
  12017. { If OptPass2MOV returned True, we don't need to set Result to
  12018. True if hp1 didn't change because the SUB instruction didn't
  12019. get modified and we'll be evaluating hp1 again when the
  12020. peephole optimizer reaches it }
  12021. end;
  12022. { Change:
  12023. subl/q $x,%reg1
  12024. movl/q %reg1,%reg2
  12025. To:
  12026. leal/q $-x(%reg1),%reg2
  12027. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12028. Breaks the dependency chain and potentially permits the removal of
  12029. a CMP instruction if one follows.
  12030. }
  12031. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12032. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12033. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12034. (
  12035. { Instructions are guaranteed to be adjacent on -O2 and under }
  12036. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12037. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12038. ) then
  12039. begin
  12040. TransferUsedRegs(TmpUsedRegs);
  12041. hp2 := p;
  12042. repeat
  12043. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12044. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12045. if (
  12046. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12047. not (cs_opt_size in current_settings.optimizerswitches) or
  12048. (
  12049. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12050. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12051. )
  12052. ) then
  12053. begin
  12054. { Change the MOV instruction to a LEA instruction, and update the
  12055. first operand }
  12056. reference_reset(NewRef, 1, []);
  12057. NewRef.base := taicpu(p).oper[1]^.reg;
  12058. NewRef.scalefactor := 1;
  12059. NewRef.offset := -taicpu(p).oper[0]^.val;
  12060. taicpu(hp1).opcode := A_LEA;
  12061. taicpu(hp1).loadref(0, NewRef);
  12062. TransferUsedRegs(TmpUsedRegs);
  12063. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12064. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12065. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12066. begin
  12067. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12068. { Move what is now the LEA instruction to before the SUB instruction }
  12069. Asml.Remove(hp1);
  12070. Asml.InsertBefore(hp1, p);
  12071. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12072. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12073. p := hp1;
  12074. end
  12075. else
  12076. begin
  12077. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12078. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12079. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12080. { hp1 may not be the immediate next instruction under -O3 }
  12081. RemoveCurrentp(p)
  12082. else
  12083. RemoveCurrentp(p, hp1);
  12084. end;
  12085. Result := True;
  12086. end;
  12087. end;
  12088. end;
  12089. end;
  12090. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12091. begin
  12092. { we can skip all instructions not messing with the stack pointer }
  12093. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12094. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12095. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12096. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12097. ({(taicpu(hp1).ops=0) or }
  12098. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12099. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12100. ) and }
  12101. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12102. )
  12103. ) do
  12104. GetNextInstruction(hp1,hp1);
  12105. Result:=assigned(hp1);
  12106. end;
  12107. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12108. var
  12109. hp1, hp2, hp3, hp4, hp5: tai;
  12110. begin
  12111. Result:=false;
  12112. hp5:=nil;
  12113. { replace
  12114. leal(q) x(<stackpointer>),<stackpointer>
  12115. call procname
  12116. leal(q) -x(<stackpointer>),<stackpointer>
  12117. ret
  12118. by
  12119. jmp procname
  12120. but do it only on level 4 because it destroys stack back traces
  12121. }
  12122. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12123. MatchOpType(taicpu(p),top_ref,top_reg) and
  12124. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12125. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  12126. { the -8 or -24 are not required, but bail out early if possible,
  12127. higher values are unlikely }
  12128. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  12129. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  12130. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  12131. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  12132. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12133. GetNextInstruction(p, hp1) and
  12134. { Take a copy of hp1 }
  12135. SetAndTest(hp1, hp4) and
  12136. { trick to skip label }
  12137. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12138. SkipSimpleInstructions(hp1) and
  12139. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12140. GetNextInstruction(hp1, hp2) and
  12141. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  12142. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  12143. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  12144. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12145. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  12146. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  12147. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  12148. { Segment register will be NR_NO }
  12149. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12150. GetNextInstruction(hp2, hp3) and
  12151. { trick to skip label }
  12152. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12153. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12154. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12155. SetAndTest(hp3,hp5) and
  12156. GetNextInstruction(hp3,hp3) and
  12157. MatchInstruction(hp3,A_RET,[S_NO])
  12158. )
  12159. ) and
  12160. (taicpu(hp3).ops=0) then
  12161. begin
  12162. taicpu(hp1).opcode := A_JMP;
  12163. taicpu(hp1).is_jmp := true;
  12164. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  12165. RemoveCurrentP(p, hp4);
  12166. RemoveInstruction(hp2);
  12167. RemoveInstruction(hp3);
  12168. if Assigned(hp5) then
  12169. begin
  12170. AsmL.Remove(hp5);
  12171. ASmL.InsertBefore(hp5,hp1)
  12172. end;
  12173. Result:=true;
  12174. end;
  12175. end;
  12176. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  12177. {$ifdef x86_64}
  12178. var
  12179. hp1, hp2, hp3, hp4, hp5: tai;
  12180. {$endif x86_64}
  12181. begin
  12182. Result:=false;
  12183. {$ifdef x86_64}
  12184. hp5:=nil;
  12185. { replace
  12186. push %rax
  12187. call procname
  12188. pop %rcx
  12189. ret
  12190. by
  12191. jmp procname
  12192. but do it only on level 4 because it destroys stack back traces
  12193. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12194. for all supported calling conventions
  12195. }
  12196. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12197. MatchOpType(taicpu(p),top_reg) and
  12198. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12199. GetNextInstruction(p, hp1) and
  12200. { Take a copy of hp1 }
  12201. SetAndTest(hp1, hp4) and
  12202. { trick to skip label }
  12203. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12204. SkipSimpleInstructions(hp1) and
  12205. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12206. GetNextInstruction(hp1, hp2) and
  12207. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12208. MatchOpType(taicpu(hp2),top_reg) and
  12209. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12210. GetNextInstruction(hp2, hp3) and
  12211. { trick to skip label }
  12212. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12213. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12214. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12215. SetAndTest(hp3,hp5) and
  12216. GetNextInstruction(hp3,hp3) and
  12217. MatchInstruction(hp3,A_RET,[S_NO])
  12218. )
  12219. ) and
  12220. (taicpu(hp3).ops=0) then
  12221. begin
  12222. taicpu(hp1).opcode := A_JMP;
  12223. taicpu(hp1).is_jmp := true;
  12224. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12225. RemoveCurrentP(p, hp4);
  12226. RemoveInstruction(hp2);
  12227. RemoveInstruction(hp3);
  12228. if Assigned(hp5) then
  12229. begin
  12230. AsmL.Remove(hp5);
  12231. ASmL.InsertBefore(hp5,hp1)
  12232. end;
  12233. Result:=true;
  12234. end;
  12235. {$endif x86_64}
  12236. end;
  12237. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12238. var
  12239. Value, RegName: string;
  12240. begin
  12241. Result:=false;
  12242. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12243. begin
  12244. case taicpu(p).oper[0]^.val of
  12245. 0:
  12246. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12247. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12248. begin
  12249. { change "mov $0,%reg" into "xor %reg,%reg" }
  12250. taicpu(p).opcode := A_XOR;
  12251. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12252. Result := True;
  12253. {$ifdef x86_64}
  12254. end
  12255. else if (taicpu(p).opsize = S_Q) then
  12256. begin
  12257. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12258. { The actual optimization }
  12259. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12260. taicpu(p).changeopsize(S_L);
  12261. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12262. Result := True;
  12263. end;
  12264. $1..$FFFFFFFF:
  12265. begin
  12266. { Code size reduction by J. Gareth "Kit" Moreton }
  12267. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  12268. case taicpu(p).opsize of
  12269. S_Q:
  12270. begin
  12271. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12272. Value := debug_tostr(taicpu(p).oper[0]^.val);
  12273. { The actual optimization }
  12274. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12275. taicpu(p).changeopsize(S_L);
  12276. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12277. Result := True;
  12278. end;
  12279. else
  12280. { Do nothing };
  12281. end;
  12282. {$endif x86_64}
  12283. end;
  12284. -1:
  12285. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  12286. if (cs_opt_size in current_settings.optimizerswitches) and
  12287. (taicpu(p).opsize <> S_B) and
  12288. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12289. begin
  12290. { change "mov $-1,%reg" into "or $-1,%reg" }
  12291. { NOTES:
  12292. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  12293. - This operation creates a false dependency on the register, so only do it when optimising for size
  12294. - 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
  12295. }
  12296. taicpu(p).opcode := A_OR;
  12297. Result := True;
  12298. end;
  12299. else
  12300. { Do nothing };
  12301. end;
  12302. end;
  12303. end;
  12304. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  12305. var
  12306. hp1: tai;
  12307. Value: TCGInt;
  12308. begin
  12309. Result := False;
  12310. if MatchOpType(taicpu(p), top_const, top_reg) then
  12311. begin
  12312. { Detect:
  12313. andw x, %ax (0 <= x < $8000)
  12314. ...
  12315. movzwl %ax,%eax
  12316. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12317. }
  12318. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  12319. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  12320. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  12321. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  12322. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  12323. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  12324. begin
  12325. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  12326. taicpu(hp1).opcode := A_CWDE;
  12327. taicpu(hp1).clearop(0);
  12328. taicpu(hp1).clearop(1);
  12329. taicpu(hp1).ops := 0;
  12330. { A change was made, but not with p, so move forward 1 }
  12331. p := tai(p.Next);
  12332. Result := True;
  12333. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  12334. end;
  12335. { If "not x" is a power of 2 (popcnt = 1), change:
  12336. and $x, %reg/ref
  12337. To:
  12338. btr lb(x), %reg/ref
  12339. }
  12340. if
  12341. {$ifndef x86_64}
  12342. (
  12343. (cs_opt_size in current_settings.optimizerswitches) or
  12344. { BTR takes more than 1 cycle on earlier processors }
  12345. (current_settings.optimizecputype >= cpu_Pentium2)
  12346. ) and
  12347. {$endif not x86_64}
  12348. { For sizes less than S_L, the byte size is equal or larger with BT,
  12349. so don't bother optimising }
  12350. (taicpu(p).opsize >= S_L) and
  12351. { "btx $x,mem" is unacceptably slow, but oper[1] being top_reg is already checked }
  12352. (
  12353. { If the value can bit into an 8-bit signed integer, a smaller
  12354. instruction can be encded with OR, so don't optimise if it falls
  12355. within this range }
  12356. (taicpu(p).oper[0]^.val < -128) or
  12357. (taicpu(p).oper[0]^.val >= 127)
  12358. ) and
  12359. (
  12360. { Make sure a TEST doesn't follow that plays with the register }
  12361. not GetNextInstruction(p, hp1) or
  12362. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  12363. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  12364. ) then
  12365. begin
  12366. {$push}{$R-}{$Q-}
  12367. { Value is a sign-extended 32-bit integer - just correct it
  12368. if it's represented as an unsigned value }
  12369. Value := not taicpu(p).oper[0]^.val;
  12370. {$pop}
  12371. {$ifdef x86_64}
  12372. if taicpu(p).opsize = S_L then
  12373. {$endif x86_64}
  12374. Value := Value and $FFFFFFFF;
  12375. if (PopCnt(QWord(Value)) = 1) then
  12376. begin
  12377. DebugMsg(SPeepholeOptimization + 'Changed AND (not $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ') to BTR ' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  12378. taicpu(p).opcode := A_BTR;
  12379. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  12380. Result := True;
  12381. Exit;
  12382. end;
  12383. end;
  12384. end;
  12385. end;
  12386. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  12387. begin
  12388. Result := False;
  12389. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  12390. Exit;
  12391. { Convert:
  12392. movswl %ax,%eax -> cwtl
  12393. movslq %eax,%rax -> cdqe
  12394. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  12395. refer to the same opcode and depends only on the assembler's
  12396. current operand-size attribute. [Kit]
  12397. }
  12398. with taicpu(p) do
  12399. case opsize of
  12400. S_WL:
  12401. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  12402. begin
  12403. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  12404. opcode := A_CWDE;
  12405. clearop(0);
  12406. clearop(1);
  12407. ops := 0;
  12408. Result := True;
  12409. end;
  12410. {$ifdef x86_64}
  12411. S_LQ:
  12412. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  12413. begin
  12414. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  12415. opcode := A_CDQE;
  12416. clearop(0);
  12417. clearop(1);
  12418. ops := 0;
  12419. Result := True;
  12420. end;
  12421. {$endif x86_64}
  12422. else
  12423. ;
  12424. end;
  12425. end;
  12426. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  12427. var
  12428. hp1, hp2: tai;
  12429. IdentityMask, Shift: TCGInt;
  12430. LimitSize: Topsize;
  12431. DoNotMerge: Boolean;
  12432. begin
  12433. Result := False;
  12434. { All these optimisations work on "shr const,%reg" }
  12435. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12436. Exit;
  12437. DoNotMerge := False;
  12438. Shift := taicpu(p).oper[0]^.val;
  12439. LimitSize := taicpu(p).opsize;
  12440. hp1 := p;
  12441. repeat
  12442. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  12443. Break;
  12444. { Detect:
  12445. shr x, %reg
  12446. and y, %reg
  12447. If and y, %reg doesn't actually change the value of %reg (e.g. with
  12448. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  12449. }
  12450. case taicpu(hp1).opcode of
  12451. A_AND:
  12452. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12453. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12454. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12455. begin
  12456. { Make sure the FLAGS register isn't in use }
  12457. TransferUsedRegs(TmpUsedRegs);
  12458. hp2 := p;
  12459. repeat
  12460. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12461. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12462. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12463. begin
  12464. { Generate the identity mask }
  12465. case taicpu(p).opsize of
  12466. S_B:
  12467. IdentityMask := $FF shr Shift;
  12468. S_W:
  12469. IdentityMask := $FFFF shr Shift;
  12470. S_L:
  12471. IdentityMask := $FFFFFFFF shr Shift;
  12472. {$ifdef x86_64}
  12473. S_Q:
  12474. { We need to force the operands to be unsigned 64-bit
  12475. integers otherwise the wrong value is generated }
  12476. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  12477. {$endif x86_64}
  12478. else
  12479. InternalError(2022081501);
  12480. end;
  12481. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  12482. begin
  12483. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  12484. { All the possible 1 bits are covered, so we can remove the AND }
  12485. hp2 := tai(hp1.Previous);
  12486. RemoveInstruction(hp1);
  12487. { p wasn't actually changed, so don't set Result to True,
  12488. but a change was nonetheless made elsewhere }
  12489. Include(OptsToCheck, aoc_ForceNewIteration);
  12490. { Do another pass in case other AND or MOVZX instructions
  12491. follow }
  12492. hp1 := hp2;
  12493. Continue;
  12494. end;
  12495. end;
  12496. end;
  12497. A_TEST, A_CMP, A_Jcc:
  12498. { Skip over conditional jumps and relevant comparisons }
  12499. Continue;
  12500. A_MOVZX:
  12501. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12502. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  12503. begin
  12504. { Since the original register is being read as is, subsequent
  12505. SHRs must not be merged at this point }
  12506. DoNotMerge := True;
  12507. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  12508. begin
  12509. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12510. begin
  12511. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  12512. { All the possible 1 bits are covered, so we can remove the AND }
  12513. hp2 := tai(hp1.Previous);
  12514. RemoveInstruction(hp1);
  12515. hp1 := hp2;
  12516. end
  12517. else { Different register target }
  12518. begin
  12519. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  12520. taicpu(hp1).opcode := A_MOV;
  12521. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  12522. case taicpu(hp1).opsize of
  12523. S_BW:
  12524. taicpu(hp1).opsize := S_W;
  12525. S_BL, S_WL:
  12526. taicpu(hp1).opsize := S_L;
  12527. else
  12528. InternalError(2022081503);
  12529. end;
  12530. end;
  12531. end
  12532. else if (Shift > 0) and
  12533. (taicpu(p).opsize = S_W) and
  12534. (taicpu(hp1).opsize = S_WL) and
  12535. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  12536. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  12537. begin
  12538. { Detect:
  12539. shr x, %ax (x > 0)
  12540. ...
  12541. movzwl %ax,%eax
  12542. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12543. }
  12544. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  12545. taicpu(hp1).opcode := A_CWDE;
  12546. taicpu(hp1).clearop(0);
  12547. taicpu(hp1).clearop(1);
  12548. taicpu(hp1).ops := 0;
  12549. end;
  12550. { Move onto the next instruction }
  12551. Continue;
  12552. end;
  12553. A_SHL, A_SAL, A_SHR:
  12554. if (taicpu(hp1).opsize <= LimitSize) and
  12555. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12556. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12557. begin
  12558. { Make sure the sizes don't exceed the register size limit
  12559. (measured by the shift value falling below the limit) }
  12560. if taicpu(hp1).opsize < LimitSize then
  12561. LimitSize := taicpu(hp1).opsize;
  12562. if taicpu(hp1).opcode = A_SHR then
  12563. Inc(Shift, taicpu(hp1).oper[0]^.val)
  12564. else
  12565. begin
  12566. Dec(Shift, taicpu(hp1).oper[0]^.val);
  12567. DoNotMerge := True;
  12568. end;
  12569. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  12570. Break;
  12571. { Since we've established that the combined shift is within
  12572. limits, we can actually combine the adjacent SHR
  12573. instructions even if they're different sizes }
  12574. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  12575. begin
  12576. hp2 := tai(hp1.Previous);
  12577. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  12578. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  12579. RemoveInstruction(hp1);
  12580. hp1 := hp2;
  12581. end;
  12582. { Move onto the next instruction }
  12583. Continue;
  12584. end;
  12585. else
  12586. ;
  12587. end;
  12588. Break;
  12589. until False;
  12590. { Detect the following (looking backwards):
  12591. shr %cl,%reg
  12592. shr x, %reg
  12593. Swap the two SHR instructions to minimise a pipeline stall.
  12594. }
  12595. if GetLastInstruction(p, hp1) and
  12596. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  12597. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12598. { First operand will be %cl }
  12599. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12600. { Just to be sure }
  12601. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  12602. begin
  12603. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  12604. { Moving the entries this way ensures the register tracking remains correct }
  12605. Asml.Remove(p);
  12606. Asml.InsertBefore(p, hp1);
  12607. p := hp1;
  12608. { Don't set Result to True because the current instruction is now
  12609. "shr %cl,%reg" and there's nothing more we can do with it }
  12610. end;
  12611. end;
  12612. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  12613. var
  12614. hp1, hp2: tai;
  12615. Opposite, SecondOpposite: TAsmOp;
  12616. NewCond: TAsmCond;
  12617. begin
  12618. Result := False;
  12619. { Change:
  12620. add/sub 128,(dest)
  12621. To:
  12622. sub/add -128,(dest)
  12623. This generaally takes fewer bytes to encode because -128 can be stored
  12624. in a signed byte, whereas +128 cannot.
  12625. }
  12626. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  12627. begin
  12628. if taicpu(p).opcode = A_ADD then
  12629. Opposite := A_SUB
  12630. else
  12631. Opposite := A_ADD;
  12632. { Be careful if the flags are in use, because the CF flag inverts
  12633. when changing from ADD to SUB and vice versa }
  12634. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12635. GetNextInstruction(p, hp1) then
  12636. begin
  12637. TransferUsedRegs(TmpUsedRegs);
  12638. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  12639. hp2 := hp1;
  12640. { Scan ahead to check if everything's safe }
  12641. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  12642. begin
  12643. if (hp1.typ <> ait_instruction) then
  12644. { Probably unsafe since the flags are still in use }
  12645. Exit;
  12646. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  12647. { Stop searching at an unconditional jump }
  12648. Break;
  12649. if not
  12650. (
  12651. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  12652. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  12653. ) and
  12654. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  12655. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  12656. Exit;
  12657. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12658. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  12659. { Move to the next instruction }
  12660. GetNextInstruction(hp1, hp1);
  12661. end;
  12662. while Assigned(hp2) and (hp2 <> hp1) do
  12663. begin
  12664. NewCond := C_None;
  12665. case taicpu(hp2).condition of
  12666. C_A, C_NBE:
  12667. NewCond := C_BE;
  12668. C_B, C_C, C_NAE:
  12669. NewCond := C_AE;
  12670. C_AE, C_NB, C_NC:
  12671. NewCond := C_B;
  12672. C_BE, C_NA:
  12673. NewCond := C_A;
  12674. else
  12675. { No change needed };
  12676. end;
  12677. if NewCond <> C_None then
  12678. begin
  12679. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  12680. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  12681. taicpu(hp2).condition := NewCond;
  12682. end
  12683. else
  12684. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  12685. begin
  12686. { Because of the flipping of the carry bit, to ensure
  12687. the operation remains equivalent, ADC becomes SBB
  12688. and vice versa, and the constant is not-inverted.
  12689. If multiple ADCs or SBBs appear in a row, each one
  12690. changed causes the carry bit to invert, so they all
  12691. need to be flipped }
  12692. if taicpu(hp2).opcode = A_ADC then
  12693. SecondOpposite := A_SBB
  12694. else
  12695. SecondOpposite := A_ADC;
  12696. if taicpu(hp2).oper[0]^.typ <> top_const then
  12697. { Should have broken out of this optimisation already }
  12698. InternalError(2021112901);
  12699. 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]^) + ' -> ' +
  12700. 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);
  12701. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  12702. taicpu(hp2).opcode := SecondOpposite;
  12703. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  12704. end;
  12705. { Move to the next instruction }
  12706. GetNextInstruction(hp2, hp2);
  12707. end;
  12708. if (hp2 <> hp1) then
  12709. InternalError(2021111501);
  12710. end;
  12711. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  12712. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  12713. taicpu(p).opcode := Opposite;
  12714. taicpu(p).oper[0]^.val := -128;
  12715. { No further optimisations can be made on this instruction, so move
  12716. onto the next one to save time }
  12717. p := tai(p.Next);
  12718. UpdateUsedRegs(p);
  12719. Result := True;
  12720. Exit;
  12721. end;
  12722. { Detect:
  12723. add/sub %reg2,(dest)
  12724. add/sub x, (dest)
  12725. (dest can be a register or a reference)
  12726. Swap the instructions to minimise a pipeline stall. This reverses the
  12727. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  12728. optimisations could be made.
  12729. }
  12730. if (taicpu(p).oper[0]^.typ = top_reg) and
  12731. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  12732. (
  12733. (
  12734. (taicpu(p).oper[1]^.typ = top_reg) and
  12735. { We can try searching further ahead if we're writing to a register }
  12736. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  12737. ) or
  12738. (
  12739. (taicpu(p).oper[1]^.typ = top_ref) and
  12740. GetNextInstruction(p, hp1)
  12741. )
  12742. ) and
  12743. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  12744. (taicpu(hp1).oper[0]^.typ = top_const) and
  12745. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  12746. begin
  12747. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  12748. TransferUsedRegs(TmpUsedRegs);
  12749. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12750. hp2 := p;
  12751. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  12752. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  12753. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  12754. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12755. begin
  12756. asml.remove(hp1);
  12757. asml.InsertBefore(hp1, p);
  12758. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  12759. Result := True;
  12760. end;
  12761. end;
  12762. end;
  12763. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  12764. begin
  12765. Result:=false;
  12766. { change "cmp $0, %reg" to "test %reg, %reg" }
  12767. if MatchOpType(taicpu(p),top_const,top_reg) and
  12768. (taicpu(p).oper[0]^.val = 0) then
  12769. begin
  12770. taicpu(p).opcode := A_TEST;
  12771. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  12772. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  12773. Result:=true;
  12774. end;
  12775. end;
  12776. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  12777. var
  12778. IsTestConstX, IsValid : Boolean;
  12779. hp1,hp2 : tai;
  12780. begin
  12781. Result:=false;
  12782. { If x is a power of 2 (popcnt = 1), change:
  12783. or $x, %reg/ref
  12784. To:
  12785. bts lb(x), %reg/ref
  12786. }
  12787. if (taicpu(p).opcode = A_OR) and
  12788. {$ifndef x86_64}
  12789. (
  12790. (cs_opt_size in current_settings.optimizerswitches) or
  12791. { BTS takes more than 1 cycle on earlier processors }
  12792. (current_settings.optimizecputype >= cpu_Pentium2)
  12793. ) and
  12794. {$endif not x86_64}
  12795. MatchOpType(taicpu(p), top_const, top_reg) and { "btx $x,mem" is unacceptably slow }
  12796. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  12797. { For sizes less than S_L, the byte size is equal or larger with BT,
  12798. so don't bother optimising }
  12799. (taicpu(p).opsize >= S_L) and
  12800. (
  12801. { If the value can bit into an 8-bit signed integer, a smaller
  12802. instruction can be encded with OR, so don't optimise if it falls
  12803. within this range }
  12804. (taicpu(p).oper[0]^.val < -128) or
  12805. (taicpu(p).oper[0]^.val >= 127)
  12806. ) and
  12807. (
  12808. { Don't optimise if a test instruction follows }
  12809. not GetNextInstruction(p, hp1) or
  12810. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  12811. ) then
  12812. begin
  12813. DebugMsg(SPeepholeOptimization + 'Changed OR $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BTS ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  12814. taicpu(p).opcode := A_BTS;
  12815. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  12816. Result := True;
  12817. Exit;
  12818. end;
  12819. { If x is a power of 2 (popcnt = 1), change:
  12820. test $x, %reg/ref
  12821. je / sete / cmove (or jne / setne)
  12822. To:
  12823. bt lb(x), %reg/ref
  12824. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  12825. }
  12826. if (taicpu(p).opcode = A_TEST) and
  12827. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  12828. (taicpu(p).oper[0]^.typ = top_const) and
  12829. (
  12830. (cs_opt_size in current_settings.optimizerswitches) or
  12831. (
  12832. (taicpu(p).oper[1]^.typ = top_reg) and
  12833. (CPUX86_HAS_FAST_BTX in cpu_capabilities[current_settings.optimizecputype])
  12834. ) or
  12835. (
  12836. (taicpu(p).oper[1]^.typ <> top_reg) and
  12837. (CPUX86_HAS_FAST_BT_MEM in cpu_capabilities[current_settings.optimizecputype])
  12838. )
  12839. ) and
  12840. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  12841. { For sizes less than S_L, the byte size is equal or larger with BT,
  12842. so don't bother optimising }
  12843. (taicpu(p).opsize >= S_L) then
  12844. begin
  12845. IsValid := True;
  12846. { Check the next set of instructions, watching the FLAGS register
  12847. and the conditions used }
  12848. TransferUsedRegs(TmpUsedRegs);
  12849. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12850. hp1 := p;
  12851. hp2 := nil;
  12852. while GetNextInstruction(hp1, hp1) do
  12853. begin
  12854. if not Assigned(hp2) then
  12855. { The first instruction after TEST }
  12856. hp2 := hp1;
  12857. if (hp1.typ <> ait_instruction) then
  12858. begin
  12859. { If the flags are no longer in use, everything is fine }
  12860. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12861. IsValid := False;
  12862. Break;
  12863. end;
  12864. case taicpu(hp1).condition of
  12865. C_None:
  12866. begin
  12867. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12868. { Something is not quite normal, so play safe and don't change }
  12869. IsValid := False;
  12870. Break;
  12871. end;
  12872. C_E, C_Z, C_NE, C_NZ:
  12873. { This is fine };
  12874. else
  12875. begin
  12876. { Unsupported condition }
  12877. IsValid := False;
  12878. Break;
  12879. end;
  12880. end;
  12881. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12882. end;
  12883. if IsValid then
  12884. begin
  12885. while hp2 <> hp1 do
  12886. begin
  12887. case taicpu(hp2).condition of
  12888. C_Z, C_E:
  12889. taicpu(hp2).condition := C_NC;
  12890. C_NZ, C_NE:
  12891. taicpu(hp2).condition := C_C;
  12892. else
  12893. { Should not get this by this point }
  12894. InternalError(2022110701);
  12895. end;
  12896. GetNextInstruction(hp2, hp2);
  12897. end;
  12898. DebugMsg(SPeepholeOptimization + 'Changed TEST $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BT ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  12899. taicpu(p).opcode := A_BT;
  12900. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  12901. Result := True;
  12902. Exit;
  12903. end;
  12904. end;
  12905. { removes the line marked with (x) from the sequence
  12906. and/or/xor/add/sub/... $x, %y
  12907. test/or %y, %y | test $-1, %y (x)
  12908. j(n)z _Label
  12909. as the first instruction already adjusts the ZF
  12910. %y operand may also be a reference }
  12911. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  12912. MatchOperand(taicpu(p).oper[0]^,-1);
  12913. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  12914. GetLastInstruction(p, hp1) and
  12915. (tai(hp1).typ = ait_instruction) and
  12916. GetNextInstruction(p,hp2) and
  12917. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  12918. case taicpu(hp1).opcode Of
  12919. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  12920. { These two instructions set the zero flag if the result is zero }
  12921. A_POPCNT, A_LZCNT:
  12922. begin
  12923. if (
  12924. { With POPCNT, an input of zero will set the zero flag
  12925. because the population count of zero is zero }
  12926. (taicpu(hp1).opcode = A_POPCNT) and
  12927. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  12928. (
  12929. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  12930. { Faster than going through the second half of the 'or'
  12931. condition below }
  12932. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  12933. )
  12934. ) or (
  12935. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  12936. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12937. { and in case of carry for A(E)/B(E)/C/NC }
  12938. (
  12939. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  12940. (
  12941. (taicpu(hp1).opcode <> A_ADD) and
  12942. (taicpu(hp1).opcode <> A_SUB) and
  12943. (taicpu(hp1).opcode <> A_LZCNT)
  12944. )
  12945. )
  12946. ) then
  12947. begin
  12948. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  12949. RemoveCurrentP(p, hp2);
  12950. Result:=true;
  12951. Exit;
  12952. end;
  12953. end;
  12954. A_SHL, A_SAL, A_SHR, A_SAR:
  12955. begin
  12956. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  12957. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  12958. { therefore, it's only safe to do this optimization for }
  12959. { shifts by a (nonzero) constant }
  12960. (taicpu(hp1).oper[0]^.typ = top_const) and
  12961. (taicpu(hp1).oper[0]^.val <> 0) and
  12962. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12963. { and in case of carry for A(E)/B(E)/C/NC }
  12964. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12965. begin
  12966. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  12967. RemoveCurrentP(p, hp2);
  12968. Result:=true;
  12969. Exit;
  12970. end;
  12971. end;
  12972. A_DEC, A_INC, A_NEG:
  12973. begin
  12974. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  12975. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12976. { and in case of carry for A(E)/B(E)/C/NC }
  12977. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12978. begin
  12979. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  12980. RemoveCurrentP(p, hp2);
  12981. Result:=true;
  12982. Exit;
  12983. end;
  12984. end;
  12985. A_ANDN, A_BZHI:
  12986. begin
  12987. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  12988. { Only the zero and sign flags are consistent with what the result is }
  12989. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  12990. begin
  12991. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  12992. RemoveCurrentP(p, hp2);
  12993. Result:=true;
  12994. Exit;
  12995. end;
  12996. end;
  12997. A_BEXTR:
  12998. begin
  12999. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13000. { Only the zero flag is set }
  13001. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13002. begin
  13003. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13004. RemoveCurrentP(p, hp2);
  13005. Result:=true;
  13006. Exit;
  13007. end;
  13008. end;
  13009. else
  13010. ;
  13011. end; { case }
  13012. { change "test $-1,%reg" into "test %reg,%reg" }
  13013. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13014. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13015. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13016. if MatchInstruction(p, A_OR, []) and
  13017. { Can only match if they're both registers }
  13018. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13019. begin
  13020. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13021. taicpu(p).opcode := A_TEST;
  13022. { No need to set Result to True, as we've done all the optimisations we can }
  13023. end;
  13024. end;
  13025. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13026. var
  13027. hp1,hp3 : tai;
  13028. {$ifndef x86_64}
  13029. hp2 : taicpu;
  13030. {$endif x86_64}
  13031. begin
  13032. Result:=false;
  13033. hp3:=nil;
  13034. {$ifndef x86_64}
  13035. { don't do this on modern CPUs, this really hurts them due to
  13036. broken call/ret pairing }
  13037. if (current_settings.optimizecputype < cpu_Pentium2) and
  13038. not(cs_create_pic in current_settings.moduleswitches) and
  13039. GetNextInstruction(p, hp1) and
  13040. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13041. MatchOpType(taicpu(hp1),top_ref) and
  13042. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13043. begin
  13044. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  13045. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13046. InsertLLItem(p.previous, p, hp2);
  13047. taicpu(p).opcode := A_JMP;
  13048. taicpu(p).is_jmp := true;
  13049. RemoveInstruction(hp1);
  13050. Result:=true;
  13051. end
  13052. else
  13053. {$endif x86_64}
  13054. { replace
  13055. call procname
  13056. ret
  13057. by
  13058. jmp procname
  13059. but do it only on level 4 because it destroys stack back traces
  13060. else if the subroutine is marked as no return, remove the ret
  13061. }
  13062. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  13063. (po_noreturn in current_procinfo.procdef.procoptions)) and
  13064. GetNextInstruction(p, hp1) and
  13065. (MatchInstruction(hp1,A_RET,[S_NO]) or
  13066. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  13067. SetAndTest(hp1,hp3) and
  13068. GetNextInstruction(hp1,hp1) and
  13069. MatchInstruction(hp1,A_RET,[S_NO])
  13070. )
  13071. ) and
  13072. (taicpu(hp1).ops=0) then
  13073. begin
  13074. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13075. { we might destroy stack alignment here if we do not do a call }
  13076. (target_info.stackalign<=sizeof(SizeUInt)) then
  13077. begin
  13078. taicpu(p).opcode := A_JMP;
  13079. taicpu(p).is_jmp := true;
  13080. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  13081. end
  13082. else
  13083. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  13084. RemoveInstruction(hp1);
  13085. if Assigned(hp3) then
  13086. begin
  13087. AsmL.Remove(hp3);
  13088. AsmL.InsertBefore(hp3,p)
  13089. end;
  13090. Result:=true;
  13091. end;
  13092. end;
  13093. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  13094. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  13095. begin
  13096. case OpSize of
  13097. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13098. Result := (Val <= $FF) and (Val >= -128);
  13099. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13100. Result := (Val <= $FFFF) and (Val >= -32768);
  13101. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  13102. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  13103. else
  13104. Result := True;
  13105. end;
  13106. end;
  13107. var
  13108. hp1, hp2 : tai;
  13109. SizeChange: Boolean;
  13110. PreMessage: string;
  13111. begin
  13112. Result := False;
  13113. if (taicpu(p).oper[0]^.typ = top_reg) and
  13114. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13115. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  13116. begin
  13117. { Change (using movzbl %al,%eax as an example):
  13118. movzbl %al, %eax movzbl %al, %eax
  13119. cmpl x, %eax testl %eax,%eax
  13120. To:
  13121. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  13122. movzbl %al, %eax movzbl %al, %eax
  13123. Smaller instruction and minimises pipeline stall as the CPU
  13124. doesn't have to wait for the register to get zero-extended. [Kit]
  13125. Also allow if the smaller of the two registers is being checked,
  13126. as this still removes the false dependency.
  13127. }
  13128. if
  13129. (
  13130. (
  13131. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  13132. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  13133. ) or (
  13134. { If MatchOperand returns True, they must both be registers }
  13135. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  13136. )
  13137. ) and
  13138. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  13139. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  13140. begin
  13141. 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);
  13142. asml.Remove(hp1);
  13143. asml.InsertBefore(hp1, p);
  13144. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  13145. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  13146. begin
  13147. taicpu(hp1).opcode := A_TEST;
  13148. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  13149. end;
  13150. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13151. case taicpu(p).opsize of
  13152. S_BW, S_BL:
  13153. begin
  13154. SizeChange := taicpu(hp1).opsize <> S_B;
  13155. taicpu(hp1).changeopsize(S_B);
  13156. end;
  13157. S_WL:
  13158. begin
  13159. SizeChange := taicpu(hp1).opsize <> S_W;
  13160. taicpu(hp1).changeopsize(S_W);
  13161. end
  13162. else
  13163. InternalError(2020112701);
  13164. end;
  13165. UpdateUsedRegs(tai(p.Next));
  13166. { Check if the register is used aferwards - if not, we can
  13167. remove the movzx instruction completely }
  13168. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  13169. begin
  13170. { Hp1 is a better position than p for debugging purposes }
  13171. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  13172. RemoveCurrentp(p, hp1);
  13173. Result := True;
  13174. end;
  13175. if SizeChange then
  13176. DebugMsg(SPeepholeOptimization + PreMessage +
  13177. 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)
  13178. else
  13179. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  13180. Exit;
  13181. end;
  13182. { Change (using movzwl %ax,%eax as an example):
  13183. movzwl %ax, %eax
  13184. movb %al, (dest) (Register is smaller than read register in movz)
  13185. To:
  13186. movb %al, (dest) (Move one back to avoid a false dependency)
  13187. movzwl %ax, %eax
  13188. }
  13189. if (taicpu(hp1).opcode = A_MOV) and
  13190. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13191. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  13192. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  13193. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  13194. begin
  13195. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  13196. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  13197. asml.Remove(hp1);
  13198. asml.InsertBefore(hp1, p);
  13199. if taicpu(hp1).oper[1]^.typ = top_reg then
  13200. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13201. { Check if the register is used aferwards - if not, we can
  13202. remove the movzx instruction completely }
  13203. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  13204. begin
  13205. { Hp1 is a better position than p for debugging purposes }
  13206. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  13207. RemoveCurrentp(p, hp1);
  13208. Result := True;
  13209. end;
  13210. Exit;
  13211. end;
  13212. end;
  13213. end;
  13214. {$ifdef x86_64}
  13215. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  13216. var
  13217. PreMessage, RegName: string;
  13218. begin
  13219. { Code size reduction by J. Gareth "Kit" Moreton }
  13220. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  13221. as this removes the REX prefix }
  13222. Result := False;
  13223. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  13224. Exit;
  13225. if taicpu(p).oper[0]^.typ <> top_reg then
  13226. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  13227. InternalError(2018011500);
  13228. case taicpu(p).opsize of
  13229. S_Q:
  13230. begin
  13231. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  13232. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  13233. { The actual optimization }
  13234. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13235. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13236. taicpu(p).changeopsize(S_L);
  13237. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  13238. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  13239. end;
  13240. else
  13241. ;
  13242. end;
  13243. end;
  13244. {$endif}
  13245. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  13246. var
  13247. XReg: TRegister;
  13248. begin
  13249. Result := False;
  13250. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  13251. Smaller encoding and slightly faster on some platforms (also works for
  13252. ZMM-sized registers) }
  13253. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  13254. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  13255. begin
  13256. XReg := taicpu(p).oper[0]^.reg;
  13257. if (taicpu(p).oper[1]^.reg = XReg) then
  13258. begin
  13259. taicpu(p).changeopsize(S_XMM);
  13260. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  13261. if (cs_opt_size in current_settings.optimizerswitches) then
  13262. begin
  13263. { Change input registers to %xmm0 to reduce size. Note that
  13264. there's a risk of a false dependency doing this, so only
  13265. optimise for size here }
  13266. XReg := NR_XMM0;
  13267. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  13268. end
  13269. else
  13270. begin
  13271. setsubreg(XReg, R_SUBMMX);
  13272. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  13273. end;
  13274. taicpu(p).oper[0]^.reg := XReg;
  13275. taicpu(p).oper[1]^.reg := XReg;
  13276. Result := True;
  13277. end;
  13278. end;
  13279. end;
  13280. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  13281. var
  13282. OperIdx: Integer;
  13283. begin
  13284. for OperIdx := 0 to p.ops - 1 do
  13285. if p.oper[OperIdx]^.typ = top_ref then
  13286. optimize_ref(p.oper[OperIdx]^.ref^, False);
  13287. end;
  13288. end.